babylon.viewer.max.js 5.4 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167
  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. */
  7386. Curve3.CreateCatmullRomSpline = function (points, nbPoints) {
  7387. var totalPoints = new Array();
  7388. totalPoints.push(points[0].clone());
  7389. Array.prototype.push.apply(totalPoints, points);
  7390. totalPoints.push(points[points.length - 1].clone());
  7391. var catmullRom = new Array();
  7392. var step = 1.0 / nbPoints;
  7393. var amount = 0.0;
  7394. for (var i = 0; i < totalPoints.length - 3; i++) {
  7395. amount = 0;
  7396. for (var c = 0; c < nbPoints; c++) {
  7397. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7398. amount += step;
  7399. }
  7400. }
  7401. i--;
  7402. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7403. return new Curve3(catmullRom);
  7404. };
  7405. /**
  7406. * Returns the Curve3 stored array of successive Vector3
  7407. */
  7408. Curve3.prototype.getPoints = function () {
  7409. return this._points;
  7410. };
  7411. /**
  7412. * Returns the computed length (float) of the curve.
  7413. */
  7414. Curve3.prototype.length = function () {
  7415. return this._length;
  7416. };
  7417. /**
  7418. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7419. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7420. * curveA and curveB keep unchanged.
  7421. */
  7422. Curve3.prototype.continue = function (curve) {
  7423. var lastPoint = this._points[this._points.length - 1];
  7424. var continuedPoints = this._points.slice();
  7425. var curvePoints = curve.getPoints();
  7426. for (var i = 1; i < curvePoints.length; i++) {
  7427. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7428. }
  7429. var continuedCurve = new Curve3(continuedPoints);
  7430. return continuedCurve;
  7431. };
  7432. Curve3.prototype._computeLength = function (path) {
  7433. var l = 0;
  7434. for (var i = 1; i < path.length; i++) {
  7435. l += (path[i].subtract(path[i - 1])).length();
  7436. }
  7437. return l;
  7438. };
  7439. return Curve3;
  7440. }());
  7441. BABYLON.Curve3 = Curve3;
  7442. // Vertex formats
  7443. var PositionNormalVertex = /** @class */ (function () {
  7444. function PositionNormalVertex(position, normal) {
  7445. if (position === void 0) { position = Vector3.Zero(); }
  7446. if (normal === void 0) { normal = Vector3.Up(); }
  7447. this.position = position;
  7448. this.normal = normal;
  7449. }
  7450. PositionNormalVertex.prototype.clone = function () {
  7451. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7452. };
  7453. return PositionNormalVertex;
  7454. }());
  7455. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7456. var PositionNormalTextureVertex = /** @class */ (function () {
  7457. function PositionNormalTextureVertex(position, normal, uv) {
  7458. if (position === void 0) { position = Vector3.Zero(); }
  7459. if (normal === void 0) { normal = Vector3.Up(); }
  7460. if (uv === void 0) { uv = Vector2.Zero(); }
  7461. this.position = position;
  7462. this.normal = normal;
  7463. this.uv = uv;
  7464. }
  7465. PositionNormalTextureVertex.prototype.clone = function () {
  7466. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7467. };
  7468. return PositionNormalTextureVertex;
  7469. }());
  7470. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7471. // Temporary pre-allocated objects for engine internal use
  7472. // usage in any internal function :
  7473. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7474. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7475. var Tmp = /** @class */ (function () {
  7476. function Tmp() {
  7477. }
  7478. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7479. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7480. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7481. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7482. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7483. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7484. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7485. Matrix.Zero(), Matrix.Zero(),
  7486. Matrix.Zero(), Matrix.Zero(),
  7487. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7488. return Tmp;
  7489. }());
  7490. BABYLON.Tmp = Tmp;
  7491. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7492. var MathTmp = /** @class */ (function () {
  7493. function MathTmp() {
  7494. }
  7495. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7496. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7497. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7498. return MathTmp;
  7499. }());
  7500. })(BABYLON || (BABYLON = {}));
  7501. //# sourceMappingURL=babylon.math.js.map
  7502. var BABYLON;
  7503. (function (BABYLON) {
  7504. var Scalar = /** @class */ (function () {
  7505. function Scalar() {
  7506. }
  7507. /**
  7508. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7509. */
  7510. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7511. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7512. var num = a - b;
  7513. return -epsilon <= num && num <= epsilon;
  7514. };
  7515. /**
  7516. * Returns a string : the upper case translation of the number i to hexadecimal.
  7517. */
  7518. Scalar.ToHex = function (i) {
  7519. var str = i.toString(16);
  7520. if (i <= 15) {
  7521. return ("0" + str).toUpperCase();
  7522. }
  7523. return str.toUpperCase();
  7524. };
  7525. /**
  7526. * Returns -1 if value is negative and +1 is value is positive.
  7527. * Returns the value itself if it's equal to zero.
  7528. */
  7529. Scalar.Sign = function (value) {
  7530. value = +value; // convert to a number
  7531. if (value === 0 || isNaN(value))
  7532. return value;
  7533. return value > 0 ? 1 : -1;
  7534. };
  7535. /**
  7536. * Returns the value itself if it's between min and max.
  7537. * Returns min if the value is lower than min.
  7538. * Returns max if the value is greater than max.
  7539. */
  7540. Scalar.Clamp = function (value, min, max) {
  7541. if (min === void 0) { min = 0; }
  7542. if (max === void 0) { max = 1; }
  7543. return Math.min(max, Math.max(min, value));
  7544. };
  7545. /**
  7546. * Returns the log2 of value.
  7547. */
  7548. Scalar.Log2 = function (value) {
  7549. return Math.log(value) * Math.LOG2E;
  7550. };
  7551. /**
  7552. * Loops the value, so that it is never larger than length and never smaller than 0.
  7553. *
  7554. * This is similar to the modulo operator but it works with floating point numbers.
  7555. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7556. * With t = 5 and length = 2.5, the result would be 0.0.
  7557. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7558. */
  7559. Scalar.Repeat = function (value, length) {
  7560. return value - Math.floor(value / length) * length;
  7561. };
  7562. /**
  7563. * Normalize the value between 0.0 and 1.0 using min and max values
  7564. */
  7565. Scalar.Normalize = function (value, min, max) {
  7566. return (value - min) / (max - min);
  7567. };
  7568. /**
  7569. * Denormalize the value from 0.0 and 1.0 using min and max values
  7570. */
  7571. Scalar.Denormalize = function (normalized, min, max) {
  7572. return (normalized * (max - min) + min);
  7573. };
  7574. /**
  7575. * Calculates the shortest difference between two given angles given in degrees.
  7576. */
  7577. Scalar.DeltaAngle = function (current, target) {
  7578. var num = Scalar.Repeat(target - current, 360.0);
  7579. if (num > 180.0) {
  7580. num -= 360.0;
  7581. }
  7582. return num;
  7583. };
  7584. /**
  7585. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7586. *
  7587. * The returned value will move back and forth between 0 and length
  7588. */
  7589. Scalar.PingPong = function (tx, length) {
  7590. var t = Scalar.Repeat(tx, length * 2.0);
  7591. return length - Math.abs(t - length);
  7592. };
  7593. /**
  7594. * Interpolates between min and max with smoothing at the limits.
  7595. *
  7596. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7597. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7598. */
  7599. Scalar.SmoothStep = function (from, to, tx) {
  7600. var t = Scalar.Clamp(tx);
  7601. t = -2.0 * t * t * t + 3.0 * t * t;
  7602. return to * t + from * (1.0 - t);
  7603. };
  7604. /**
  7605. * Moves a value current towards target.
  7606. *
  7607. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7608. * Negative values of maxDelta pushes the value away from target.
  7609. */
  7610. Scalar.MoveTowards = function (current, target, maxDelta) {
  7611. var result = 0;
  7612. if (Math.abs(target - current) <= maxDelta) {
  7613. result = target;
  7614. }
  7615. else {
  7616. result = current + Scalar.Sign(target - current) * maxDelta;
  7617. }
  7618. return result;
  7619. };
  7620. /**
  7621. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7622. *
  7623. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7624. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7625. */
  7626. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7627. var num = Scalar.DeltaAngle(current, target);
  7628. var result = 0;
  7629. if (-maxDelta < num && num < maxDelta) {
  7630. result = target;
  7631. }
  7632. else {
  7633. target = current + num;
  7634. result = Scalar.MoveTowards(current, target, maxDelta);
  7635. }
  7636. return result;
  7637. };
  7638. /**
  7639. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7640. */
  7641. Scalar.Lerp = function (start, end, amount) {
  7642. return start + ((end - start) * amount);
  7643. };
  7644. /**
  7645. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7646. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7647. */
  7648. Scalar.LerpAngle = function (start, end, amount) {
  7649. var num = Scalar.Repeat(end - start, 360.0);
  7650. if (num > 180.0) {
  7651. num -= 360.0;
  7652. }
  7653. return start + num * Scalar.Clamp(amount);
  7654. };
  7655. /**
  7656. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7657. */
  7658. Scalar.InverseLerp = function (a, b, value) {
  7659. var result = 0;
  7660. if (a != b) {
  7661. result = Scalar.Clamp((value - a) / (b - a));
  7662. }
  7663. else {
  7664. result = 0.0;
  7665. }
  7666. return result;
  7667. };
  7668. /**
  7669. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7670. */
  7671. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7672. var squared = amount * amount;
  7673. var cubed = amount * squared;
  7674. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7675. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7676. var part3 = (cubed - (2.0 * squared)) + amount;
  7677. var part4 = cubed - squared;
  7678. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7679. };
  7680. /**
  7681. * Returns a random float number between and min and max values
  7682. */
  7683. Scalar.RandomRange = function (min, max) {
  7684. if (min === max)
  7685. return min;
  7686. return ((Math.random() * (max - min)) + min);
  7687. };
  7688. /**
  7689. * This function returns percentage of a number in a given range.
  7690. *
  7691. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7692. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7693. */
  7694. Scalar.RangeToPercent = function (number, min, max) {
  7695. return ((number - min) / (max - min));
  7696. };
  7697. /**
  7698. * This function returns number that corresponds to the percentage in a given range.
  7699. *
  7700. * PercentToRange(0.34,0,100) will return 34.
  7701. */
  7702. Scalar.PercentToRange = function (percent, min, max) {
  7703. return ((max - min) * percent + min);
  7704. };
  7705. /**
  7706. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7707. * @param angle The angle to normalize in radian.
  7708. * @return The converted angle.
  7709. */
  7710. Scalar.NormalizeRadians = function (angle) {
  7711. // More precise but slower version kept for reference.
  7712. // angle = angle % Tools.TwoPi;
  7713. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7714. //if (angle > Math.PI) {
  7715. // angle -= Tools.TwoPi;
  7716. //}
  7717. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7718. return angle;
  7719. };
  7720. /**
  7721. * Two pi constants convenient for computation.
  7722. */
  7723. Scalar.TwoPi = Math.PI * 2;
  7724. return Scalar;
  7725. }());
  7726. BABYLON.Scalar = Scalar;
  7727. })(BABYLON || (BABYLON = {}));
  7728. //# sourceMappingURL=babylon.math.scalar.js.map
  7729. //# sourceMappingURL=babylon.mixins.js.map
  7730. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7731. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7732. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7733. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7734. //# sourceMappingURL=babylon.webgl2.js.map
  7735. var BABYLON;
  7736. (function (BABYLON) {
  7737. var __decoratorInitialStore = {};
  7738. var __mergedStore = {};
  7739. var _copySource = function (creationFunction, source, instanciate) {
  7740. var destination = creationFunction();
  7741. // Tags
  7742. if (BABYLON.Tags) {
  7743. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7744. }
  7745. var classStore = getMergedStore(destination);
  7746. // Properties
  7747. for (var property in classStore) {
  7748. var propertyDescriptor = classStore[property];
  7749. var sourceProperty = source[property];
  7750. var propertyType = propertyDescriptor.type;
  7751. if (sourceProperty !== undefined && sourceProperty !== null) {
  7752. switch (propertyType) {
  7753. case 0: // Value
  7754. case 6: // Mesh reference
  7755. case 11: // Camera reference
  7756. destination[property] = sourceProperty;
  7757. break;
  7758. case 1: // Texture
  7759. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7760. break;
  7761. case 2: // Color3
  7762. case 3: // FresnelParameters
  7763. case 4: // Vector2
  7764. case 5: // Vector3
  7765. case 7: // Color Curves
  7766. case 10: // Quaternion
  7767. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7768. break;
  7769. }
  7770. }
  7771. }
  7772. return destination;
  7773. };
  7774. function getDirectStore(target) {
  7775. var classKey = target.getClassName();
  7776. if (!__decoratorInitialStore[classKey]) {
  7777. __decoratorInitialStore[classKey] = {};
  7778. }
  7779. return __decoratorInitialStore[classKey];
  7780. }
  7781. /**
  7782. * Return the list of properties flagged as serializable
  7783. * @param target: host object
  7784. */
  7785. function getMergedStore(target) {
  7786. var classKey = target.getClassName();
  7787. if (__mergedStore[classKey]) {
  7788. return __mergedStore[classKey];
  7789. }
  7790. __mergedStore[classKey] = {};
  7791. var store = __mergedStore[classKey];
  7792. var currentTarget = target;
  7793. var currentKey = classKey;
  7794. while (currentKey) {
  7795. var initialStore = __decoratorInitialStore[currentKey];
  7796. for (var property in initialStore) {
  7797. store[property] = initialStore[property];
  7798. }
  7799. var parent_1 = void 0;
  7800. var done = false;
  7801. do {
  7802. parent_1 = Object.getPrototypeOf(currentTarget);
  7803. if (!parent_1.getClassName) {
  7804. done = true;
  7805. break;
  7806. }
  7807. if (parent_1.getClassName() !== currentKey) {
  7808. break;
  7809. }
  7810. currentTarget = parent_1;
  7811. } while (parent_1);
  7812. if (done) {
  7813. break;
  7814. }
  7815. currentKey = parent_1.getClassName();
  7816. currentTarget = parent_1;
  7817. }
  7818. return store;
  7819. }
  7820. function generateSerializableMember(type, sourceName) {
  7821. return function (target, propertyKey) {
  7822. var classStore = getDirectStore(target);
  7823. if (!classStore[propertyKey]) {
  7824. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7825. }
  7826. };
  7827. }
  7828. function generateExpandMember(setCallback, targetKey) {
  7829. if (targetKey === void 0) { targetKey = null; }
  7830. return function (target, propertyKey) {
  7831. var key = targetKey || ("_" + propertyKey);
  7832. Object.defineProperty(target, propertyKey, {
  7833. get: function () {
  7834. return this[key];
  7835. },
  7836. set: function (value) {
  7837. if (this[key] === value) {
  7838. return;
  7839. }
  7840. this[key] = value;
  7841. target[setCallback].apply(this);
  7842. },
  7843. enumerable: true,
  7844. configurable: true
  7845. });
  7846. };
  7847. }
  7848. function expandToProperty(callback, targetKey) {
  7849. if (targetKey === void 0) { targetKey = null; }
  7850. return generateExpandMember(callback, targetKey);
  7851. }
  7852. BABYLON.expandToProperty = expandToProperty;
  7853. function serialize(sourceName) {
  7854. return generateSerializableMember(0, sourceName); // value member
  7855. }
  7856. BABYLON.serialize = serialize;
  7857. function serializeAsTexture(sourceName) {
  7858. return generateSerializableMember(1, sourceName); // texture member
  7859. }
  7860. BABYLON.serializeAsTexture = serializeAsTexture;
  7861. function serializeAsColor3(sourceName) {
  7862. return generateSerializableMember(2, sourceName); // color3 member
  7863. }
  7864. BABYLON.serializeAsColor3 = serializeAsColor3;
  7865. function serializeAsFresnelParameters(sourceName) {
  7866. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7867. }
  7868. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7869. function serializeAsVector2(sourceName) {
  7870. return generateSerializableMember(4, sourceName); // vector2 member
  7871. }
  7872. BABYLON.serializeAsVector2 = serializeAsVector2;
  7873. function serializeAsVector3(sourceName) {
  7874. return generateSerializableMember(5, sourceName); // vector3 member
  7875. }
  7876. BABYLON.serializeAsVector3 = serializeAsVector3;
  7877. function serializeAsMeshReference(sourceName) {
  7878. return generateSerializableMember(6, sourceName); // mesh reference member
  7879. }
  7880. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7881. function serializeAsColorCurves(sourceName) {
  7882. return generateSerializableMember(7, sourceName); // color curves
  7883. }
  7884. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7885. function serializeAsColor4(sourceName) {
  7886. return generateSerializableMember(8, sourceName); // color 4
  7887. }
  7888. BABYLON.serializeAsColor4 = serializeAsColor4;
  7889. function serializeAsImageProcessingConfiguration(sourceName) {
  7890. return generateSerializableMember(9, sourceName); // image processing
  7891. }
  7892. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7893. function serializeAsQuaternion(sourceName) {
  7894. return generateSerializableMember(10, sourceName); // quaternion member
  7895. }
  7896. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7897. /**
  7898. * Decorator used to define property that can be serialized as reference to a camera
  7899. * @param sourceName defines the name of the property to decorate
  7900. */
  7901. function serializeAsCameraReference(sourceName) {
  7902. return generateSerializableMember(11, sourceName); // camera reference member
  7903. }
  7904. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7905. var SerializationHelper = /** @class */ (function () {
  7906. function SerializationHelper() {
  7907. }
  7908. SerializationHelper.Serialize = function (entity, serializationObject) {
  7909. if (!serializationObject) {
  7910. serializationObject = {};
  7911. }
  7912. // Tags
  7913. if (BABYLON.Tags) {
  7914. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7915. }
  7916. var serializedProperties = getMergedStore(entity);
  7917. // Properties
  7918. for (var property in serializedProperties) {
  7919. var propertyDescriptor = serializedProperties[property];
  7920. var targetPropertyName = propertyDescriptor.sourceName || property;
  7921. var propertyType = propertyDescriptor.type;
  7922. var sourceProperty = entity[property];
  7923. if (sourceProperty !== undefined && sourceProperty !== null) {
  7924. switch (propertyType) {
  7925. case 0: // Value
  7926. serializationObject[targetPropertyName] = sourceProperty;
  7927. break;
  7928. case 1: // Texture
  7929. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7930. break;
  7931. case 2: // Color3
  7932. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7933. break;
  7934. case 3: // FresnelParameters
  7935. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7936. break;
  7937. case 4: // Vector2
  7938. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7939. break;
  7940. case 5: // Vector3
  7941. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7942. break;
  7943. case 6: // Mesh reference
  7944. serializationObject[targetPropertyName] = sourceProperty.id;
  7945. break;
  7946. case 7: // Color Curves
  7947. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7948. break;
  7949. case 8: // Color 4
  7950. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7951. break;
  7952. case 9: // Image Processing
  7953. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7954. break;
  7955. case 10: // Quaternion
  7956. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7957. break;
  7958. case 11: // Camera reference
  7959. serializationObject[targetPropertyName] = sourceProperty.id;
  7960. break;
  7961. }
  7962. }
  7963. }
  7964. return serializationObject;
  7965. };
  7966. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7967. if (rootUrl === void 0) { rootUrl = null; }
  7968. var destination = creationFunction();
  7969. if (!rootUrl) {
  7970. rootUrl = "";
  7971. }
  7972. // Tags
  7973. if (BABYLON.Tags) {
  7974. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7975. }
  7976. var classStore = getMergedStore(destination);
  7977. // Properties
  7978. for (var property in classStore) {
  7979. var propertyDescriptor = classStore[property];
  7980. var sourceProperty = source[propertyDescriptor.sourceName || property];
  7981. var propertyType = propertyDescriptor.type;
  7982. if (sourceProperty !== undefined && sourceProperty !== null) {
  7983. var dest = destination;
  7984. switch (propertyType) {
  7985. case 0: // Value
  7986. dest[property] = sourceProperty;
  7987. break;
  7988. case 1: // Texture
  7989. if (scene) {
  7990. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  7991. }
  7992. break;
  7993. case 2: // Color3
  7994. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  7995. break;
  7996. case 3: // FresnelParameters
  7997. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  7998. break;
  7999. case 4: // Vector2
  8000. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8001. break;
  8002. case 5: // Vector3
  8003. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8004. break;
  8005. case 6: // Mesh reference
  8006. if (scene) {
  8007. dest[property] = scene.getLastMeshByID(sourceProperty);
  8008. }
  8009. break;
  8010. case 7: // Color Curves
  8011. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8012. break;
  8013. case 8: // Color 4
  8014. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8015. break;
  8016. case 9: // Image Processing
  8017. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8018. break;
  8019. case 10: // Quaternion
  8020. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8021. break;
  8022. case 11: // Camera reference
  8023. if (scene) {
  8024. dest[property] = scene.getCameraByID(sourceProperty);
  8025. }
  8026. break;
  8027. }
  8028. }
  8029. }
  8030. return destination;
  8031. };
  8032. SerializationHelper.Clone = function (creationFunction, source) {
  8033. return _copySource(creationFunction, source, false);
  8034. };
  8035. SerializationHelper.Instanciate = function (creationFunction, source) {
  8036. return _copySource(creationFunction, source, true);
  8037. };
  8038. return SerializationHelper;
  8039. }());
  8040. BABYLON.SerializationHelper = SerializationHelper;
  8041. })(BABYLON || (BABYLON = {}));
  8042. //# sourceMappingURL=babylon.decorators.js.map
  8043. var BABYLON;
  8044. (function (BABYLON) {
  8045. /**
  8046. * Wrapper class for promise with external resolve and reject.
  8047. */
  8048. var Deferred = /** @class */ (function () {
  8049. /**
  8050. * Constructor for this deferred object.
  8051. */
  8052. function Deferred() {
  8053. var _this = this;
  8054. this.promise = new Promise(function (resolve, reject) {
  8055. _this._resolve = resolve;
  8056. _this._reject = reject;
  8057. });
  8058. }
  8059. Object.defineProperty(Deferred.prototype, "resolve", {
  8060. /**
  8061. * The resolve method of the promise associated with this deferred object.
  8062. */
  8063. get: function () {
  8064. return this._resolve;
  8065. },
  8066. enumerable: true,
  8067. configurable: true
  8068. });
  8069. Object.defineProperty(Deferred.prototype, "reject", {
  8070. /**
  8071. * The reject method of the promise associated with this deferred object.
  8072. */
  8073. get: function () {
  8074. return this._reject;
  8075. },
  8076. enumerable: true,
  8077. configurable: true
  8078. });
  8079. return Deferred;
  8080. }());
  8081. BABYLON.Deferred = Deferred;
  8082. })(BABYLON || (BABYLON = {}));
  8083. //# sourceMappingURL=babylon.deferred.js.map
  8084. var BABYLON;
  8085. (function (BABYLON) {
  8086. /**
  8087. * A class serves as a medium between the observable and its observers
  8088. */
  8089. var EventState = /** @class */ (function () {
  8090. /**
  8091. * Create a new EventState
  8092. * @param mask defines the mask associated with this state
  8093. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8094. * @param target defines the original target of the state
  8095. * @param currentTarget defines the current target of the state
  8096. */
  8097. function EventState(mask, skipNextObservers, target, currentTarget) {
  8098. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8099. this.initalize(mask, skipNextObservers, target, currentTarget);
  8100. }
  8101. /**
  8102. * Initialize the current event state
  8103. * @param mask defines the mask associated with this state
  8104. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8105. * @param target defines the original target of the state
  8106. * @param currentTarget defines the current target of the state
  8107. * @returns the current event state
  8108. */
  8109. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8110. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8111. this.mask = mask;
  8112. this.skipNextObservers = skipNextObservers;
  8113. this.target = target;
  8114. this.currentTarget = currentTarget;
  8115. return this;
  8116. };
  8117. return EventState;
  8118. }());
  8119. BABYLON.EventState = EventState;
  8120. /**
  8121. * Represent an Observer registered to a given Observable object.
  8122. */
  8123. var Observer = /** @class */ (function () {
  8124. /**
  8125. * Creates a new observer
  8126. * @param callback defines the callback to call when the observer is notified
  8127. * @param mask defines the mask of the observer (used to filter notifications)
  8128. * @param scope defines the current scope used to restore the JS context
  8129. */
  8130. function Observer(
  8131. /**
  8132. * Defines the callback to call when the observer is notified
  8133. */
  8134. callback,
  8135. /**
  8136. * Defines the mask of the observer (used to filter notifications)
  8137. */
  8138. mask,
  8139. /**
  8140. * Defines the current scope used to restore the JS context
  8141. */
  8142. scope) {
  8143. if (scope === void 0) { scope = null; }
  8144. this.callback = callback;
  8145. this.mask = mask;
  8146. this.scope = scope;
  8147. /** @hidden */
  8148. this._willBeUnregistered = false;
  8149. /**
  8150. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8151. */
  8152. this.unregisterOnNextCall = false;
  8153. }
  8154. return Observer;
  8155. }());
  8156. BABYLON.Observer = Observer;
  8157. /**
  8158. * Represent a list of observers registered to multiple Observables object.
  8159. */
  8160. var MultiObserver = /** @class */ (function () {
  8161. function MultiObserver() {
  8162. }
  8163. /**
  8164. * Release associated resources
  8165. */
  8166. MultiObserver.prototype.dispose = function () {
  8167. if (this._observers && this._observables) {
  8168. for (var index = 0; index < this._observers.length; index++) {
  8169. this._observables[index].remove(this._observers[index]);
  8170. }
  8171. }
  8172. this._observers = null;
  8173. this._observables = null;
  8174. };
  8175. /**
  8176. * Raise a callback when one of the observable will notify
  8177. * @param observables defines a list of observables to watch
  8178. * @param callback defines the callback to call on notification
  8179. * @param mask defines the mask used to filter notifications
  8180. * @param scope defines the current scope used to restore the JS context
  8181. * @returns the new MultiObserver
  8182. */
  8183. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8184. if (mask === void 0) { mask = -1; }
  8185. if (scope === void 0) { scope = null; }
  8186. var result = new MultiObserver();
  8187. result._observers = new Array();
  8188. result._observables = observables;
  8189. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8190. var observable = observables_1[_i];
  8191. var observer = observable.add(callback, mask, false, scope);
  8192. if (observer) {
  8193. result._observers.push(observer);
  8194. }
  8195. }
  8196. return result;
  8197. };
  8198. return MultiObserver;
  8199. }());
  8200. BABYLON.MultiObserver = MultiObserver;
  8201. /**
  8202. * The Observable class is a simple implementation of the Observable pattern.
  8203. *
  8204. * 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.
  8205. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8206. * 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).
  8207. * 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.
  8208. */
  8209. var Observable = /** @class */ (function () {
  8210. /**
  8211. * Creates a new observable
  8212. * @param onObserverAdded defines a callback to call when a new observer is added
  8213. */
  8214. function Observable(onObserverAdded) {
  8215. this._observers = new Array();
  8216. this._eventState = new EventState(0);
  8217. if (onObserverAdded) {
  8218. this._onObserverAdded = onObserverAdded;
  8219. }
  8220. }
  8221. /**
  8222. * Create a new Observer with the specified callback
  8223. * @param callback the callback that will be executed for that Observer
  8224. * @param mask the mask used to filter observers
  8225. * @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.
  8226. * @param scope optional scope for the callback to be called from
  8227. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8228. * @returns the new observer created for the callback
  8229. */
  8230. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8231. if (mask === void 0) { mask = -1; }
  8232. if (insertFirst === void 0) { insertFirst = false; }
  8233. if (scope === void 0) { scope = null; }
  8234. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8235. if (!callback) {
  8236. return null;
  8237. }
  8238. var observer = new Observer(callback, mask, scope);
  8239. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8240. if (insertFirst) {
  8241. this._observers.unshift(observer);
  8242. }
  8243. else {
  8244. this._observers.push(observer);
  8245. }
  8246. if (this._onObserverAdded) {
  8247. this._onObserverAdded(observer);
  8248. }
  8249. return observer;
  8250. };
  8251. /**
  8252. * Remove an Observer from the Observable object
  8253. * @param observer the instance of the Observer to remove
  8254. * @returns false if it doesn't belong to this Observable
  8255. */
  8256. Observable.prototype.remove = function (observer) {
  8257. if (!observer) {
  8258. return false;
  8259. }
  8260. var index = this._observers.indexOf(observer);
  8261. if (index !== -1) {
  8262. this._observers.splice(index, 1);
  8263. return true;
  8264. }
  8265. return false;
  8266. };
  8267. /**
  8268. * Remove a callback from the Observable object
  8269. * @param callback the callback to remove
  8270. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8271. * @returns false if it doesn't belong to this Observable
  8272. */
  8273. Observable.prototype.removeCallback = function (callback, scope) {
  8274. for (var index = 0; index < this._observers.length; index++) {
  8275. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8276. this._observers.splice(index, 1);
  8277. return true;
  8278. }
  8279. }
  8280. return false;
  8281. };
  8282. Observable.prototype._deferUnregister = function (observer) {
  8283. var _this = this;
  8284. observer.unregisterOnNextCall = false;
  8285. observer._willBeUnregistered = true;
  8286. BABYLON.Tools.SetImmediate(function () {
  8287. _this.remove(observer);
  8288. });
  8289. };
  8290. /**
  8291. * Notify all Observers by calling their respective callback with the given data
  8292. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8293. * @param eventData defines the data to send to all observers
  8294. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8295. * @param target defines the original target of the state
  8296. * @param currentTarget defines the current target of the state
  8297. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8298. */
  8299. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8300. if (mask === void 0) { mask = -1; }
  8301. if (!this._observers.length) {
  8302. return true;
  8303. }
  8304. var state = this._eventState;
  8305. state.mask = mask;
  8306. state.target = target;
  8307. state.currentTarget = currentTarget;
  8308. state.skipNextObservers = false;
  8309. state.lastReturnValue = eventData;
  8310. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8311. var obs = _a[_i];
  8312. if (obs._willBeUnregistered) {
  8313. continue;
  8314. }
  8315. if (obs.mask & mask) {
  8316. if (obs.scope) {
  8317. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8318. }
  8319. else {
  8320. state.lastReturnValue = obs.callback(eventData, state);
  8321. }
  8322. if (obs.unregisterOnNextCall) {
  8323. this._deferUnregister(obs);
  8324. }
  8325. }
  8326. if (state.skipNextObservers) {
  8327. return false;
  8328. }
  8329. }
  8330. return true;
  8331. };
  8332. /**
  8333. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8334. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8335. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8336. * and it is crucial that all callbacks will be executed.
  8337. * The order of the callbacks is kept, callbacks are not executed parallel.
  8338. *
  8339. * @param eventData The data to be sent to each callback
  8340. * @param mask is used to filter observers defaults to -1
  8341. * @param target defines the callback target (see EventState)
  8342. * @param currentTarget defines he current object in the bubbling phase
  8343. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8344. */
  8345. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8346. var _this = this;
  8347. if (mask === void 0) { mask = -1; }
  8348. // create an empty promise
  8349. var p = Promise.resolve(eventData);
  8350. // no observers? return this promise.
  8351. if (!this._observers.length) {
  8352. return p;
  8353. }
  8354. var state = this._eventState;
  8355. state.mask = mask;
  8356. state.target = target;
  8357. state.currentTarget = currentTarget;
  8358. state.skipNextObservers = false;
  8359. // execute one callback after another (not using Promise.all, the order is important)
  8360. this._observers.forEach(function (obs) {
  8361. if (state.skipNextObservers) {
  8362. return;
  8363. }
  8364. if (obs._willBeUnregistered) {
  8365. return;
  8366. }
  8367. if (obs.mask & mask) {
  8368. if (obs.scope) {
  8369. p = p.then(function (lastReturnedValue) {
  8370. state.lastReturnValue = lastReturnedValue;
  8371. return obs.callback.apply(obs.scope, [eventData, state]);
  8372. });
  8373. }
  8374. else {
  8375. p = p.then(function (lastReturnedValue) {
  8376. state.lastReturnValue = lastReturnedValue;
  8377. return obs.callback(eventData, state);
  8378. });
  8379. }
  8380. if (obs.unregisterOnNextCall) {
  8381. _this._deferUnregister(obs);
  8382. }
  8383. }
  8384. });
  8385. // return the eventData
  8386. return p.then(function () { return eventData; });
  8387. };
  8388. /**
  8389. * Notify a specific observer
  8390. * @param observer defines the observer to notify
  8391. * @param eventData defines the data to be sent to each callback
  8392. * @param mask is used to filter observers defaults to -1
  8393. */
  8394. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8395. if (mask === void 0) { mask = -1; }
  8396. var state = this._eventState;
  8397. state.mask = mask;
  8398. state.skipNextObservers = false;
  8399. observer.callback(eventData, state);
  8400. };
  8401. /**
  8402. * Gets a boolean indicating if the observable has at least one observer
  8403. * @returns true is the Observable has at least one Observer registered
  8404. */
  8405. Observable.prototype.hasObservers = function () {
  8406. return this._observers.length > 0;
  8407. };
  8408. /**
  8409. * Clear the list of observers
  8410. */
  8411. Observable.prototype.clear = function () {
  8412. this._observers = new Array();
  8413. this._onObserverAdded = null;
  8414. };
  8415. /**
  8416. * Clone the current observable
  8417. * @returns a new observable
  8418. */
  8419. Observable.prototype.clone = function () {
  8420. var result = new Observable();
  8421. result._observers = this._observers.slice(0);
  8422. return result;
  8423. };
  8424. /**
  8425. * Does this observable handles observer registered with a given mask
  8426. * @param mask defines the mask to be tested
  8427. * @return whether or not one observer registered with the given mask is handeled
  8428. **/
  8429. Observable.prototype.hasSpecificMask = function (mask) {
  8430. if (mask === void 0) { mask = -1; }
  8431. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8432. var obs = _a[_i];
  8433. if (obs.mask & mask || obs.mask === mask) {
  8434. return true;
  8435. }
  8436. }
  8437. return false;
  8438. };
  8439. return Observable;
  8440. }());
  8441. BABYLON.Observable = Observable;
  8442. })(BABYLON || (BABYLON = {}));
  8443. //# sourceMappingURL=babylon.observable.js.map
  8444. var BABYLON;
  8445. (function (BABYLON) {
  8446. var SmartArray = /** @class */ (function () {
  8447. function SmartArray(capacity) {
  8448. this.length = 0;
  8449. this.data = new Array(capacity);
  8450. this._id = SmartArray._GlobalId++;
  8451. }
  8452. SmartArray.prototype.push = function (value) {
  8453. this.data[this.length++] = value;
  8454. if (this.length > this.data.length) {
  8455. this.data.length *= 2;
  8456. }
  8457. };
  8458. SmartArray.prototype.forEach = function (func) {
  8459. for (var index = 0; index < this.length; index++) {
  8460. func(this.data[index]);
  8461. }
  8462. };
  8463. SmartArray.prototype.sort = function (compareFn) {
  8464. this.data.sort(compareFn);
  8465. };
  8466. SmartArray.prototype.reset = function () {
  8467. this.length = 0;
  8468. };
  8469. SmartArray.prototype.dispose = function () {
  8470. this.reset();
  8471. if (this.data) {
  8472. this.data.length = 0;
  8473. this.data = [];
  8474. }
  8475. };
  8476. SmartArray.prototype.concat = function (array) {
  8477. if (array.length === 0) {
  8478. return;
  8479. }
  8480. if (this.length + array.length > this.data.length) {
  8481. this.data.length = (this.length + array.length) * 2;
  8482. }
  8483. for (var index = 0; index < array.length; index++) {
  8484. this.data[this.length++] = (array.data || array)[index];
  8485. }
  8486. };
  8487. SmartArray.prototype.indexOf = function (value) {
  8488. var position = this.data.indexOf(value);
  8489. if (position >= this.length) {
  8490. return -1;
  8491. }
  8492. return position;
  8493. };
  8494. SmartArray.prototype.contains = function (value) {
  8495. return this.data.indexOf(value) !== -1;
  8496. };
  8497. // Statics
  8498. SmartArray._GlobalId = 0;
  8499. return SmartArray;
  8500. }());
  8501. BABYLON.SmartArray = SmartArray;
  8502. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8503. __extends(SmartArrayNoDuplicate, _super);
  8504. function SmartArrayNoDuplicate() {
  8505. var _this = _super !== null && _super.apply(this, arguments) || this;
  8506. _this._duplicateId = 0;
  8507. return _this;
  8508. }
  8509. SmartArrayNoDuplicate.prototype.push = function (value) {
  8510. _super.prototype.push.call(this, value);
  8511. if (!value.__smartArrayFlags) {
  8512. value.__smartArrayFlags = {};
  8513. }
  8514. value.__smartArrayFlags[this._id] = this._duplicateId;
  8515. };
  8516. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8517. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8518. return false;
  8519. }
  8520. this.push(value);
  8521. return true;
  8522. };
  8523. SmartArrayNoDuplicate.prototype.reset = function () {
  8524. _super.prototype.reset.call(this);
  8525. this._duplicateId++;
  8526. };
  8527. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8528. if (array.length === 0) {
  8529. return;
  8530. }
  8531. if (this.length + array.length > this.data.length) {
  8532. this.data.length = (this.length + array.length) * 2;
  8533. }
  8534. for (var index = 0; index < array.length; index++) {
  8535. var item = (array.data || array)[index];
  8536. this.pushNoDuplicate(item);
  8537. }
  8538. };
  8539. return SmartArrayNoDuplicate;
  8540. }(SmartArray));
  8541. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8542. })(BABYLON || (BABYLON = {}));
  8543. //# sourceMappingURL=babylon.smartArray.js.map
  8544. var BABYLON;
  8545. (function (BABYLON) {
  8546. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8547. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8548. var LoadFileError = /** @class */ (function (_super) {
  8549. __extends(LoadFileError, _super);
  8550. function LoadFileError(message, request) {
  8551. var _this = _super.call(this, message) || this;
  8552. _this.request = request;
  8553. _this.name = "LoadFileError";
  8554. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8555. return _this;
  8556. }
  8557. // Polyfill for Object.setPrototypeOf if necessary.
  8558. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8559. return LoadFileError;
  8560. }(Error));
  8561. BABYLON.LoadFileError = LoadFileError;
  8562. var RetryStrategy = /** @class */ (function () {
  8563. function RetryStrategy() {
  8564. }
  8565. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8566. if (maxRetries === void 0) { maxRetries = 3; }
  8567. if (baseInterval === void 0) { baseInterval = 500; }
  8568. return function (url, request, retryIndex) {
  8569. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8570. return -1;
  8571. }
  8572. return Math.pow(2, retryIndex) * baseInterval;
  8573. };
  8574. };
  8575. return RetryStrategy;
  8576. }());
  8577. BABYLON.RetryStrategy = RetryStrategy;
  8578. // Screenshots
  8579. var screenshotCanvas;
  8580. var cloneValue = function (source, destinationObject) {
  8581. if (!source)
  8582. return null;
  8583. if (source instanceof BABYLON.Mesh) {
  8584. return null;
  8585. }
  8586. if (source instanceof BABYLON.SubMesh) {
  8587. return source.clone(destinationObject);
  8588. }
  8589. else if (source.clone) {
  8590. return source.clone();
  8591. }
  8592. return null;
  8593. };
  8594. var Tools = /** @class */ (function () {
  8595. function Tools() {
  8596. }
  8597. /**
  8598. * Interpolates between a and b via alpha
  8599. * @param a The lower value (returned when alpha = 0)
  8600. * @param b The upper value (returned when alpha = 1)
  8601. * @param alpha The interpolation-factor
  8602. * @return The mixed value
  8603. */
  8604. Tools.Mix = function (a, b, alpha) {
  8605. return a * (1 - alpha) + b * alpha;
  8606. };
  8607. Tools.Instantiate = function (className) {
  8608. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8609. return Tools.RegisteredExternalClasses[className];
  8610. }
  8611. var arr = className.split(".");
  8612. var fn = (window || this);
  8613. for (var i = 0, len = arr.length; i < len; i++) {
  8614. fn = fn[arr[i]];
  8615. }
  8616. if (typeof fn !== "function") {
  8617. return null;
  8618. }
  8619. return fn;
  8620. };
  8621. /**
  8622. * Provides a slice function that will work even on IE
  8623. * @param data defines the array to slice
  8624. * @param start defines the start of the data (optional)
  8625. * @param end defines the end of the data (optional)
  8626. * @returns the new sliced array
  8627. */
  8628. Tools.Slice = function (data, start, end) {
  8629. if (data.slice) {
  8630. return data.slice(start, end);
  8631. }
  8632. return Array.prototype.slice.call(data, start, end);
  8633. };
  8634. Tools.SetImmediate = function (action) {
  8635. if (window.setImmediate) {
  8636. window.setImmediate(action);
  8637. }
  8638. else {
  8639. setTimeout(action, 1);
  8640. }
  8641. };
  8642. Tools.IsExponentOfTwo = function (value) {
  8643. var count = 1;
  8644. do {
  8645. count *= 2;
  8646. } while (count < value);
  8647. return count === value;
  8648. };
  8649. /**
  8650. * Returns the nearest 32-bit single precision float representation of a Number
  8651. * @param value A Number. If the parameter is of a different type, it will get converted
  8652. * to a number or to NaN if it cannot be converted
  8653. * @returns number
  8654. */
  8655. Tools.FloatRound = function (value) {
  8656. if (Math.fround) {
  8657. return Math.fround(value);
  8658. }
  8659. return (Tools._tmpFloatArray[0] = value);
  8660. };
  8661. /**
  8662. * Find the next highest power of two.
  8663. * @param x Number to start search from.
  8664. * @return Next highest power of two.
  8665. */
  8666. Tools.CeilingPOT = function (x) {
  8667. x--;
  8668. x |= x >> 1;
  8669. x |= x >> 2;
  8670. x |= x >> 4;
  8671. x |= x >> 8;
  8672. x |= x >> 16;
  8673. x++;
  8674. return x;
  8675. };
  8676. /**
  8677. * Find the next lowest power of two.
  8678. * @param x Number to start search from.
  8679. * @return Next lowest power of two.
  8680. */
  8681. Tools.FloorPOT = function (x) {
  8682. x = x | (x >> 1);
  8683. x = x | (x >> 2);
  8684. x = x | (x >> 4);
  8685. x = x | (x >> 8);
  8686. x = x | (x >> 16);
  8687. return x - (x >> 1);
  8688. };
  8689. /**
  8690. * Find the nearest power of two.
  8691. * @param x Number to start search from.
  8692. * @return Next nearest power of two.
  8693. */
  8694. Tools.NearestPOT = function (x) {
  8695. var c = Tools.CeilingPOT(x);
  8696. var f = Tools.FloorPOT(x);
  8697. return (c - x) > (x - f) ? f : c;
  8698. };
  8699. Tools.GetExponentOfTwo = function (value, max, mode) {
  8700. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8701. var pot;
  8702. switch (mode) {
  8703. case BABYLON.Engine.SCALEMODE_FLOOR:
  8704. pot = Tools.FloorPOT(value);
  8705. break;
  8706. case BABYLON.Engine.SCALEMODE_NEAREST:
  8707. pot = Tools.NearestPOT(value);
  8708. break;
  8709. case BABYLON.Engine.SCALEMODE_CEILING:
  8710. default:
  8711. pot = Tools.CeilingPOT(value);
  8712. break;
  8713. }
  8714. return Math.min(pot, max);
  8715. };
  8716. Tools.GetFilename = function (path) {
  8717. var index = path.lastIndexOf("/");
  8718. if (index < 0)
  8719. return path;
  8720. return path.substring(index + 1);
  8721. };
  8722. /**
  8723. * Extracts the "folder" part of a path (everything before the filename).
  8724. * @param uri The URI to extract the info from
  8725. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8726. * @returns The "folder" part of the path
  8727. */
  8728. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8729. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8730. var index = uri.lastIndexOf("/");
  8731. if (index < 0) {
  8732. if (returnUnchangedIfNoSlash) {
  8733. return uri;
  8734. }
  8735. return "";
  8736. }
  8737. return uri.substring(0, index + 1);
  8738. };
  8739. Tools.GetDOMTextContent = function (element) {
  8740. var result = "";
  8741. var child = element.firstChild;
  8742. while (child) {
  8743. if (child.nodeType === 3) {
  8744. result += child.textContent;
  8745. }
  8746. child = child.nextSibling;
  8747. }
  8748. return result;
  8749. };
  8750. Tools.ToDegrees = function (angle) {
  8751. return angle * 180 / Math.PI;
  8752. };
  8753. Tools.ToRadians = function (angle) {
  8754. return angle * Math.PI / 180;
  8755. };
  8756. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8757. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8758. var output = "";
  8759. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8760. var i = 0;
  8761. var bytes = new Uint8Array(buffer);
  8762. while (i < bytes.length) {
  8763. chr1 = bytes[i++];
  8764. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8765. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8766. enc1 = chr1 >> 2;
  8767. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8768. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8769. enc4 = chr3 & 63;
  8770. if (isNaN(chr2)) {
  8771. enc3 = enc4 = 64;
  8772. }
  8773. else if (isNaN(chr3)) {
  8774. enc4 = 64;
  8775. }
  8776. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8777. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8778. }
  8779. return "data:image/png;base64," + output;
  8780. };
  8781. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8782. if (bias === void 0) { bias = null; }
  8783. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8784. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8785. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8786. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8787. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8788. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8789. }
  8790. if (bias) {
  8791. minimum.x -= minimum.x * bias.x + bias.y;
  8792. minimum.y -= minimum.y * bias.x + bias.y;
  8793. minimum.z -= minimum.z * bias.x + bias.y;
  8794. maximum.x += maximum.x * bias.x + bias.y;
  8795. maximum.y += maximum.y * bias.x + bias.y;
  8796. maximum.z += maximum.z * bias.x + bias.y;
  8797. }
  8798. return {
  8799. minimum: minimum,
  8800. maximum: maximum
  8801. };
  8802. };
  8803. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8804. if (bias === void 0) { bias = null; }
  8805. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8806. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8807. if (!stride) {
  8808. stride = 3;
  8809. }
  8810. for (var index = start; index < start + count; index++) {
  8811. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8812. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8813. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8814. }
  8815. if (bias) {
  8816. minimum.x -= minimum.x * bias.x + bias.y;
  8817. minimum.y -= minimum.y * bias.x + bias.y;
  8818. minimum.z -= minimum.z * bias.x + bias.y;
  8819. maximum.x += maximum.x * bias.x + bias.y;
  8820. maximum.y += maximum.y * bias.x + bias.y;
  8821. maximum.z += maximum.z * bias.x + bias.y;
  8822. }
  8823. return {
  8824. minimum: minimum,
  8825. maximum: maximum
  8826. };
  8827. };
  8828. Tools.Vector2ArrayFeeder = function (array) {
  8829. return function (index) {
  8830. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8831. var length = isFloatArray ? array.length / 2 : array.length;
  8832. if (index >= length) {
  8833. return null;
  8834. }
  8835. if (isFloatArray) {
  8836. var fa = array;
  8837. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8838. }
  8839. var a = array;
  8840. return a[index];
  8841. };
  8842. };
  8843. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8844. if (bias === void 0) { bias = null; }
  8845. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8846. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8847. var i = 0;
  8848. var cur = feeder(i++);
  8849. while (cur) {
  8850. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8851. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8852. cur = feeder(i++);
  8853. }
  8854. if (bias) {
  8855. minimum.x -= minimum.x * bias.x + bias.y;
  8856. minimum.y -= minimum.y * bias.x + bias.y;
  8857. maximum.x += maximum.x * bias.x + bias.y;
  8858. maximum.y += maximum.y * bias.x + bias.y;
  8859. }
  8860. return {
  8861. minimum: minimum,
  8862. maximum: maximum
  8863. };
  8864. };
  8865. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8866. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8867. return null;
  8868. return Array.isArray(obj) ? obj : [obj];
  8869. };
  8870. // Misc.
  8871. Tools.GetPointerPrefix = function () {
  8872. var eventPrefix = "pointer";
  8873. // Check if pointer events are supported
  8874. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8875. eventPrefix = "mouse";
  8876. }
  8877. return eventPrefix;
  8878. };
  8879. /**
  8880. * @param func - the function to be called
  8881. * @param requester - the object that will request the next frame. Falls back to window.
  8882. */
  8883. Tools.QueueNewFrame = function (func, requester) {
  8884. if (!Tools.IsWindowObjectExist()) {
  8885. return setTimeout(func, 16);
  8886. }
  8887. if (!requester) {
  8888. requester = window;
  8889. }
  8890. if (requester.requestAnimationFrame) {
  8891. return requester.requestAnimationFrame(func);
  8892. }
  8893. else if (requester.msRequestAnimationFrame) {
  8894. return requester.msRequestAnimationFrame(func);
  8895. }
  8896. else if (requester.webkitRequestAnimationFrame) {
  8897. return requester.webkitRequestAnimationFrame(func);
  8898. }
  8899. else if (requester.mozRequestAnimationFrame) {
  8900. return requester.mozRequestAnimationFrame(func);
  8901. }
  8902. else if (requester.oRequestAnimationFrame) {
  8903. return requester.oRequestAnimationFrame(func);
  8904. }
  8905. else {
  8906. return window.setTimeout(func, 16);
  8907. }
  8908. };
  8909. Tools.RequestFullscreen = function (element) {
  8910. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8911. if (!requestFunction)
  8912. return;
  8913. requestFunction.call(element);
  8914. };
  8915. Tools.ExitFullscreen = function () {
  8916. if (document.exitFullscreen) {
  8917. document.exitFullscreen();
  8918. }
  8919. else if (document.mozCancelFullScreen) {
  8920. document.mozCancelFullScreen();
  8921. }
  8922. else if (document.webkitCancelFullScreen) {
  8923. document.webkitCancelFullScreen();
  8924. }
  8925. else if (document.msCancelFullScreen) {
  8926. document.msCancelFullScreen();
  8927. }
  8928. };
  8929. Tools.SetCorsBehavior = function (url, element) {
  8930. if (url && url.indexOf("data:") === 0) {
  8931. return;
  8932. }
  8933. if (Tools.CorsBehavior) {
  8934. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  8935. element.crossOrigin = Tools.CorsBehavior;
  8936. }
  8937. else {
  8938. var result = Tools.CorsBehavior(url);
  8939. if (result) {
  8940. element.crossOrigin = result;
  8941. }
  8942. }
  8943. }
  8944. };
  8945. // External files
  8946. Tools.CleanUrl = function (url) {
  8947. url = url.replace(/#/mg, "%23");
  8948. return url;
  8949. };
  8950. Tools.LoadImage = function (url, onLoad, onError, database) {
  8951. if (url instanceof ArrayBuffer) {
  8952. url = Tools.EncodeArrayBufferTobase64(url);
  8953. }
  8954. url = Tools.CleanUrl(url);
  8955. url = Tools.PreprocessUrl(url);
  8956. var img = new Image();
  8957. Tools.SetCorsBehavior(url, img);
  8958. var loadHandler = function () {
  8959. img.removeEventListener("load", loadHandler);
  8960. img.removeEventListener("error", errorHandler);
  8961. onLoad(img);
  8962. };
  8963. var errorHandler = function (err) {
  8964. img.removeEventListener("load", loadHandler);
  8965. img.removeEventListener("error", errorHandler);
  8966. Tools.Error("Error while trying to load image: " + url);
  8967. if (onError) {
  8968. onError("Error while trying to load image: " + url, err);
  8969. }
  8970. };
  8971. img.addEventListener("load", loadHandler);
  8972. img.addEventListener("error", errorHandler);
  8973. var noIndexedDB = function () {
  8974. img.src = url;
  8975. };
  8976. var loadFromIndexedDB = function () {
  8977. if (database) {
  8978. database.loadImageFromDB(url, img);
  8979. }
  8980. };
  8981. //ANY database to do!
  8982. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  8983. database.openAsync(loadFromIndexedDB, noIndexedDB);
  8984. }
  8985. else {
  8986. if (url.indexOf("file:") !== -1) {
  8987. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  8988. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  8989. try {
  8990. var blobURL;
  8991. try {
  8992. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  8993. }
  8994. catch (ex) {
  8995. // Chrome doesn't support oneTimeOnly parameter
  8996. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  8997. }
  8998. img.src = blobURL;
  8999. }
  9000. catch (e) {
  9001. img.src = "";
  9002. }
  9003. return img;
  9004. }
  9005. }
  9006. noIndexedDB();
  9007. }
  9008. return img;
  9009. };
  9010. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9011. url = Tools.CleanUrl(url);
  9012. url = Tools.PreprocessUrl(url);
  9013. // If file and file input are set
  9014. if (url.indexOf("file:") !== -1) {
  9015. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9016. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9017. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9018. }
  9019. }
  9020. var loadUrl = Tools.BaseUrl + url;
  9021. var aborted = false;
  9022. var fileRequest = {
  9023. onCompleteObservable: new BABYLON.Observable(),
  9024. abort: function () { return aborted = true; },
  9025. };
  9026. var requestFile = function () {
  9027. var request = new XMLHttpRequest();
  9028. var retryHandle = null;
  9029. fileRequest.abort = function () {
  9030. aborted = true;
  9031. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9032. request.abort();
  9033. }
  9034. if (retryHandle !== null) {
  9035. clearTimeout(retryHandle);
  9036. retryHandle = null;
  9037. }
  9038. };
  9039. var retryLoop = function (retryIndex) {
  9040. request.open('GET', loadUrl, true);
  9041. if (useArrayBuffer) {
  9042. request.responseType = "arraybuffer";
  9043. }
  9044. if (onProgress) {
  9045. request.addEventListener("progress", onProgress);
  9046. }
  9047. var onLoadEnd = function () {
  9048. request.removeEventListener("loadend", onLoadEnd);
  9049. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9050. fileRequest.onCompleteObservable.clear();
  9051. };
  9052. request.addEventListener("loadend", onLoadEnd);
  9053. var onReadyStateChange = function () {
  9054. if (aborted) {
  9055. return;
  9056. }
  9057. // In case of undefined state in some browsers.
  9058. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9059. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9060. request.removeEventListener("readystatechange", onReadyStateChange);
  9061. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9062. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9063. return;
  9064. }
  9065. var retryStrategy = Tools.DefaultRetryStrategy;
  9066. if (retryStrategy) {
  9067. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9068. if (waitTime !== -1) {
  9069. // Prevent the request from completing for retry.
  9070. request.removeEventListener("loadend", onLoadEnd);
  9071. request = new XMLHttpRequest();
  9072. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9073. return;
  9074. }
  9075. }
  9076. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9077. if (onError) {
  9078. onError(request, e);
  9079. }
  9080. else {
  9081. throw e;
  9082. }
  9083. }
  9084. };
  9085. request.addEventListener("readystatechange", onReadyStateChange);
  9086. request.send();
  9087. };
  9088. retryLoop(0);
  9089. };
  9090. // Caching all files
  9091. if (database && database.enableSceneOffline) {
  9092. var noIndexedDB_1 = function () {
  9093. if (!aborted) {
  9094. requestFile();
  9095. }
  9096. };
  9097. var loadFromIndexedDB = function () {
  9098. // TODO: database needs to support aborting and should return a IFileRequest
  9099. if (aborted) {
  9100. return;
  9101. }
  9102. if (database) {
  9103. database.loadFileFromDB(url, function (data) {
  9104. if (!aborted) {
  9105. onSuccess(data);
  9106. }
  9107. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9108. }, onProgress ? function (event) {
  9109. if (!aborted) {
  9110. onProgress(event);
  9111. }
  9112. } : undefined, noIndexedDB_1, useArrayBuffer);
  9113. }
  9114. };
  9115. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9116. }
  9117. else {
  9118. requestFile();
  9119. }
  9120. return fileRequest;
  9121. };
  9122. /**
  9123. * Load a script (identified by an url). When the url returns, the
  9124. * content of this file is added into a new script element, attached to the DOM (body element)
  9125. */
  9126. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9127. var head = document.getElementsByTagName('head')[0];
  9128. var script = document.createElement('script');
  9129. script.type = 'text/javascript';
  9130. script.src = scriptUrl;
  9131. script.onload = function () {
  9132. if (onSuccess) {
  9133. onSuccess();
  9134. }
  9135. };
  9136. script.onerror = function (e) {
  9137. if (onError) {
  9138. onError("Unable to load script '" + scriptUrl + "'", e);
  9139. }
  9140. };
  9141. head.appendChild(script);
  9142. };
  9143. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9144. var reader = new FileReader();
  9145. var request = {
  9146. onCompleteObservable: new BABYLON.Observable(),
  9147. abort: function () { return reader.abort(); },
  9148. };
  9149. reader.onloadend = function (e) {
  9150. request.onCompleteObservable.notifyObservers(request);
  9151. };
  9152. reader.onload = function (e) {
  9153. //target doesn't have result from ts 1.3
  9154. callback(e.target['result']);
  9155. };
  9156. reader.onprogress = progressCallback;
  9157. reader.readAsDataURL(fileToLoad);
  9158. return request;
  9159. };
  9160. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9161. var reader = new FileReader();
  9162. var request = {
  9163. onCompleteObservable: new BABYLON.Observable(),
  9164. abort: function () { return reader.abort(); },
  9165. };
  9166. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9167. reader.onerror = function (e) {
  9168. Tools.Log("Error while reading file: " + fileToLoad.name);
  9169. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9170. };
  9171. reader.onload = function (e) {
  9172. //target doesn't have result from ts 1.3
  9173. callback(e.target['result']);
  9174. };
  9175. if (progressCallBack) {
  9176. reader.onprogress = progressCallBack;
  9177. }
  9178. if (!useArrayBuffer) {
  9179. // Asynchronous read
  9180. reader.readAsText(fileToLoad);
  9181. }
  9182. else {
  9183. reader.readAsArrayBuffer(fileToLoad);
  9184. }
  9185. return request;
  9186. };
  9187. //returns a downloadable url to a file content.
  9188. Tools.FileAsURL = function (content) {
  9189. var fileBlob = new Blob([content]);
  9190. var url = window.URL || window.webkitURL;
  9191. var link = url.createObjectURL(fileBlob);
  9192. return link;
  9193. };
  9194. // Misc.
  9195. Tools.Format = function (value, decimals) {
  9196. if (decimals === void 0) { decimals = 2; }
  9197. return value.toFixed(decimals);
  9198. };
  9199. Tools.CheckExtends = function (v, min, max) {
  9200. if (v.x < min.x)
  9201. min.x = v.x;
  9202. if (v.y < min.y)
  9203. min.y = v.y;
  9204. if (v.z < min.z)
  9205. min.z = v.z;
  9206. if (v.x > max.x)
  9207. max.x = v.x;
  9208. if (v.y > max.y)
  9209. max.y = v.y;
  9210. if (v.z > max.z)
  9211. max.z = v.z;
  9212. };
  9213. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9214. for (var prop in source) {
  9215. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9216. continue;
  9217. }
  9218. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9219. continue;
  9220. }
  9221. var sourceValue = source[prop];
  9222. var typeOfSourceValue = typeof sourceValue;
  9223. if (typeOfSourceValue === "function") {
  9224. continue;
  9225. }
  9226. try {
  9227. if (typeOfSourceValue === "object") {
  9228. if (sourceValue instanceof Array) {
  9229. destination[prop] = [];
  9230. if (sourceValue.length > 0) {
  9231. if (typeof sourceValue[0] == "object") {
  9232. for (var index = 0; index < sourceValue.length; index++) {
  9233. var clonedValue = cloneValue(sourceValue[index], destination);
  9234. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9235. destination[prop].push(clonedValue);
  9236. }
  9237. }
  9238. }
  9239. else {
  9240. destination[prop] = sourceValue.slice(0);
  9241. }
  9242. }
  9243. }
  9244. else {
  9245. destination[prop] = cloneValue(sourceValue, destination);
  9246. }
  9247. }
  9248. else {
  9249. destination[prop] = sourceValue;
  9250. }
  9251. }
  9252. catch (e) {
  9253. // Just ignore error (it could be because of a read-only property)
  9254. }
  9255. }
  9256. };
  9257. Tools.IsEmpty = function (obj) {
  9258. for (var i in obj) {
  9259. if (obj.hasOwnProperty(i)) {
  9260. return false;
  9261. }
  9262. }
  9263. return true;
  9264. };
  9265. Tools.RegisterTopRootEvents = function (events) {
  9266. for (var index = 0; index < events.length; index++) {
  9267. var event = events[index];
  9268. window.addEventListener(event.name, event.handler, false);
  9269. try {
  9270. if (window.parent) {
  9271. window.parent.addEventListener(event.name, event.handler, false);
  9272. }
  9273. }
  9274. catch (e) {
  9275. // Silently fails...
  9276. }
  9277. }
  9278. };
  9279. Tools.UnregisterTopRootEvents = function (events) {
  9280. for (var index = 0; index < events.length; index++) {
  9281. var event = events[index];
  9282. window.removeEventListener(event.name, event.handler);
  9283. try {
  9284. if (window.parent) {
  9285. window.parent.removeEventListener(event.name, event.handler);
  9286. }
  9287. }
  9288. catch (e) {
  9289. // Silently fails...
  9290. }
  9291. }
  9292. };
  9293. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9294. if (mimeType === void 0) { mimeType = "image/png"; }
  9295. // Read the contents of the framebuffer
  9296. var numberOfChannelsByLine = width * 4;
  9297. var halfHeight = height / 2;
  9298. //Reading datas from WebGL
  9299. var data = engine.readPixels(0, 0, width, height);
  9300. //To flip image on Y axis.
  9301. for (var i = 0; i < halfHeight; i++) {
  9302. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9303. var currentCell = j + i * numberOfChannelsByLine;
  9304. var targetLine = height - i - 1;
  9305. var targetCell = j + targetLine * numberOfChannelsByLine;
  9306. var temp = data[currentCell];
  9307. data[currentCell] = data[targetCell];
  9308. data[targetCell] = temp;
  9309. }
  9310. }
  9311. // Create a 2D canvas to store the result
  9312. if (!screenshotCanvas) {
  9313. screenshotCanvas = document.createElement('canvas');
  9314. }
  9315. screenshotCanvas.width = width;
  9316. screenshotCanvas.height = height;
  9317. var context = screenshotCanvas.getContext('2d');
  9318. if (context) {
  9319. // Copy the pixels to a 2D canvas
  9320. var imageData = context.createImageData(width, height);
  9321. var castData = (imageData.data);
  9322. castData.set(data);
  9323. context.putImageData(imageData, 0, 0);
  9324. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9325. }
  9326. };
  9327. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9328. if (mimeType === void 0) { mimeType = "image/png"; }
  9329. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9330. if (successCallback) {
  9331. successCallback(base64Image);
  9332. }
  9333. else {
  9334. // We need HTMLCanvasElement.toBlob for HD screenshots
  9335. if (!screenshotCanvas.toBlob) {
  9336. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9337. screenshotCanvas.toBlob = function (callback, type, quality) {
  9338. var _this = this;
  9339. setTimeout(function () {
  9340. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9341. for (var i = 0; i < len; i++) {
  9342. arr[i] = binStr.charCodeAt(i);
  9343. }
  9344. callback(new Blob([arr], { type: type || 'image/png' }));
  9345. });
  9346. };
  9347. }
  9348. screenshotCanvas.toBlob(function (blob) {
  9349. var url = URL.createObjectURL(blob);
  9350. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9351. if (("download" in document.createElement("a"))) {
  9352. var a = window.document.createElement("a");
  9353. a.href = url;
  9354. if (fileName) {
  9355. a.setAttribute("download", fileName);
  9356. }
  9357. else {
  9358. var date = new Date();
  9359. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(-2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9360. a.setAttribute("download", "screenshot_" + stringDate + ".png");
  9361. }
  9362. window.document.body.appendChild(a);
  9363. a.addEventListener("click", function () {
  9364. if (a.parentElement) {
  9365. a.parentElement.removeChild(a);
  9366. }
  9367. });
  9368. a.click();
  9369. }
  9370. else {
  9371. var newWindow = window.open("");
  9372. if (!newWindow)
  9373. return;
  9374. var img = newWindow.document.createElement("img");
  9375. img.onload = function () {
  9376. // no longer need to read the blob so it's revoked
  9377. URL.revokeObjectURL(url);
  9378. };
  9379. img.src = url;
  9380. newWindow.document.body.appendChild(img);
  9381. }
  9382. });
  9383. }
  9384. };
  9385. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9386. if (mimeType === void 0) { mimeType = "image/png"; }
  9387. var width;
  9388. var height;
  9389. // If a precision value is specified
  9390. if (size.precision) {
  9391. width = Math.round(engine.getRenderWidth() * size.precision);
  9392. height = Math.round(width / engine.getAspectRatio(camera));
  9393. }
  9394. else if (size.width && size.height) {
  9395. width = size.width;
  9396. height = size.height;
  9397. }
  9398. //If passing only width, computing height to keep display canvas ratio.
  9399. else if (size.width && !size.height) {
  9400. width = size.width;
  9401. height = Math.round(width / engine.getAspectRatio(camera));
  9402. }
  9403. //If passing only height, computing width to keep display canvas ratio.
  9404. else if (size.height && !size.width) {
  9405. height = size.height;
  9406. width = Math.round(height * engine.getAspectRatio(camera));
  9407. }
  9408. //Assuming here that "size" parameter is a number
  9409. else if (!isNaN(size)) {
  9410. height = size;
  9411. width = size;
  9412. }
  9413. else {
  9414. Tools.Error("Invalid 'size' parameter !");
  9415. return;
  9416. }
  9417. if (!screenshotCanvas) {
  9418. screenshotCanvas = document.createElement('canvas');
  9419. }
  9420. screenshotCanvas.width = width;
  9421. screenshotCanvas.height = height;
  9422. var renderContext = screenshotCanvas.getContext("2d");
  9423. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9424. var newWidth = width;
  9425. var newHeight = newWidth / ratio;
  9426. if (newHeight > height) {
  9427. newHeight = height;
  9428. newWidth = newHeight * ratio;
  9429. }
  9430. var offsetX = Math.max(0, width - newWidth) / 2;
  9431. var offsetY = Math.max(0, height - newHeight) / 2;
  9432. var renderingCanvas = engine.getRenderingCanvas();
  9433. if (renderContext && renderingCanvas) {
  9434. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9435. }
  9436. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9437. };
  9438. /**
  9439. * Generates an image screenshot from the specified camera.
  9440. *
  9441. * @param engine The engine to use for rendering
  9442. * @param camera The camera to use for rendering
  9443. * @param size This parameter can be set to a single number or to an object with the
  9444. * following (optional) properties: precision, width, height. If a single number is passed,
  9445. * it will be used for both width and height. If an object is passed, the screenshot size
  9446. * will be derived from the parameters. The precision property is a multiplier allowing
  9447. * rendering at a higher or lower resolution.
  9448. * @param successCallback The callback receives a single parameter which contains the
  9449. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9450. * src parameter of an <img> to display it.
  9451. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9452. * Check your browser for supported MIME types.
  9453. * @param samples Texture samples (default: 1)
  9454. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9455. * @param fileName A name for for the downloaded file.
  9456. * @constructor
  9457. */
  9458. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9459. if (mimeType === void 0) { mimeType = "image/png"; }
  9460. if (samples === void 0) { samples = 1; }
  9461. if (antialiasing === void 0) { antialiasing = false; }
  9462. var width;
  9463. var height;
  9464. //If a precision value is specified
  9465. if (size.precision) {
  9466. width = Math.round(engine.getRenderWidth() * size.precision);
  9467. height = Math.round(width / engine.getAspectRatio(camera));
  9468. size = { width: width, height: height };
  9469. }
  9470. else if (size.width && size.height) {
  9471. width = size.width;
  9472. height = size.height;
  9473. }
  9474. //If passing only width, computing height to keep display canvas ratio.
  9475. else if (size.width && !size.height) {
  9476. width = size.width;
  9477. height = Math.round(width / engine.getAspectRatio(camera));
  9478. size = { width: width, height: height };
  9479. }
  9480. //If passing only height, computing width to keep display canvas ratio.
  9481. else if (size.height && !size.width) {
  9482. height = size.height;
  9483. width = Math.round(height * engine.getAspectRatio(camera));
  9484. size = { width: width, height: height };
  9485. }
  9486. //Assuming here that "size" parameter is a number
  9487. else if (!isNaN(size)) {
  9488. height = size;
  9489. width = size;
  9490. }
  9491. else {
  9492. Tools.Error("Invalid 'size' parameter !");
  9493. return;
  9494. }
  9495. var scene = camera.getScene();
  9496. var previousCamera = null;
  9497. if (scene.activeCamera !== camera) {
  9498. previousCamera = scene.activeCamera;
  9499. scene.activeCamera = camera;
  9500. }
  9501. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9502. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9503. texture.renderList = null;
  9504. texture.samples = samples;
  9505. if (antialiasing) {
  9506. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9507. }
  9508. texture.onAfterRenderObservable.add(function () {
  9509. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9510. });
  9511. scene.incrementRenderId();
  9512. scene.resetCachedMaterial();
  9513. texture.render(true);
  9514. texture.dispose();
  9515. if (previousCamera) {
  9516. scene.activeCamera = previousCamera;
  9517. }
  9518. camera.getProjectionMatrix(true); // Force cache refresh;
  9519. };
  9520. // XHR response validator for local file scenario
  9521. Tools.ValidateXHRData = function (xhr, dataType) {
  9522. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9523. if (dataType === void 0) { dataType = 7; }
  9524. try {
  9525. if (dataType & 1) {
  9526. if (xhr.responseText && xhr.responseText.length > 0) {
  9527. return true;
  9528. }
  9529. else if (dataType === 1) {
  9530. return false;
  9531. }
  9532. }
  9533. if (dataType & 2) {
  9534. // Check header width and height since there is no "TGA" magic number
  9535. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9536. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9537. return true;
  9538. }
  9539. else if (dataType === 2) {
  9540. return false;
  9541. }
  9542. }
  9543. if (dataType & 4) {
  9544. // Check for the "DDS" magic number
  9545. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9546. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9547. return true;
  9548. }
  9549. else {
  9550. return false;
  9551. }
  9552. }
  9553. }
  9554. catch (e) {
  9555. // Global protection
  9556. }
  9557. return false;
  9558. };
  9559. /**
  9560. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9561. * Be aware Math.random() could cause collisions, but:
  9562. * "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"
  9563. */
  9564. Tools.RandomId = function () {
  9565. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9566. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9567. return v.toString(16);
  9568. });
  9569. };
  9570. /**
  9571. * Test if the given uri is a base64 string.
  9572. * @param uri The uri to test
  9573. * @return True if the uri is a base64 string or false otherwise.
  9574. */
  9575. Tools.IsBase64 = function (uri) {
  9576. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9577. };
  9578. /**
  9579. * Decode the given base64 uri.
  9580. * @param uri The uri to decode
  9581. * @return The decoded base64 data.
  9582. */
  9583. Tools.DecodeBase64 = function (uri) {
  9584. var decodedString = atob(uri.split(",")[1]);
  9585. var bufferLength = decodedString.length;
  9586. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9587. for (var i = 0; i < bufferLength; i++) {
  9588. bufferView[i] = decodedString.charCodeAt(i);
  9589. }
  9590. return bufferView.buffer;
  9591. };
  9592. Object.defineProperty(Tools, "NoneLogLevel", {
  9593. get: function () {
  9594. return Tools._NoneLogLevel;
  9595. },
  9596. enumerable: true,
  9597. configurable: true
  9598. });
  9599. Object.defineProperty(Tools, "MessageLogLevel", {
  9600. get: function () {
  9601. return Tools._MessageLogLevel;
  9602. },
  9603. enumerable: true,
  9604. configurable: true
  9605. });
  9606. Object.defineProperty(Tools, "WarningLogLevel", {
  9607. get: function () {
  9608. return Tools._WarningLogLevel;
  9609. },
  9610. enumerable: true,
  9611. configurable: true
  9612. });
  9613. Object.defineProperty(Tools, "ErrorLogLevel", {
  9614. get: function () {
  9615. return Tools._ErrorLogLevel;
  9616. },
  9617. enumerable: true,
  9618. configurable: true
  9619. });
  9620. Object.defineProperty(Tools, "AllLogLevel", {
  9621. get: function () {
  9622. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9623. },
  9624. enumerable: true,
  9625. configurable: true
  9626. });
  9627. Tools._AddLogEntry = function (entry) {
  9628. Tools._LogCache = entry + Tools._LogCache;
  9629. if (Tools.OnNewCacheEntry) {
  9630. Tools.OnNewCacheEntry(entry);
  9631. }
  9632. };
  9633. Tools._FormatMessage = function (message) {
  9634. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9635. var date = new Date();
  9636. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9637. };
  9638. Tools._LogDisabled = function (message) {
  9639. // nothing to do
  9640. };
  9641. Tools._LogEnabled = function (message) {
  9642. var formattedMessage = Tools._FormatMessage(message);
  9643. console.log("BJS - " + formattedMessage);
  9644. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9645. Tools._AddLogEntry(entry);
  9646. };
  9647. Tools._WarnDisabled = function (message) {
  9648. // nothing to do
  9649. };
  9650. Tools._WarnEnabled = function (message) {
  9651. var formattedMessage = Tools._FormatMessage(message);
  9652. console.warn("BJS - " + formattedMessage);
  9653. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9654. Tools._AddLogEntry(entry);
  9655. };
  9656. Tools._ErrorDisabled = function (message) {
  9657. // nothing to do
  9658. };
  9659. Tools._ErrorEnabled = function (message) {
  9660. Tools.errorsCount++;
  9661. var formattedMessage = Tools._FormatMessage(message);
  9662. console.error("BJS - " + formattedMessage);
  9663. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9664. Tools._AddLogEntry(entry);
  9665. };
  9666. Object.defineProperty(Tools, "LogCache", {
  9667. get: function () {
  9668. return Tools._LogCache;
  9669. },
  9670. enumerable: true,
  9671. configurable: true
  9672. });
  9673. Tools.ClearLogCache = function () {
  9674. Tools._LogCache = "";
  9675. Tools.errorsCount = 0;
  9676. };
  9677. Object.defineProperty(Tools, "LogLevels", {
  9678. set: function (level) {
  9679. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9680. Tools.Log = Tools._LogEnabled;
  9681. }
  9682. else {
  9683. Tools.Log = Tools._LogDisabled;
  9684. }
  9685. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9686. Tools.Warn = Tools._WarnEnabled;
  9687. }
  9688. else {
  9689. Tools.Warn = Tools._WarnDisabled;
  9690. }
  9691. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9692. Tools.Error = Tools._ErrorEnabled;
  9693. }
  9694. else {
  9695. Tools.Error = Tools._ErrorDisabled;
  9696. }
  9697. },
  9698. enumerable: true,
  9699. configurable: true
  9700. });
  9701. Tools.IsWindowObjectExist = function () {
  9702. return (typeof window) !== "undefined";
  9703. };
  9704. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9705. get: function () {
  9706. return Tools._PerformanceNoneLogLevel;
  9707. },
  9708. enumerable: true,
  9709. configurable: true
  9710. });
  9711. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9712. get: function () {
  9713. return Tools._PerformanceUserMarkLogLevel;
  9714. },
  9715. enumerable: true,
  9716. configurable: true
  9717. });
  9718. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9719. get: function () {
  9720. return Tools._PerformanceConsoleLogLevel;
  9721. },
  9722. enumerable: true,
  9723. configurable: true
  9724. });
  9725. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9726. set: function (level) {
  9727. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9728. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9729. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9730. return;
  9731. }
  9732. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9733. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9734. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9735. return;
  9736. }
  9737. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9738. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9739. },
  9740. enumerable: true,
  9741. configurable: true
  9742. });
  9743. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9744. };
  9745. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9746. };
  9747. Tools._StartUserMark = function (counterName, condition) {
  9748. if (condition === void 0) { condition = true; }
  9749. if (!Tools._performance) {
  9750. if (!Tools.IsWindowObjectExist()) {
  9751. return;
  9752. }
  9753. Tools._performance = window.performance;
  9754. }
  9755. if (!condition || !Tools._performance.mark) {
  9756. return;
  9757. }
  9758. Tools._performance.mark(counterName + "-Begin");
  9759. };
  9760. Tools._EndUserMark = function (counterName, condition) {
  9761. if (condition === void 0) { condition = true; }
  9762. if (!condition || !Tools._performance.mark) {
  9763. return;
  9764. }
  9765. Tools._performance.mark(counterName + "-End");
  9766. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9767. };
  9768. Tools._StartPerformanceConsole = function (counterName, condition) {
  9769. if (condition === void 0) { condition = true; }
  9770. if (!condition) {
  9771. return;
  9772. }
  9773. Tools._StartUserMark(counterName, condition);
  9774. if (console.time) {
  9775. console.time(counterName);
  9776. }
  9777. };
  9778. Tools._EndPerformanceConsole = function (counterName, condition) {
  9779. if (condition === void 0) { condition = true; }
  9780. if (!condition) {
  9781. return;
  9782. }
  9783. Tools._EndUserMark(counterName, condition);
  9784. if (console.time) {
  9785. console.timeEnd(counterName);
  9786. }
  9787. };
  9788. Object.defineProperty(Tools, "Now", {
  9789. get: function () {
  9790. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9791. return window.performance.now();
  9792. }
  9793. return Date.now();
  9794. },
  9795. enumerable: true,
  9796. configurable: true
  9797. });
  9798. /**
  9799. * This method will return the name of the class used to create the instance of the given object.
  9800. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9801. * @param object the object to get the class name from
  9802. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9803. */
  9804. Tools.GetClassName = function (object, isType) {
  9805. if (isType === void 0) { isType = false; }
  9806. var name = null;
  9807. if (!isType && object.getClassName) {
  9808. name = object.getClassName();
  9809. }
  9810. else {
  9811. if (object instanceof Object) {
  9812. var classObj = isType ? object : Object.getPrototypeOf(object);
  9813. name = classObj.constructor["__bjsclassName__"];
  9814. }
  9815. if (!name) {
  9816. name = typeof object;
  9817. }
  9818. }
  9819. return name;
  9820. };
  9821. Tools.First = function (array, predicate) {
  9822. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9823. var el = array_1[_i];
  9824. if (predicate(el)) {
  9825. return el;
  9826. }
  9827. }
  9828. return null;
  9829. };
  9830. /**
  9831. * This method will return the name of the full name of the class, including its owning module (if any).
  9832. * 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).
  9833. * @param object the object to get the class name from
  9834. * @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.
  9835. */
  9836. Tools.getFullClassName = function (object, isType) {
  9837. if (isType === void 0) { isType = false; }
  9838. var className = null;
  9839. var moduleName = null;
  9840. if (!isType && object.getClassName) {
  9841. className = object.getClassName();
  9842. }
  9843. else {
  9844. if (object instanceof Object) {
  9845. var classObj = isType ? object : Object.getPrototypeOf(object);
  9846. className = classObj.constructor["__bjsclassName__"];
  9847. moduleName = classObj.constructor["__bjsmoduleName__"];
  9848. }
  9849. if (!className) {
  9850. className = typeof object;
  9851. }
  9852. }
  9853. if (!className) {
  9854. return null;
  9855. }
  9856. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9857. };
  9858. /**
  9859. * 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.
  9860. * @param array
  9861. */
  9862. Tools.arrayOrStringFeeder = function (array) {
  9863. return function (index) {
  9864. if (index >= array.length) {
  9865. return null;
  9866. }
  9867. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9868. if (val && val.getHashCode) {
  9869. val = val.getHashCode();
  9870. }
  9871. if (typeof val === "string") {
  9872. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  9873. }
  9874. return val;
  9875. };
  9876. };
  9877. /**
  9878. * Compute the hashCode of a stream of number
  9879. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  9880. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  9881. * @return the hash code computed
  9882. */
  9883. Tools.hashCodeFromStream = function (feeder) {
  9884. // Based from here: http://stackoverflow.com/a/7616484/802124
  9885. var hash = 0;
  9886. var index = 0;
  9887. var chr = feeder(index++);
  9888. while (chr != null) {
  9889. hash = ((hash << 5) - hash) + chr;
  9890. hash |= 0; // Convert to 32bit integer
  9891. chr = feeder(index++);
  9892. }
  9893. return hash;
  9894. };
  9895. /**
  9896. * Returns a promise that resolves after the given amount of time.
  9897. * @param delay Number of milliseconds to delay
  9898. * @returns Promise that resolves after the given amount of time
  9899. */
  9900. Tools.DelayAsync = function (delay) {
  9901. return new Promise(function (resolve) {
  9902. setTimeout(function () {
  9903. resolve();
  9904. }, delay);
  9905. });
  9906. };
  9907. Tools.BaseUrl = "";
  9908. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  9909. /**
  9910. * Default behaviour for cors in the application.
  9911. * It can be a string if the expected behavior is identical in the entire app.
  9912. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  9913. */
  9914. Tools.CorsBehavior = "anonymous";
  9915. Tools.UseFallbackTexture = true;
  9916. /**
  9917. * Use this object to register external classes like custom textures or material
  9918. * to allow the laoders to instantiate them
  9919. */
  9920. Tools.RegisteredExternalClasses = {};
  9921. // Used in case of a texture loading problem
  9922. 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";
  9923. Tools._tmpFloatArray = new Float32Array(1);
  9924. Tools.PreprocessUrl = function (url) {
  9925. return url;
  9926. };
  9927. // Logs
  9928. Tools._NoneLogLevel = 0;
  9929. Tools._MessageLogLevel = 1;
  9930. Tools._WarningLogLevel = 2;
  9931. Tools._ErrorLogLevel = 4;
  9932. Tools._LogCache = "";
  9933. Tools.errorsCount = 0;
  9934. Tools.Log = Tools._LogEnabled;
  9935. Tools.Warn = Tools._WarnEnabled;
  9936. Tools.Error = Tools._ErrorEnabled;
  9937. // Performances
  9938. Tools._PerformanceNoneLogLevel = 0;
  9939. Tools._PerformanceUserMarkLogLevel = 1;
  9940. Tools._PerformanceConsoleLogLevel = 2;
  9941. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9942. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9943. return Tools;
  9944. }());
  9945. BABYLON.Tools = Tools;
  9946. /**
  9947. * This class is used to track a performance counter which is number based.
  9948. * The user has access to many properties which give statistics of different nature
  9949. *
  9950. * The implementer can track two kinds of Performance Counter: time and count
  9951. * 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.
  9952. * 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.
  9953. */
  9954. var PerfCounter = /** @class */ (function () {
  9955. function PerfCounter() {
  9956. this._startMonitoringTime = 0;
  9957. this._min = 0;
  9958. this._max = 0;
  9959. this._average = 0;
  9960. this._lastSecAverage = 0;
  9961. this._current = 0;
  9962. this._totalValueCount = 0;
  9963. this._totalAccumulated = 0;
  9964. this._lastSecAccumulated = 0;
  9965. this._lastSecTime = 0;
  9966. this._lastSecValueCount = 0;
  9967. }
  9968. Object.defineProperty(PerfCounter.prototype, "min", {
  9969. /**
  9970. * Returns the smallest value ever
  9971. */
  9972. get: function () {
  9973. return this._min;
  9974. },
  9975. enumerable: true,
  9976. configurable: true
  9977. });
  9978. Object.defineProperty(PerfCounter.prototype, "max", {
  9979. /**
  9980. * Returns the biggest value ever
  9981. */
  9982. get: function () {
  9983. return this._max;
  9984. },
  9985. enumerable: true,
  9986. configurable: true
  9987. });
  9988. Object.defineProperty(PerfCounter.prototype, "average", {
  9989. /**
  9990. * Returns the average value since the performance counter is running
  9991. */
  9992. get: function () {
  9993. return this._average;
  9994. },
  9995. enumerable: true,
  9996. configurable: true
  9997. });
  9998. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  9999. /**
  10000. * Returns the average value of the last second the counter was monitored
  10001. */
  10002. get: function () {
  10003. return this._lastSecAverage;
  10004. },
  10005. enumerable: true,
  10006. configurable: true
  10007. });
  10008. Object.defineProperty(PerfCounter.prototype, "current", {
  10009. /**
  10010. * Returns the current value
  10011. */
  10012. get: function () {
  10013. return this._current;
  10014. },
  10015. enumerable: true,
  10016. configurable: true
  10017. });
  10018. Object.defineProperty(PerfCounter.prototype, "total", {
  10019. get: function () {
  10020. return this._totalAccumulated;
  10021. },
  10022. enumerable: true,
  10023. configurable: true
  10024. });
  10025. Object.defineProperty(PerfCounter.prototype, "count", {
  10026. get: function () {
  10027. return this._totalValueCount;
  10028. },
  10029. enumerable: true,
  10030. configurable: true
  10031. });
  10032. /**
  10033. * Call this method to start monitoring a new frame.
  10034. * 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.
  10035. */
  10036. PerfCounter.prototype.fetchNewFrame = function () {
  10037. this._totalValueCount++;
  10038. this._current = 0;
  10039. this._lastSecValueCount++;
  10040. };
  10041. /**
  10042. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10043. * @param newCount the count value to add to the monitored count
  10044. * @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.
  10045. */
  10046. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10047. if (!PerfCounter.Enabled) {
  10048. return;
  10049. }
  10050. this._current += newCount;
  10051. if (fetchResult) {
  10052. this._fetchResult();
  10053. }
  10054. };
  10055. /**
  10056. * Start monitoring this performance counter
  10057. */
  10058. PerfCounter.prototype.beginMonitoring = function () {
  10059. if (!PerfCounter.Enabled) {
  10060. return;
  10061. }
  10062. this._startMonitoringTime = Tools.Now;
  10063. };
  10064. /**
  10065. * Compute the time lapsed since the previous beginMonitoring() call.
  10066. * @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
  10067. */
  10068. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10069. if (newFrame === void 0) { newFrame = true; }
  10070. if (!PerfCounter.Enabled) {
  10071. return;
  10072. }
  10073. if (newFrame) {
  10074. this.fetchNewFrame();
  10075. }
  10076. var currentTime = Tools.Now;
  10077. this._current = currentTime - this._startMonitoringTime;
  10078. if (newFrame) {
  10079. this._fetchResult();
  10080. }
  10081. };
  10082. PerfCounter.prototype._fetchResult = function () {
  10083. this._totalAccumulated += this._current;
  10084. this._lastSecAccumulated += this._current;
  10085. // Min/Max update
  10086. this._min = Math.min(this._min, this._current);
  10087. this._max = Math.max(this._max, this._current);
  10088. this._average = this._totalAccumulated / this._totalValueCount;
  10089. // Reset last sec?
  10090. var now = Tools.Now;
  10091. if ((now - this._lastSecTime) > 1000) {
  10092. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10093. this._lastSecTime = now;
  10094. this._lastSecAccumulated = 0;
  10095. this._lastSecValueCount = 0;
  10096. }
  10097. };
  10098. PerfCounter.Enabled = true;
  10099. return PerfCounter;
  10100. }());
  10101. BABYLON.PerfCounter = PerfCounter;
  10102. /**
  10103. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10104. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10105. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10106. * @param name The name of the class, case should be preserved
  10107. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10108. */
  10109. function className(name, module) {
  10110. return function (target) {
  10111. target["__bjsclassName__"] = name;
  10112. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10113. };
  10114. }
  10115. BABYLON.className = className;
  10116. /**
  10117. * An implementation of a loop for asynchronous functions.
  10118. */
  10119. var AsyncLoop = /** @class */ (function () {
  10120. /**
  10121. * Constroctor.
  10122. * @param iterations the number of iterations.
  10123. * @param _fn the function to run each iteration
  10124. * @param _successCallback the callback that will be called upon succesful execution
  10125. * @param offset starting offset.
  10126. */
  10127. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10128. if (offset === void 0) { offset = 0; }
  10129. this.iterations = iterations;
  10130. this._fn = _fn;
  10131. this._successCallback = _successCallback;
  10132. this.index = offset - 1;
  10133. this._done = false;
  10134. }
  10135. /**
  10136. * Execute the next iteration. Must be called after the last iteration was finished.
  10137. */
  10138. AsyncLoop.prototype.executeNext = function () {
  10139. if (!this._done) {
  10140. if (this.index + 1 < this.iterations) {
  10141. ++this.index;
  10142. this._fn(this);
  10143. }
  10144. else {
  10145. this.breakLoop();
  10146. }
  10147. }
  10148. };
  10149. /**
  10150. * Break the loop and run the success callback.
  10151. */
  10152. AsyncLoop.prototype.breakLoop = function () {
  10153. this._done = true;
  10154. this._successCallback();
  10155. };
  10156. /**
  10157. * Helper function
  10158. */
  10159. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10160. if (offset === void 0) { offset = 0; }
  10161. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10162. loop.executeNext();
  10163. return loop;
  10164. };
  10165. /**
  10166. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10167. * @param iterations total number of iterations
  10168. * @param syncedIterations number of synchronous iterations in each async iteration.
  10169. * @param fn the function to call each iteration.
  10170. * @param callback a success call back that will be called when iterating stops.
  10171. * @param breakFunction a break condition (optional)
  10172. * @param timeout timeout settings for the setTimeout function. default - 0.
  10173. * @constructor
  10174. */
  10175. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10176. if (timeout === void 0) { timeout = 0; }
  10177. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10178. if (breakFunction && breakFunction())
  10179. loop.breakLoop();
  10180. else {
  10181. setTimeout(function () {
  10182. for (var i = 0; i < syncedIterations; ++i) {
  10183. var iteration = (loop.index * syncedIterations) + i;
  10184. if (iteration >= iterations)
  10185. break;
  10186. fn(iteration);
  10187. if (breakFunction && breakFunction()) {
  10188. loop.breakLoop();
  10189. break;
  10190. }
  10191. }
  10192. loop.executeNext();
  10193. }, timeout);
  10194. }
  10195. }, callback);
  10196. };
  10197. return AsyncLoop;
  10198. }());
  10199. BABYLON.AsyncLoop = AsyncLoop;
  10200. })(BABYLON || (BABYLON = {}));
  10201. //# sourceMappingURL=babylon.tools.js.map
  10202. var BABYLON;
  10203. (function (BABYLON) {
  10204. var PromiseStates;
  10205. (function (PromiseStates) {
  10206. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10207. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10208. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10209. })(PromiseStates || (PromiseStates = {}));
  10210. var FulFillmentAgregator = /** @class */ (function () {
  10211. function FulFillmentAgregator() {
  10212. this.count = 0;
  10213. this.target = 0;
  10214. this.results = [];
  10215. }
  10216. return FulFillmentAgregator;
  10217. }());
  10218. var InternalPromise = /** @class */ (function () {
  10219. function InternalPromise(resolver) {
  10220. var _this = this;
  10221. this._state = PromiseStates.Pending;
  10222. this._children = new Array();
  10223. this._rejectWasConsumed = false;
  10224. if (!resolver) {
  10225. return;
  10226. }
  10227. try {
  10228. resolver(function (value) {
  10229. _this._resolve(value);
  10230. }, function (reason) {
  10231. _this._reject(reason);
  10232. });
  10233. }
  10234. catch (e) {
  10235. this._reject(e);
  10236. }
  10237. }
  10238. Object.defineProperty(InternalPromise.prototype, "_result", {
  10239. get: function () {
  10240. return this._resultValue;
  10241. },
  10242. set: function (value) {
  10243. this._resultValue = value;
  10244. if (this._parent && this._parent._result === undefined) {
  10245. this._parent._result = value;
  10246. }
  10247. },
  10248. enumerable: true,
  10249. configurable: true
  10250. });
  10251. InternalPromise.prototype.catch = function (onRejected) {
  10252. return this.then(undefined, onRejected);
  10253. };
  10254. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10255. var _this = this;
  10256. var newPromise = new InternalPromise();
  10257. newPromise._onFulfilled = onFulfilled;
  10258. newPromise._onRejected = onRejected;
  10259. // Composition
  10260. this._children.push(newPromise);
  10261. newPromise._parent = this;
  10262. if (this._state !== PromiseStates.Pending) {
  10263. BABYLON.Tools.SetImmediate(function () {
  10264. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10265. var returnedValue = newPromise._resolve(_this._result);
  10266. if (returnedValue !== undefined && returnedValue !== null) {
  10267. if (returnedValue._state !== undefined) {
  10268. var returnedPromise = returnedValue;
  10269. newPromise._children.push(returnedPromise);
  10270. returnedPromise._parent = newPromise;
  10271. newPromise = returnedPromise;
  10272. }
  10273. else {
  10274. newPromise._result = returnedValue;
  10275. }
  10276. }
  10277. }
  10278. else {
  10279. newPromise._reject(_this._reason);
  10280. }
  10281. });
  10282. }
  10283. return newPromise;
  10284. };
  10285. InternalPromise.prototype._moveChildren = function (children) {
  10286. var _this = this;
  10287. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10288. this._children.forEach(function (child) {
  10289. child._parent = _this;
  10290. });
  10291. if (this._state === PromiseStates.Fulfilled) {
  10292. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10293. var child = _b[_i];
  10294. child._resolve(this._result);
  10295. }
  10296. }
  10297. else if (this._state === PromiseStates.Rejected) {
  10298. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10299. var child = _d[_c];
  10300. child._reject(this._reason);
  10301. }
  10302. }
  10303. var _a;
  10304. };
  10305. InternalPromise.prototype._resolve = function (value) {
  10306. try {
  10307. this._state = PromiseStates.Fulfilled;
  10308. var returnedValue = null;
  10309. if (this._onFulfilled) {
  10310. returnedValue = this._onFulfilled(value);
  10311. }
  10312. if (returnedValue !== undefined && returnedValue !== null) {
  10313. if (returnedValue._state !== undefined) {
  10314. // Transmit children
  10315. var returnedPromise = returnedValue;
  10316. returnedPromise._parent = this;
  10317. returnedPromise._moveChildren(this._children);
  10318. value = returnedPromise._result;
  10319. }
  10320. else {
  10321. value = returnedValue;
  10322. }
  10323. }
  10324. this._result = value;
  10325. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10326. var child = _a[_i];
  10327. child._resolve(value);
  10328. }
  10329. this._children.length = 0;
  10330. delete this._onFulfilled;
  10331. delete this._onRejected;
  10332. }
  10333. catch (e) {
  10334. this._reject(e, true);
  10335. }
  10336. };
  10337. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10338. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10339. this._state = PromiseStates.Rejected;
  10340. this._reason = reason;
  10341. if (this._onRejected && !onLocalThrow) {
  10342. try {
  10343. this._onRejected(reason);
  10344. this._rejectWasConsumed = true;
  10345. }
  10346. catch (e) {
  10347. reason = e;
  10348. }
  10349. }
  10350. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10351. var child = _a[_i];
  10352. if (this._rejectWasConsumed) {
  10353. child._resolve(null);
  10354. }
  10355. else {
  10356. child._reject(reason);
  10357. }
  10358. }
  10359. this._children.length = 0;
  10360. delete this._onFulfilled;
  10361. delete this._onRejected;
  10362. };
  10363. InternalPromise.resolve = function (value) {
  10364. var newPromise = new InternalPromise();
  10365. newPromise._resolve(value);
  10366. return newPromise;
  10367. };
  10368. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10369. promise.then(function (value) {
  10370. agregator.results[index] = value;
  10371. agregator.count++;
  10372. if (agregator.count === agregator.target) {
  10373. agregator.rootPromise._resolve(agregator.results);
  10374. }
  10375. return null;
  10376. }, function (reason) {
  10377. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10378. agregator.rootPromise._reject(reason);
  10379. }
  10380. });
  10381. };
  10382. InternalPromise.all = function (promises) {
  10383. var newPromise = new InternalPromise();
  10384. var agregator = new FulFillmentAgregator();
  10385. agregator.target = promises.length;
  10386. agregator.rootPromise = newPromise;
  10387. if (promises.length) {
  10388. for (var index = 0; index < promises.length; index++) {
  10389. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10390. }
  10391. }
  10392. else {
  10393. newPromise._resolve([]);
  10394. }
  10395. return newPromise;
  10396. };
  10397. InternalPromise.race = function (promises) {
  10398. var newPromise = new InternalPromise();
  10399. if (promises.length) {
  10400. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10401. var promise = promises_1[_i];
  10402. promise.then(function (value) {
  10403. if (newPromise) {
  10404. newPromise._resolve(value);
  10405. newPromise = null;
  10406. }
  10407. return null;
  10408. }, function (reason) {
  10409. if (newPromise) {
  10410. newPromise._reject(reason);
  10411. newPromise = null;
  10412. }
  10413. });
  10414. }
  10415. }
  10416. return newPromise;
  10417. };
  10418. return InternalPromise;
  10419. }());
  10420. /**
  10421. * Helper class that provides a small promise polyfill
  10422. */
  10423. var PromisePolyfill = /** @class */ (function () {
  10424. function PromisePolyfill() {
  10425. }
  10426. /**
  10427. * Static function used to check if the polyfill is required
  10428. * If this is the case then the function will inject the polyfill to window.Promise
  10429. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10430. */
  10431. PromisePolyfill.Apply = function (force) {
  10432. if (force === void 0) { force = false; }
  10433. if (force || typeof Promise === 'undefined') {
  10434. var root = window;
  10435. root.Promise = InternalPromise;
  10436. }
  10437. };
  10438. return PromisePolyfill;
  10439. }());
  10440. BABYLON.PromisePolyfill = PromisePolyfill;
  10441. })(BABYLON || (BABYLON = {}));
  10442. //# sourceMappingURL=babylon.promise.js.map
  10443. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10444. var BABYLON;
  10445. (function (BABYLON) {
  10446. /**
  10447. * Helper class to push actions to a pool of workers.
  10448. */
  10449. var WorkerPool = /** @class */ (function () {
  10450. /**
  10451. * Constructor
  10452. * @param workers Array of workers to use for actions
  10453. */
  10454. function WorkerPool(workers) {
  10455. this._pendingActions = new Array();
  10456. this._workerInfos = workers.map(function (worker) { return ({
  10457. worker: worker,
  10458. active: false
  10459. }); });
  10460. }
  10461. /**
  10462. * Terminates all workers and clears any pending actions.
  10463. */
  10464. WorkerPool.prototype.dispose = function () {
  10465. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10466. var workerInfo = _a[_i];
  10467. workerInfo.worker.terminate();
  10468. }
  10469. delete this._workerInfos;
  10470. delete this._pendingActions;
  10471. };
  10472. /**
  10473. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10474. * pended until a worker has completed its action.
  10475. * @param action The action to perform. Call onComplete when the action is complete.
  10476. */
  10477. WorkerPool.prototype.push = function (action) {
  10478. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10479. var workerInfo = _a[_i];
  10480. if (!workerInfo.active) {
  10481. this._execute(workerInfo, action);
  10482. return;
  10483. }
  10484. }
  10485. this._pendingActions.push(action);
  10486. };
  10487. WorkerPool.prototype._execute = function (workerInfo, action) {
  10488. var _this = this;
  10489. workerInfo.active = true;
  10490. action(workerInfo.worker, function () {
  10491. workerInfo.active = false;
  10492. var nextAction = _this._pendingActions.shift();
  10493. if (nextAction) {
  10494. _this._execute(workerInfo, nextAction);
  10495. }
  10496. });
  10497. };
  10498. return WorkerPool;
  10499. }());
  10500. BABYLON.WorkerPool = WorkerPool;
  10501. })(BABYLON || (BABYLON = {}));
  10502. //# sourceMappingURL=babylon.workerPool.js.map
  10503. var BABYLON;
  10504. (function (BABYLON) {
  10505. /**
  10506. * @hidden
  10507. **/
  10508. var _AlphaState = /** @class */ (function () {
  10509. /**
  10510. * Initializes the state.
  10511. */
  10512. function _AlphaState() {
  10513. this._isAlphaBlendDirty = false;
  10514. this._isBlendFunctionParametersDirty = false;
  10515. this._isBlendEquationParametersDirty = false;
  10516. this._isBlendConstantsDirty = false;
  10517. this._alphaBlend = false;
  10518. this._blendFunctionParameters = new Array(4);
  10519. this._blendEquationParameters = new Array(2);
  10520. this._blendConstants = new Array(4);
  10521. this.reset();
  10522. }
  10523. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10524. get: function () {
  10525. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10526. },
  10527. enumerable: true,
  10528. configurable: true
  10529. });
  10530. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10531. get: function () {
  10532. return this._alphaBlend;
  10533. },
  10534. set: function (value) {
  10535. if (this._alphaBlend === value) {
  10536. return;
  10537. }
  10538. this._alphaBlend = value;
  10539. this._isAlphaBlendDirty = true;
  10540. },
  10541. enumerable: true,
  10542. configurable: true
  10543. });
  10544. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10545. if (this._blendConstants[0] === r &&
  10546. this._blendConstants[1] === g &&
  10547. this._blendConstants[2] === b &&
  10548. this._blendConstants[3] === a) {
  10549. return;
  10550. }
  10551. this._blendConstants[0] = r;
  10552. this._blendConstants[1] = g;
  10553. this._blendConstants[2] = b;
  10554. this._blendConstants[3] = a;
  10555. this._isBlendConstantsDirty = true;
  10556. };
  10557. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10558. if (this._blendFunctionParameters[0] === value0 &&
  10559. this._blendFunctionParameters[1] === value1 &&
  10560. this._blendFunctionParameters[2] === value2 &&
  10561. this._blendFunctionParameters[3] === value3) {
  10562. return;
  10563. }
  10564. this._blendFunctionParameters[0] = value0;
  10565. this._blendFunctionParameters[1] = value1;
  10566. this._blendFunctionParameters[2] = value2;
  10567. this._blendFunctionParameters[3] = value3;
  10568. this._isBlendFunctionParametersDirty = true;
  10569. };
  10570. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10571. if (this._blendEquationParameters[0] === rgb &&
  10572. this._blendEquationParameters[1] === alpha) {
  10573. return;
  10574. }
  10575. this._blendEquationParameters[0] = rgb;
  10576. this._blendEquationParameters[1] = alpha;
  10577. this._isBlendEquationParametersDirty = true;
  10578. };
  10579. _AlphaState.prototype.reset = function () {
  10580. this._alphaBlend = false;
  10581. this._blendFunctionParameters[0] = null;
  10582. this._blendFunctionParameters[1] = null;
  10583. this._blendFunctionParameters[2] = null;
  10584. this._blendFunctionParameters[3] = null;
  10585. this._blendEquationParameters[0] = null;
  10586. this._blendEquationParameters[1] = null;
  10587. this._blendConstants[0] = null;
  10588. this._blendConstants[1] = null;
  10589. this._blendConstants[2] = null;
  10590. this._blendConstants[3] = null;
  10591. this._isAlphaBlendDirty = true;
  10592. this._isBlendFunctionParametersDirty = false;
  10593. this._isBlendEquationParametersDirty = false;
  10594. this._isBlendConstantsDirty = false;
  10595. };
  10596. _AlphaState.prototype.apply = function (gl) {
  10597. if (!this.isDirty) {
  10598. return;
  10599. }
  10600. // Alpha blend
  10601. if (this._isAlphaBlendDirty) {
  10602. if (this._alphaBlend) {
  10603. gl.enable(gl.BLEND);
  10604. }
  10605. else {
  10606. gl.disable(gl.BLEND);
  10607. }
  10608. this._isAlphaBlendDirty = false;
  10609. }
  10610. // Alpha function
  10611. if (this._isBlendFunctionParametersDirty) {
  10612. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10613. this._isBlendFunctionParametersDirty = false;
  10614. }
  10615. // Alpha equation
  10616. if (this._isBlendEquationParametersDirty) {
  10617. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10618. this._isBlendEquationParametersDirty = false;
  10619. }
  10620. // Constants
  10621. if (this._isBlendConstantsDirty) {
  10622. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10623. this._isBlendConstantsDirty = false;
  10624. }
  10625. };
  10626. return _AlphaState;
  10627. }());
  10628. BABYLON._AlphaState = _AlphaState;
  10629. })(BABYLON || (BABYLON = {}));
  10630. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10631. var BABYLON;
  10632. (function (BABYLON) {
  10633. /**
  10634. * @hidden
  10635. **/
  10636. var _DepthCullingState = /** @class */ (function () {
  10637. /**
  10638. * Initializes the state.
  10639. */
  10640. function _DepthCullingState() {
  10641. this._isDepthTestDirty = false;
  10642. this._isDepthMaskDirty = false;
  10643. this._isDepthFuncDirty = false;
  10644. this._isCullFaceDirty = false;
  10645. this._isCullDirty = false;
  10646. this._isZOffsetDirty = false;
  10647. this._isFrontFaceDirty = false;
  10648. this.reset();
  10649. }
  10650. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10651. get: function () {
  10652. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10653. },
  10654. enumerable: true,
  10655. configurable: true
  10656. });
  10657. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10658. get: function () {
  10659. return this._zOffset;
  10660. },
  10661. set: function (value) {
  10662. if (this._zOffset === value) {
  10663. return;
  10664. }
  10665. this._zOffset = value;
  10666. this._isZOffsetDirty = true;
  10667. },
  10668. enumerable: true,
  10669. configurable: true
  10670. });
  10671. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10672. get: function () {
  10673. return this._cullFace;
  10674. },
  10675. set: function (value) {
  10676. if (this._cullFace === value) {
  10677. return;
  10678. }
  10679. this._cullFace = value;
  10680. this._isCullFaceDirty = true;
  10681. },
  10682. enumerable: true,
  10683. configurable: true
  10684. });
  10685. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10686. get: function () {
  10687. return this._cull;
  10688. },
  10689. set: function (value) {
  10690. if (this._cull === value) {
  10691. return;
  10692. }
  10693. this._cull = value;
  10694. this._isCullDirty = true;
  10695. },
  10696. enumerable: true,
  10697. configurable: true
  10698. });
  10699. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10700. get: function () {
  10701. return this._depthFunc;
  10702. },
  10703. set: function (value) {
  10704. if (this._depthFunc === value) {
  10705. return;
  10706. }
  10707. this._depthFunc = value;
  10708. this._isDepthFuncDirty = true;
  10709. },
  10710. enumerable: true,
  10711. configurable: true
  10712. });
  10713. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10714. get: function () {
  10715. return this._depthMask;
  10716. },
  10717. set: function (value) {
  10718. if (this._depthMask === value) {
  10719. return;
  10720. }
  10721. this._depthMask = value;
  10722. this._isDepthMaskDirty = true;
  10723. },
  10724. enumerable: true,
  10725. configurable: true
  10726. });
  10727. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10728. get: function () {
  10729. return this._depthTest;
  10730. },
  10731. set: function (value) {
  10732. if (this._depthTest === value) {
  10733. return;
  10734. }
  10735. this._depthTest = value;
  10736. this._isDepthTestDirty = true;
  10737. },
  10738. enumerable: true,
  10739. configurable: true
  10740. });
  10741. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10742. get: function () {
  10743. return this._frontFace;
  10744. },
  10745. set: function (value) {
  10746. if (this._frontFace === value) {
  10747. return;
  10748. }
  10749. this._frontFace = value;
  10750. this._isFrontFaceDirty = true;
  10751. },
  10752. enumerable: true,
  10753. configurable: true
  10754. });
  10755. _DepthCullingState.prototype.reset = function () {
  10756. this._depthMask = true;
  10757. this._depthTest = true;
  10758. this._depthFunc = null;
  10759. this._cullFace = null;
  10760. this._cull = null;
  10761. this._zOffset = 0;
  10762. this._frontFace = null;
  10763. this._isDepthTestDirty = true;
  10764. this._isDepthMaskDirty = true;
  10765. this._isDepthFuncDirty = false;
  10766. this._isCullFaceDirty = false;
  10767. this._isCullDirty = false;
  10768. this._isZOffsetDirty = false;
  10769. this._isFrontFaceDirty = false;
  10770. };
  10771. _DepthCullingState.prototype.apply = function (gl) {
  10772. if (!this.isDirty) {
  10773. return;
  10774. }
  10775. // Cull
  10776. if (this._isCullDirty) {
  10777. if (this.cull) {
  10778. gl.enable(gl.CULL_FACE);
  10779. }
  10780. else {
  10781. gl.disable(gl.CULL_FACE);
  10782. }
  10783. this._isCullDirty = false;
  10784. }
  10785. // Cull face
  10786. if (this._isCullFaceDirty) {
  10787. gl.cullFace(this.cullFace);
  10788. this._isCullFaceDirty = false;
  10789. }
  10790. // Depth mask
  10791. if (this._isDepthMaskDirty) {
  10792. gl.depthMask(this.depthMask);
  10793. this._isDepthMaskDirty = false;
  10794. }
  10795. // Depth test
  10796. if (this._isDepthTestDirty) {
  10797. if (this.depthTest) {
  10798. gl.enable(gl.DEPTH_TEST);
  10799. }
  10800. else {
  10801. gl.disable(gl.DEPTH_TEST);
  10802. }
  10803. this._isDepthTestDirty = false;
  10804. }
  10805. // Depth func
  10806. if (this._isDepthFuncDirty) {
  10807. gl.depthFunc(this.depthFunc);
  10808. this._isDepthFuncDirty = false;
  10809. }
  10810. // zOffset
  10811. if (this._isZOffsetDirty) {
  10812. if (this.zOffset) {
  10813. gl.enable(gl.POLYGON_OFFSET_FILL);
  10814. gl.polygonOffset(this.zOffset, 0);
  10815. }
  10816. else {
  10817. gl.disable(gl.POLYGON_OFFSET_FILL);
  10818. }
  10819. this._isZOffsetDirty = false;
  10820. }
  10821. // Front face
  10822. if (this._isFrontFaceDirty) {
  10823. gl.frontFace(this.frontFace);
  10824. this._isFrontFaceDirty = false;
  10825. }
  10826. };
  10827. return _DepthCullingState;
  10828. }());
  10829. BABYLON._DepthCullingState = _DepthCullingState;
  10830. })(BABYLON || (BABYLON = {}));
  10831. //# sourceMappingURL=babylon.depthCullingState.js.map
  10832. var BABYLON;
  10833. (function (BABYLON) {
  10834. /**
  10835. * @hidden
  10836. **/
  10837. var _StencilState = /** @class */ (function () {
  10838. function _StencilState() {
  10839. this._isStencilTestDirty = false;
  10840. this._isStencilMaskDirty = false;
  10841. this._isStencilFuncDirty = false;
  10842. this._isStencilOpDirty = false;
  10843. this.reset();
  10844. }
  10845. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10846. get: function () {
  10847. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10848. },
  10849. enumerable: true,
  10850. configurable: true
  10851. });
  10852. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10853. get: function () {
  10854. return this._stencilFunc;
  10855. },
  10856. set: function (value) {
  10857. if (this._stencilFunc === value) {
  10858. return;
  10859. }
  10860. this._stencilFunc = value;
  10861. this._isStencilFuncDirty = true;
  10862. },
  10863. enumerable: true,
  10864. configurable: true
  10865. });
  10866. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  10867. get: function () {
  10868. return this._stencilFuncRef;
  10869. },
  10870. set: function (value) {
  10871. if (this._stencilFuncRef === value) {
  10872. return;
  10873. }
  10874. this._stencilFuncRef = value;
  10875. this._isStencilFuncDirty = true;
  10876. },
  10877. enumerable: true,
  10878. configurable: true
  10879. });
  10880. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  10881. get: function () {
  10882. return this._stencilFuncMask;
  10883. },
  10884. set: function (value) {
  10885. if (this._stencilFuncMask === value) {
  10886. return;
  10887. }
  10888. this._stencilFuncMask = value;
  10889. this._isStencilFuncDirty = true;
  10890. },
  10891. enumerable: true,
  10892. configurable: true
  10893. });
  10894. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  10895. get: function () {
  10896. return this._stencilOpStencilFail;
  10897. },
  10898. set: function (value) {
  10899. if (this._stencilOpStencilFail === value) {
  10900. return;
  10901. }
  10902. this._stencilOpStencilFail = value;
  10903. this._isStencilOpDirty = true;
  10904. },
  10905. enumerable: true,
  10906. configurable: true
  10907. });
  10908. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  10909. get: function () {
  10910. return this._stencilOpDepthFail;
  10911. },
  10912. set: function (value) {
  10913. if (this._stencilOpDepthFail === value) {
  10914. return;
  10915. }
  10916. this._stencilOpDepthFail = value;
  10917. this._isStencilOpDirty = true;
  10918. },
  10919. enumerable: true,
  10920. configurable: true
  10921. });
  10922. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  10923. get: function () {
  10924. return this._stencilOpStencilDepthPass;
  10925. },
  10926. set: function (value) {
  10927. if (this._stencilOpStencilDepthPass === value) {
  10928. return;
  10929. }
  10930. this._stencilOpStencilDepthPass = value;
  10931. this._isStencilOpDirty = true;
  10932. },
  10933. enumerable: true,
  10934. configurable: true
  10935. });
  10936. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  10937. get: function () {
  10938. return this._stencilMask;
  10939. },
  10940. set: function (value) {
  10941. if (this._stencilMask === value) {
  10942. return;
  10943. }
  10944. this._stencilMask = value;
  10945. this._isStencilMaskDirty = true;
  10946. },
  10947. enumerable: true,
  10948. configurable: true
  10949. });
  10950. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  10951. get: function () {
  10952. return this._stencilTest;
  10953. },
  10954. set: function (value) {
  10955. if (this._stencilTest === value) {
  10956. return;
  10957. }
  10958. this._stencilTest = value;
  10959. this._isStencilTestDirty = true;
  10960. },
  10961. enumerable: true,
  10962. configurable: true
  10963. });
  10964. _StencilState.prototype.reset = function () {
  10965. this._stencilTest = false;
  10966. this._stencilMask = 0xFF;
  10967. this._stencilFunc = BABYLON.Engine.ALWAYS;
  10968. this._stencilFuncRef = 1;
  10969. this._stencilFuncMask = 0xFF;
  10970. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  10971. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  10972. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  10973. this._isStencilTestDirty = true;
  10974. this._isStencilMaskDirty = true;
  10975. this._isStencilFuncDirty = true;
  10976. this._isStencilOpDirty = true;
  10977. };
  10978. _StencilState.prototype.apply = function (gl) {
  10979. if (!this.isDirty) {
  10980. return;
  10981. }
  10982. // Stencil test
  10983. if (this._isStencilTestDirty) {
  10984. if (this.stencilTest) {
  10985. gl.enable(gl.STENCIL_TEST);
  10986. }
  10987. else {
  10988. gl.disable(gl.STENCIL_TEST);
  10989. }
  10990. this._isStencilTestDirty = false;
  10991. }
  10992. // Stencil mask
  10993. if (this._isStencilMaskDirty) {
  10994. gl.stencilMask(this.stencilMask);
  10995. this._isStencilMaskDirty = false;
  10996. }
  10997. // Stencil func
  10998. if (this._isStencilFuncDirty) {
  10999. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11000. this._isStencilFuncDirty = false;
  11001. }
  11002. // Stencil op
  11003. if (this._isStencilOpDirty) {
  11004. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11005. this._isStencilOpDirty = false;
  11006. }
  11007. };
  11008. return _StencilState;
  11009. }());
  11010. BABYLON._StencilState = _StencilState;
  11011. })(BABYLON || (BABYLON = {}));
  11012. //# sourceMappingURL=babylon.stencilState.js.map
  11013. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11014. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11015. s = arguments[i];
  11016. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11017. t[p] = s[p];
  11018. }
  11019. return t;
  11020. };
  11021. var BABYLON;
  11022. (function (BABYLON) {
  11023. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11024. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11025. };
  11026. var compileRawShader = function (gl, source, type) {
  11027. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11028. gl.shaderSource(shader, source);
  11029. gl.compileShader(shader);
  11030. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11031. var log = gl.getShaderInfoLog(shader);
  11032. if (log) {
  11033. throw new Error(log);
  11034. }
  11035. }
  11036. if (!shader) {
  11037. throw new Error("Something went wrong while compile the shader.");
  11038. }
  11039. return shader;
  11040. };
  11041. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11042. var magFilter = gl.NEAREST;
  11043. var minFilter = gl.NEAREST;
  11044. switch (samplingMode) {
  11045. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11046. magFilter = gl.LINEAR;
  11047. if (generateMipMaps) {
  11048. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11049. }
  11050. else {
  11051. minFilter = gl.LINEAR;
  11052. }
  11053. break;
  11054. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11055. magFilter = gl.LINEAR;
  11056. if (generateMipMaps) {
  11057. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11058. }
  11059. else {
  11060. minFilter = gl.LINEAR;
  11061. }
  11062. break;
  11063. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11064. magFilter = gl.NEAREST;
  11065. if (generateMipMaps) {
  11066. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11067. }
  11068. else {
  11069. minFilter = gl.NEAREST;
  11070. }
  11071. break;
  11072. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11073. magFilter = gl.NEAREST;
  11074. if (generateMipMaps) {
  11075. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11076. }
  11077. else {
  11078. minFilter = gl.NEAREST;
  11079. }
  11080. break;
  11081. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11082. magFilter = gl.NEAREST;
  11083. if (generateMipMaps) {
  11084. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11085. }
  11086. else {
  11087. minFilter = gl.LINEAR;
  11088. }
  11089. break;
  11090. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11091. magFilter = gl.NEAREST;
  11092. if (generateMipMaps) {
  11093. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11094. }
  11095. else {
  11096. minFilter = gl.LINEAR;
  11097. }
  11098. break;
  11099. case BABYLON.Texture.NEAREST_LINEAR:
  11100. magFilter = gl.NEAREST;
  11101. minFilter = gl.LINEAR;
  11102. break;
  11103. case BABYLON.Texture.NEAREST_NEAREST:
  11104. magFilter = gl.NEAREST;
  11105. minFilter = gl.NEAREST;
  11106. break;
  11107. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11108. magFilter = gl.LINEAR;
  11109. if (generateMipMaps) {
  11110. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11111. }
  11112. else {
  11113. minFilter = gl.NEAREST;
  11114. }
  11115. break;
  11116. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11117. magFilter = gl.LINEAR;
  11118. if (generateMipMaps) {
  11119. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11120. }
  11121. else {
  11122. minFilter = gl.NEAREST;
  11123. }
  11124. break;
  11125. case BABYLON.Texture.LINEAR_LINEAR:
  11126. magFilter = gl.LINEAR;
  11127. minFilter = gl.LINEAR;
  11128. break;
  11129. case BABYLON.Texture.LINEAR_NEAREST:
  11130. magFilter = gl.LINEAR;
  11131. minFilter = gl.NEAREST;
  11132. break;
  11133. }
  11134. return {
  11135. min: minFilter,
  11136. mag: magFilter
  11137. };
  11138. };
  11139. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11140. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11141. var img;
  11142. var onload = function () {
  11143. loadedImages[index] = img;
  11144. loadedImages._internalCount++;
  11145. if (scene) {
  11146. scene._removePendingData(img);
  11147. }
  11148. if (loadedImages._internalCount === 6) {
  11149. onfinish(loadedImages);
  11150. }
  11151. };
  11152. var onerror = function (message, exception) {
  11153. if (scene) {
  11154. scene._removePendingData(img);
  11155. }
  11156. if (onErrorCallBack) {
  11157. onErrorCallBack(message, exception);
  11158. }
  11159. };
  11160. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11161. if (scene) {
  11162. scene._addPendingData(img);
  11163. }
  11164. };
  11165. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11166. if (onError === void 0) { onError = null; }
  11167. var loadedImages = [];
  11168. loadedImages._internalCount = 0;
  11169. for (var index = 0; index < 6; index++) {
  11170. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11171. }
  11172. };
  11173. var BufferPointer = /** @class */ (function () {
  11174. function BufferPointer() {
  11175. }
  11176. return BufferPointer;
  11177. }());
  11178. /**
  11179. * Interface for attribute information associated with buffer instanciation
  11180. */
  11181. var InstancingAttributeInfo = /** @class */ (function () {
  11182. function InstancingAttributeInfo() {
  11183. }
  11184. return InstancingAttributeInfo;
  11185. }());
  11186. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11187. /**
  11188. * Define options used to create a render target texture
  11189. */
  11190. var RenderTargetCreationOptions = /** @class */ (function () {
  11191. function RenderTargetCreationOptions() {
  11192. }
  11193. return RenderTargetCreationOptions;
  11194. }());
  11195. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11196. /**
  11197. * Define options used to create a depth texture
  11198. */
  11199. var DepthTextureCreationOptions = /** @class */ (function () {
  11200. function DepthTextureCreationOptions() {
  11201. }
  11202. return DepthTextureCreationOptions;
  11203. }());
  11204. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11205. /**
  11206. * Class used to describe the capabilities of the engine relatively to the current browser
  11207. */
  11208. var EngineCapabilities = /** @class */ (function () {
  11209. function EngineCapabilities() {
  11210. }
  11211. return EngineCapabilities;
  11212. }());
  11213. BABYLON.EngineCapabilities = EngineCapabilities;
  11214. /**
  11215. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11216. */
  11217. var Engine = /** @class */ (function () {
  11218. /**
  11219. * Creates a new engine
  11220. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11221. * @param antialias defines enable antialiasing (default: false)
  11222. * @param options defines further options to be sent to the getContext() function
  11223. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11224. */
  11225. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11226. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11227. var _this = this;
  11228. // Public members
  11229. /**
  11230. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11231. */
  11232. this.forcePOTTextures = false;
  11233. /**
  11234. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11235. */
  11236. this.isFullscreen = false;
  11237. /**
  11238. * Gets a boolean indicating if the pointer is currently locked
  11239. */
  11240. this.isPointerLock = false;
  11241. /**
  11242. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11243. */
  11244. this.cullBackFaces = true;
  11245. /**
  11246. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11247. */
  11248. this.renderEvenInBackground = true;
  11249. /**
  11250. * Gets or sets a boolean indicating that cache can be kept between frames
  11251. */
  11252. this.preventCacheWipeBetweenFrames = false;
  11253. /**
  11254. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11255. **/
  11256. this.enableOfflineSupport = false;
  11257. /**
  11258. * 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)
  11259. **/
  11260. this.disableManifestCheck = false;
  11261. /**
  11262. * Gets the list of created scenes
  11263. */
  11264. this.scenes = new Array();
  11265. /**
  11266. * Gets the list of created postprocesses
  11267. */
  11268. this.postProcesses = new Array();
  11269. // Observables
  11270. /**
  11271. * Observable event triggered each time the rendering canvas is resized
  11272. */
  11273. this.onResizeObservable = new BABYLON.Observable();
  11274. /**
  11275. * Observable event triggered each time the canvas loses focus
  11276. */
  11277. this.onCanvasBlurObservable = new BABYLON.Observable();
  11278. /**
  11279. * Observable event triggered each time the canvas gains focus
  11280. */
  11281. this.onCanvasFocusObservable = new BABYLON.Observable();
  11282. /**
  11283. * Observable event triggered each time the canvas receives pointerout event
  11284. */
  11285. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11286. /**
  11287. * Observable event triggered before each texture is initialized
  11288. */
  11289. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11290. //WebVR
  11291. this._vrDisplay = undefined;
  11292. this._vrSupported = false;
  11293. this._vrExclusivePointerMode = false;
  11294. // Uniform buffers list
  11295. /**
  11296. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11297. */
  11298. this.disableUniformBuffers = false;
  11299. /** @hidden */
  11300. this._uniformBuffers = new Array();
  11301. // Observables
  11302. /**
  11303. * Observable raised when the engine begins a new frame
  11304. */
  11305. this.onBeginFrameObservable = new BABYLON.Observable();
  11306. /**
  11307. * Observable raised when the engine ends the current frame
  11308. */
  11309. this.onEndFrameObservable = new BABYLON.Observable();
  11310. /**
  11311. * Observable raised when the engine is about to compile a shader
  11312. */
  11313. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11314. /**
  11315. * Observable raised when the engine has jsut compiled a shader
  11316. */
  11317. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11318. this._windowIsBackground = false;
  11319. this._webGLVersion = 1.0;
  11320. /** @hidden */
  11321. this._badOS = false;
  11322. /** @hidden */
  11323. this._badDesktopOS = false;
  11324. /**
  11325. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11326. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11327. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11328. */
  11329. this.disableTextureBindingOptimization = false;
  11330. /**
  11331. * Observable signaled when VR display mode changes
  11332. */
  11333. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11334. /**
  11335. * Observable signaled when VR request present is complete
  11336. */
  11337. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11338. /**
  11339. * Observable signaled when VR request present starts
  11340. */
  11341. this.onVRRequestPresentStart = new BABYLON.Observable();
  11342. this._colorWrite = true;
  11343. /** @hidden */
  11344. this._drawCalls = new BABYLON.PerfCounter();
  11345. /** @hidden */
  11346. this._textureCollisions = new BABYLON.PerfCounter();
  11347. this._renderingQueueLaunched = false;
  11348. this._activeRenderLoops = new Array();
  11349. // Deterministic lockstepMaxSteps
  11350. this._deterministicLockstep = false;
  11351. this._lockstepMaxSteps = 4;
  11352. // Lost context
  11353. /**
  11354. * Observable signaled when a context lost event is raised
  11355. */
  11356. this.onContextLostObservable = new BABYLON.Observable();
  11357. /**
  11358. * Observable signaled when a context restored event is raised
  11359. */
  11360. this.onContextRestoredObservable = new BABYLON.Observable();
  11361. this._contextWasLost = false;
  11362. this._doNotHandleContextLost = false;
  11363. // FPS
  11364. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11365. this._fps = 60;
  11366. this._deltaTime = 0;
  11367. /**
  11368. * Turn this value on if you want to pause FPS computation when in background
  11369. */
  11370. this.disablePerformanceMonitorInBackground = false;
  11371. // States
  11372. /** @hidden */
  11373. this._depthCullingState = new BABYLON._DepthCullingState();
  11374. /** @hidden */
  11375. this._stencilState = new BABYLON._StencilState();
  11376. /** @hidden */
  11377. this._alphaState = new BABYLON._AlphaState();
  11378. /** @hidden */
  11379. this._alphaMode = Engine.ALPHA_DISABLE;
  11380. // Cache
  11381. this._internalTexturesCache = new Array();
  11382. /** @hidden */
  11383. this._activeChannel = 0;
  11384. this._currentTextureChannel = -1;
  11385. /** @hidden */
  11386. this._boundTexturesCache = {};
  11387. this._compiledEffects = {};
  11388. this._vertexAttribArraysEnabled = [];
  11389. this._uintIndicesCurrentlySet = false;
  11390. this._currentBoundBuffer = new Array();
  11391. this._currentBufferPointers = new Array();
  11392. this._currentInstanceLocations = new Array();
  11393. this._currentInstanceBuffers = new Array();
  11394. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11395. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11396. this._vaoRecordInProgress = false;
  11397. this._mustWipeVertexAttributes = false;
  11398. this._nextFreeTextureSlots = new Array();
  11399. this._maxSimultaneousTextures = 0;
  11400. this._activeRequests = new Array();
  11401. // Hardware supported Compressed Textures
  11402. this._texturesSupported = new Array();
  11403. this._onVRFullScreenTriggered = function () {
  11404. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11405. //get the old size before we change
  11406. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11407. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11408. //get the width and height, change the render size
  11409. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11410. _this.setHardwareScalingLevel(1);
  11411. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11412. }
  11413. else {
  11414. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11415. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11416. }
  11417. };
  11418. this._boundUniforms = {};
  11419. // Register promises
  11420. BABYLON.PromisePolyfill.Apply();
  11421. var canvas = null;
  11422. Engine.Instances.push(this);
  11423. if (!canvasOrContext) {
  11424. return;
  11425. }
  11426. options = options || {};
  11427. if (canvasOrContext.getContext) {
  11428. canvas = canvasOrContext;
  11429. this._renderingCanvas = canvas;
  11430. if (antialias != null) {
  11431. options.antialias = antialias;
  11432. }
  11433. if (options.deterministicLockstep === undefined) {
  11434. options.deterministicLockstep = false;
  11435. }
  11436. if (options.lockstepMaxSteps === undefined) {
  11437. options.lockstepMaxSteps = 4;
  11438. }
  11439. if (options.preserveDrawingBuffer === undefined) {
  11440. options.preserveDrawingBuffer = false;
  11441. }
  11442. if (options.audioEngine === undefined) {
  11443. options.audioEngine = true;
  11444. }
  11445. if (options.stencil === undefined) {
  11446. options.stencil = true;
  11447. }
  11448. this._deterministicLockstep = options.deterministicLockstep;
  11449. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11450. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11451. // Exceptions
  11452. if (navigator && navigator.userAgent) {
  11453. var ua = navigator.userAgent;
  11454. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11455. var exception = _a[_i];
  11456. var key = exception.key;
  11457. var targets = exception.targets;
  11458. if (ua.indexOf(key) > -1) {
  11459. if (exception.capture && exception.captureConstraint) {
  11460. var capture = exception.capture;
  11461. var constraint = exception.captureConstraint;
  11462. var regex = new RegExp(capture);
  11463. var matches = regex.exec(ua);
  11464. if (matches && matches.length > 0) {
  11465. var capturedValue = parseInt(matches[matches.length - 1]);
  11466. if (capturedValue >= constraint) {
  11467. continue;
  11468. }
  11469. }
  11470. }
  11471. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11472. var target = targets_1[_b];
  11473. switch (target) {
  11474. case "uniformBuffer":
  11475. this.disableUniformBuffers = true;
  11476. break;
  11477. case "textureBindingOptimization":
  11478. this.disableTextureBindingOptimization = true;
  11479. break;
  11480. }
  11481. }
  11482. }
  11483. }
  11484. }
  11485. // GL
  11486. if (!options.disableWebGL2Support) {
  11487. try {
  11488. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11489. if (this._gl) {
  11490. this._webGLVersion = 2.0;
  11491. }
  11492. }
  11493. catch (e) {
  11494. // Do nothing
  11495. }
  11496. }
  11497. if (!this._gl) {
  11498. if (!canvas) {
  11499. throw new Error("The provided canvas is null or undefined.");
  11500. }
  11501. try {
  11502. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11503. }
  11504. catch (e) {
  11505. throw new Error("WebGL not supported");
  11506. }
  11507. }
  11508. if (!this._gl) {
  11509. throw new Error("WebGL not supported");
  11510. }
  11511. this._onCanvasFocus = function () {
  11512. _this.onCanvasFocusObservable.notifyObservers(_this);
  11513. };
  11514. this._onCanvasBlur = function () {
  11515. _this.onCanvasBlurObservable.notifyObservers(_this);
  11516. };
  11517. canvas.addEventListener("focus", this._onCanvasFocus);
  11518. canvas.addEventListener("blur", this._onCanvasBlur);
  11519. this._onBlur = function () {
  11520. if (_this.disablePerformanceMonitorInBackground) {
  11521. _this._performanceMonitor.disable();
  11522. }
  11523. _this._windowIsBackground = true;
  11524. };
  11525. this._onFocus = function () {
  11526. if (_this.disablePerformanceMonitorInBackground) {
  11527. _this._performanceMonitor.enable();
  11528. }
  11529. _this._windowIsBackground = false;
  11530. };
  11531. this._onCanvasPointerOut = function (ev) {
  11532. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11533. };
  11534. window.addEventListener("blur", this._onBlur);
  11535. window.addEventListener("focus", this._onFocus);
  11536. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11537. // Context lost
  11538. if (!this._doNotHandleContextLost) {
  11539. this._onContextLost = function (evt) {
  11540. evt.preventDefault();
  11541. _this._contextWasLost = true;
  11542. BABYLON.Tools.Warn("WebGL context lost.");
  11543. _this.onContextLostObservable.notifyObservers(_this);
  11544. };
  11545. this._onContextRestored = function (evt) {
  11546. // Adding a timeout to avoid race condition at browser level
  11547. setTimeout(function () {
  11548. // Rebuild gl context
  11549. _this._initGLContext();
  11550. // Rebuild effects
  11551. _this._rebuildEffects();
  11552. // Rebuild textures
  11553. _this._rebuildInternalTextures();
  11554. // Rebuild buffers
  11555. _this._rebuildBuffers();
  11556. // Cache
  11557. _this.wipeCaches(true);
  11558. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11559. _this.onContextRestoredObservable.notifyObservers(_this);
  11560. _this._contextWasLost = false;
  11561. }, 0);
  11562. };
  11563. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11564. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11565. }
  11566. }
  11567. else {
  11568. this._gl = canvasOrContext;
  11569. this._renderingCanvas = this._gl.canvas;
  11570. if (this._gl.renderbufferStorageMultisample) {
  11571. this._webGLVersion = 2.0;
  11572. }
  11573. options.stencil = this._gl.getContextAttributes().stencil;
  11574. }
  11575. // Viewport
  11576. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11577. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11578. this.resize();
  11579. this._isStencilEnable = options.stencil ? true : false;
  11580. this._initGLContext();
  11581. if (canvas) {
  11582. // Fullscreen
  11583. this._onFullscreenChange = function () {
  11584. if (document.fullscreen !== undefined) {
  11585. _this.isFullscreen = document.fullscreen;
  11586. }
  11587. else if (document.mozFullScreen !== undefined) {
  11588. _this.isFullscreen = document.mozFullScreen;
  11589. }
  11590. else if (document.webkitIsFullScreen !== undefined) {
  11591. _this.isFullscreen = document.webkitIsFullScreen;
  11592. }
  11593. else if (document.msIsFullScreen !== undefined) {
  11594. _this.isFullscreen = document.msIsFullScreen;
  11595. }
  11596. // Pointer lock
  11597. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11598. canvas.requestPointerLock = canvas.requestPointerLock ||
  11599. canvas.msRequestPointerLock ||
  11600. canvas.mozRequestPointerLock ||
  11601. canvas.webkitRequestPointerLock;
  11602. if (canvas.requestPointerLock) {
  11603. canvas.requestPointerLock();
  11604. }
  11605. }
  11606. };
  11607. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11608. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11609. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11610. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11611. // Pointer lock
  11612. this._onPointerLockChange = function () {
  11613. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11614. document.webkitPointerLockElement === canvas ||
  11615. document.msPointerLockElement === canvas ||
  11616. document.pointerLockElement === canvas);
  11617. };
  11618. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11619. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11620. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11621. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11622. this._onVRDisplayPointerRestricted = function () {
  11623. if (canvas) {
  11624. canvas.requestPointerLock();
  11625. }
  11626. };
  11627. this._onVRDisplayPointerUnrestricted = function () {
  11628. document.exitPointerLock();
  11629. };
  11630. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11631. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11632. }
  11633. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11634. Engine.audioEngine = new BABYLON.AudioEngine();
  11635. }
  11636. // Prepare buffer pointers
  11637. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11638. this._currentBufferPointers[i] = new BufferPointer();
  11639. }
  11640. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11641. // Load WebVR Devices
  11642. if (options.autoEnableWebVR) {
  11643. this.initWebVR();
  11644. }
  11645. // Detect if we are running on a faulty buggy OS.
  11646. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11647. // Detect if we are running on a faulty buggy desktop OS.
  11648. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11649. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11650. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11651. }
  11652. Object.defineProperty(Engine, "LastCreatedEngine", {
  11653. /**
  11654. * Gets the latest created engine
  11655. */
  11656. get: function () {
  11657. if (Engine.Instances.length === 0) {
  11658. return null;
  11659. }
  11660. return Engine.Instances[Engine.Instances.length - 1];
  11661. },
  11662. enumerable: true,
  11663. configurable: true
  11664. });
  11665. Object.defineProperty(Engine, "LastCreatedScene", {
  11666. /**
  11667. * Gets the latest created scene
  11668. */
  11669. get: function () {
  11670. var lastCreatedEngine = Engine.LastCreatedEngine;
  11671. if (!lastCreatedEngine) {
  11672. return null;
  11673. }
  11674. if (lastCreatedEngine.scenes.length === 0) {
  11675. return null;
  11676. }
  11677. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11678. },
  11679. enumerable: true,
  11680. configurable: true
  11681. });
  11682. /**
  11683. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11684. * @param flag defines which part of the materials must be marked as dirty
  11685. * @param predicate defines a predicate used to filter which materials should be affected
  11686. */
  11687. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11688. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11689. var engine = Engine.Instances[engineIndex];
  11690. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11691. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11692. }
  11693. }
  11694. };
  11695. Object.defineProperty(Engine, "NEVER", {
  11696. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11697. get: function () {
  11698. return Engine._NEVER;
  11699. },
  11700. enumerable: true,
  11701. configurable: true
  11702. });
  11703. Object.defineProperty(Engine, "ALWAYS", {
  11704. /** 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 */
  11705. get: function () {
  11706. return Engine._ALWAYS;
  11707. },
  11708. enumerable: true,
  11709. configurable: true
  11710. });
  11711. Object.defineProperty(Engine, "LESS", {
  11712. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11713. get: function () {
  11714. return Engine._LESS;
  11715. },
  11716. enumerable: true,
  11717. configurable: true
  11718. });
  11719. Object.defineProperty(Engine, "EQUAL", {
  11720. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11721. get: function () {
  11722. return Engine._EQUAL;
  11723. },
  11724. enumerable: true,
  11725. configurable: true
  11726. });
  11727. Object.defineProperty(Engine, "LEQUAL", {
  11728. /** 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 */
  11729. get: function () {
  11730. return Engine._LEQUAL;
  11731. },
  11732. enumerable: true,
  11733. configurable: true
  11734. });
  11735. Object.defineProperty(Engine, "GREATER", {
  11736. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11737. get: function () {
  11738. return Engine._GREATER;
  11739. },
  11740. enumerable: true,
  11741. configurable: true
  11742. });
  11743. Object.defineProperty(Engine, "GEQUAL", {
  11744. /** 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 */
  11745. get: function () {
  11746. return Engine._GEQUAL;
  11747. },
  11748. enumerable: true,
  11749. configurable: true
  11750. });
  11751. Object.defineProperty(Engine, "NOTEQUAL", {
  11752. /** 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 */
  11753. get: function () {
  11754. return Engine._NOTEQUAL;
  11755. },
  11756. enumerable: true,
  11757. configurable: true
  11758. });
  11759. Object.defineProperty(Engine, "KEEP", {
  11760. /** Passed to stencilOperation to specify that stencil value must be kept */
  11761. get: function () {
  11762. return Engine._KEEP;
  11763. },
  11764. enumerable: true,
  11765. configurable: true
  11766. });
  11767. Object.defineProperty(Engine, "REPLACE", {
  11768. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11769. get: function () {
  11770. return Engine._REPLACE;
  11771. },
  11772. enumerable: true,
  11773. configurable: true
  11774. });
  11775. Object.defineProperty(Engine, "INCR", {
  11776. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11777. get: function () {
  11778. return Engine._INCR;
  11779. },
  11780. enumerable: true,
  11781. configurable: true
  11782. });
  11783. Object.defineProperty(Engine, "DECR", {
  11784. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11785. get: function () {
  11786. return Engine._DECR;
  11787. },
  11788. enumerable: true,
  11789. configurable: true
  11790. });
  11791. Object.defineProperty(Engine, "INVERT", {
  11792. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11793. get: function () {
  11794. return Engine._INVERT;
  11795. },
  11796. enumerable: true,
  11797. configurable: true
  11798. });
  11799. Object.defineProperty(Engine, "INCR_WRAP", {
  11800. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11801. get: function () {
  11802. return Engine._INCR_WRAP;
  11803. },
  11804. enumerable: true,
  11805. configurable: true
  11806. });
  11807. Object.defineProperty(Engine, "DECR_WRAP", {
  11808. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11809. get: function () {
  11810. return Engine._DECR_WRAP;
  11811. },
  11812. enumerable: true,
  11813. configurable: true
  11814. });
  11815. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11816. // Alpha
  11817. /** Defines that alpha blending is disabled */
  11818. get: function () {
  11819. return Engine._ALPHA_DISABLE;
  11820. },
  11821. enumerable: true,
  11822. configurable: true
  11823. });
  11824. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11825. /** Defines that alpha blending to SRC + DEST */
  11826. get: function () {
  11827. return Engine._ALPHA_ONEONE;
  11828. },
  11829. enumerable: true,
  11830. configurable: true
  11831. });
  11832. Object.defineProperty(Engine, "ALPHA_ADD", {
  11833. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11834. get: function () {
  11835. return Engine._ALPHA_ADD;
  11836. },
  11837. enumerable: true,
  11838. configurable: true
  11839. });
  11840. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11841. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11842. get: function () {
  11843. return Engine._ALPHA_COMBINE;
  11844. },
  11845. enumerable: true,
  11846. configurable: true
  11847. });
  11848. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  11849. /** Defines that alpha blending to DEST - SRC * DEST */
  11850. get: function () {
  11851. return Engine._ALPHA_SUBTRACT;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  11857. /** Defines that alpha blending to SRC * DEST */
  11858. get: function () {
  11859. return Engine._ALPHA_MULTIPLY;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  11865. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  11866. get: function () {
  11867. return Engine._ALPHA_MAXIMIZED;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  11873. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  11874. get: function () {
  11875. return Engine._ALPHA_PREMULTIPLIED;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  11881. /**
  11882. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  11883. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  11884. */
  11885. get: function () {
  11886. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  11887. },
  11888. enumerable: true,
  11889. configurable: true
  11890. });
  11891. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  11892. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  11893. get: function () {
  11894. return Engine._ALPHA_INTERPOLATE;
  11895. },
  11896. enumerable: true,
  11897. configurable: true
  11898. });
  11899. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  11900. /**
  11901. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  11902. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  11903. */
  11904. get: function () {
  11905. return Engine._ALPHA_SCREENMODE;
  11906. },
  11907. enumerable: true,
  11908. configurable: true
  11909. });
  11910. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  11911. // Delays
  11912. /** Defines that the ressource is not delayed*/
  11913. get: function () {
  11914. return Engine._DELAYLOADSTATE_NONE;
  11915. },
  11916. enumerable: true,
  11917. configurable: true
  11918. });
  11919. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  11920. /** Defines that the ressource was successfully delay loaded */
  11921. get: function () {
  11922. return Engine._DELAYLOADSTATE_LOADED;
  11923. },
  11924. enumerable: true,
  11925. configurable: true
  11926. });
  11927. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  11928. /** Defines that the ressource is currently delay loading */
  11929. get: function () {
  11930. return Engine._DELAYLOADSTATE_LOADING;
  11931. },
  11932. enumerable: true,
  11933. configurable: true
  11934. });
  11935. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  11936. /** Defines that the ressource is delayed and has not started loading */
  11937. get: function () {
  11938. return Engine._DELAYLOADSTATE_NOTLOADED;
  11939. },
  11940. enumerable: true,
  11941. configurable: true
  11942. });
  11943. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  11944. /** ALPHA */
  11945. get: function () {
  11946. return Engine._TEXTUREFORMAT_ALPHA;
  11947. },
  11948. enumerable: true,
  11949. configurable: true
  11950. });
  11951. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  11952. /** LUMINANCE */
  11953. get: function () {
  11954. return Engine._TEXTUREFORMAT_LUMINANCE;
  11955. },
  11956. enumerable: true,
  11957. configurable: true
  11958. });
  11959. Object.defineProperty(Engine, "TEXTUREFORMAT_R32F", {
  11960. /**
  11961. * R32F
  11962. */
  11963. get: function () {
  11964. return Engine._TEXTUREFORMAT_R32F;
  11965. },
  11966. enumerable: true,
  11967. configurable: true
  11968. });
  11969. Object.defineProperty(Engine, "TEXTUREFORMAT_RG32F", {
  11970. /**
  11971. * RG32F
  11972. */
  11973. get: function () {
  11974. return Engine._TEXTUREFORMAT_RG32F;
  11975. },
  11976. enumerable: true,
  11977. configurable: true
  11978. });
  11979. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB32F", {
  11980. /**
  11981. * RGB32F
  11982. */
  11983. get: function () {
  11984. return Engine._TEXTUREFORMAT_RGB32F;
  11985. },
  11986. enumerable: true,
  11987. configurable: true
  11988. });
  11989. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA32F", {
  11990. /**
  11991. * RGBA32F
  11992. */
  11993. get: function () {
  11994. return Engine._TEXTUREFORMAT_RGBA32F;
  11995. },
  11996. enumerable: true,
  11997. configurable: true
  11998. });
  11999. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12000. /** LUMINANCE_ALPHA */
  12001. get: function () {
  12002. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12003. },
  12004. enumerable: true,
  12005. configurable: true
  12006. });
  12007. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12008. /** RGB */
  12009. get: function () {
  12010. return Engine._TEXTUREFORMAT_RGB;
  12011. },
  12012. enumerable: true,
  12013. configurable: true
  12014. });
  12015. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12016. /** RGBA */
  12017. get: function () {
  12018. return Engine._TEXTUREFORMAT_RGBA;
  12019. },
  12020. enumerable: true,
  12021. configurable: true
  12022. });
  12023. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12024. /** UNSIGNED_INT */
  12025. get: function () {
  12026. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12027. },
  12028. enumerable: true,
  12029. configurable: true
  12030. });
  12031. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12032. /** FLOAT */
  12033. get: function () {
  12034. return Engine._TEXTURETYPE_FLOAT;
  12035. },
  12036. enumerable: true,
  12037. configurable: true
  12038. });
  12039. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12040. /** HALF_FLOAT */
  12041. get: function () {
  12042. return Engine._TEXTURETYPE_HALF_FLOAT;
  12043. },
  12044. enumerable: true,
  12045. configurable: true
  12046. });
  12047. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12048. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12049. get: function () {
  12050. return Engine._SCALEMODE_FLOOR;
  12051. },
  12052. enumerable: true,
  12053. configurable: true
  12054. });
  12055. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12056. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12057. get: function () {
  12058. return Engine._SCALEMODE_NEAREST;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12064. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12065. get: function () {
  12066. return Engine._SCALEMODE_CEILING;
  12067. },
  12068. enumerable: true,
  12069. configurable: true
  12070. });
  12071. Object.defineProperty(Engine, "Version", {
  12072. /**
  12073. * Returns the current version of the framework
  12074. */
  12075. get: function () {
  12076. return "3.2.0";
  12077. },
  12078. enumerable: true,
  12079. configurable: true
  12080. });
  12081. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12082. /**
  12083. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12084. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12085. */
  12086. get: function () {
  12087. return this._vrExclusivePointerMode;
  12088. },
  12089. enumerable: true,
  12090. configurable: true
  12091. });
  12092. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12093. /**
  12094. * Gets a boolean indicating that the engine supports uniform buffers
  12095. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12096. */
  12097. get: function () {
  12098. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12099. },
  12100. enumerable: true,
  12101. configurable: true
  12102. });
  12103. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12104. /**
  12105. * Gets a boolean indicating that only power of 2 textures are supported
  12106. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12107. */
  12108. get: function () {
  12109. return this._webGLVersion < 2 || this.forcePOTTextures;
  12110. },
  12111. enumerable: true,
  12112. configurable: true
  12113. });
  12114. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12115. /**
  12116. * Gets the performance monitor attached to this engine
  12117. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12118. */
  12119. get: function () {
  12120. return this._performanceMonitor;
  12121. },
  12122. enumerable: true,
  12123. configurable: true
  12124. });
  12125. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12126. /**
  12127. * Gets the list of texture formats supported
  12128. */
  12129. get: function () {
  12130. return this._texturesSupported;
  12131. },
  12132. enumerable: true,
  12133. configurable: true
  12134. });
  12135. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12136. /**
  12137. * Gets the list of texture formats in use
  12138. */
  12139. get: function () {
  12140. return this._textureFormatInUse;
  12141. },
  12142. enumerable: true,
  12143. configurable: true
  12144. });
  12145. Object.defineProperty(Engine.prototype, "currentViewport", {
  12146. /**
  12147. * Gets the current viewport
  12148. */
  12149. get: function () {
  12150. return this._cachedViewport;
  12151. },
  12152. enumerable: true,
  12153. configurable: true
  12154. });
  12155. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12156. /**
  12157. * Gets the default empty texture
  12158. */
  12159. get: function () {
  12160. if (!this._emptyTexture) {
  12161. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12162. }
  12163. return this._emptyTexture;
  12164. },
  12165. enumerable: true,
  12166. configurable: true
  12167. });
  12168. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12169. /**
  12170. * Gets the default empty 3D texture
  12171. */
  12172. get: function () {
  12173. if (!this._emptyTexture3D) {
  12174. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12175. }
  12176. return this._emptyTexture3D;
  12177. },
  12178. enumerable: true,
  12179. configurable: true
  12180. });
  12181. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12182. /**
  12183. * Gets the default empty cube texture
  12184. */
  12185. get: function () {
  12186. if (!this._emptyCubeTexture) {
  12187. var faceData = new Uint8Array(4);
  12188. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12189. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12190. }
  12191. return this._emptyCubeTexture;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Engine.prototype._rebuildInternalTextures = function () {
  12197. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12198. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12199. var internalTexture = currentState_1[_i];
  12200. internalTexture._rebuild();
  12201. }
  12202. };
  12203. Engine.prototype._rebuildEffects = function () {
  12204. for (var key in this._compiledEffects) {
  12205. var effect = this._compiledEffects[key];
  12206. effect._prepareEffect();
  12207. }
  12208. BABYLON.Effect.ResetCache();
  12209. };
  12210. Engine.prototype._rebuildBuffers = function () {
  12211. // Index / Vertex
  12212. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12213. var scene = _a[_i];
  12214. scene.resetCachedMaterial();
  12215. scene._rebuildGeometries();
  12216. scene._rebuildTextures();
  12217. }
  12218. // Uniforms
  12219. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12220. var uniformBuffer = _c[_b];
  12221. uniformBuffer._rebuild();
  12222. }
  12223. };
  12224. Engine.prototype._initGLContext = function () {
  12225. // Caps
  12226. this._caps = new EngineCapabilities();
  12227. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12228. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12229. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12230. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12231. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12232. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12233. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12234. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12235. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12236. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12237. // Infos
  12238. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12239. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12240. if (rendererInfo != null) {
  12241. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12242. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12243. }
  12244. if (!this._glVendor) {
  12245. this._glVendor = "Unknown vendor";
  12246. }
  12247. if (!this._glRenderer) {
  12248. this._glRenderer = "Unknown renderer";
  12249. }
  12250. // Constants
  12251. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12252. if (this._gl.RGBA16F !== 0x881A) {
  12253. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12254. }
  12255. if (this._gl.RGBA32F !== 0x8814) {
  12256. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12257. }
  12258. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12259. this._gl.DEPTH24_STENCIL8 = 35056;
  12260. }
  12261. // Extensions
  12262. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12263. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12264. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12265. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12266. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12267. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12268. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12269. 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');
  12270. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12271. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12272. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12273. this._caps.highPrecisionShaderSupported = true;
  12274. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12275. if (this._caps.timerQuery) {
  12276. if (this._webGLVersion === 1) {
  12277. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12278. }
  12279. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12280. }
  12281. // Checks if some of the format renders first to allow the use of webgl inspector.
  12282. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12283. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12284. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12285. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12286. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12287. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12288. if (this._webGLVersion > 1) {
  12289. this._gl.HALF_FLOAT_OES = 0x140B;
  12290. }
  12291. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12292. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12293. // Draw buffers
  12294. if (this._webGLVersion > 1) {
  12295. this._caps.drawBuffersExtension = true;
  12296. }
  12297. else {
  12298. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12299. if (drawBuffersExtension !== null) {
  12300. this._caps.drawBuffersExtension = true;
  12301. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12302. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12303. for (var i = 0; i < 16; i++) {
  12304. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12305. }
  12306. }
  12307. else {
  12308. this._caps.drawBuffersExtension = false;
  12309. }
  12310. }
  12311. // Depth Texture
  12312. if (this._webGLVersion > 1) {
  12313. this._caps.depthTextureExtension = true;
  12314. }
  12315. else {
  12316. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12317. if (depthTextureExtension != null) {
  12318. this._caps.depthTextureExtension = true;
  12319. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12320. }
  12321. }
  12322. // Vertex array object
  12323. if (this._webGLVersion > 1) {
  12324. this._caps.vertexArrayObject = true;
  12325. }
  12326. else {
  12327. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12328. if (vertexArrayObjectExtension != null) {
  12329. this._caps.vertexArrayObject = true;
  12330. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12331. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12332. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12333. }
  12334. else {
  12335. this._caps.vertexArrayObject = false;
  12336. }
  12337. }
  12338. // Instances count
  12339. if (this._webGLVersion > 1) {
  12340. this._caps.instancedArrays = true;
  12341. }
  12342. else {
  12343. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12344. if (instanceExtension != null) {
  12345. this._caps.instancedArrays = true;
  12346. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12347. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12348. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12349. }
  12350. else {
  12351. this._caps.instancedArrays = false;
  12352. }
  12353. }
  12354. // Intelligently add supported compressed formats in order to check for.
  12355. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12356. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12357. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12358. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12359. if (this._caps.astc)
  12360. this.texturesSupported.push('-astc.ktx');
  12361. if (this._caps.s3tc)
  12362. this.texturesSupported.push('-dxt.ktx');
  12363. if (this._caps.pvrtc)
  12364. this.texturesSupported.push('-pvrtc.ktx');
  12365. if (this._caps.etc2)
  12366. this.texturesSupported.push('-etc2.ktx');
  12367. if (this._caps.etc1)
  12368. this.texturesSupported.push('-etc1.ktx');
  12369. if (this._gl.getShaderPrecisionFormat) {
  12370. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12371. if (highp) {
  12372. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12373. }
  12374. }
  12375. // Depth buffer
  12376. this.setDepthBuffer(true);
  12377. this.setDepthFunctionToLessOrEqual();
  12378. this.setDepthWrite(true);
  12379. // Texture maps
  12380. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12381. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12382. this._nextFreeTextureSlots.push(slot);
  12383. }
  12384. };
  12385. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12386. /**
  12387. * Gets version of the current webGL context
  12388. */
  12389. get: function () {
  12390. return this._webGLVersion;
  12391. },
  12392. enumerable: true,
  12393. configurable: true
  12394. });
  12395. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12396. /**
  12397. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12398. */
  12399. get: function () {
  12400. return this._isStencilEnable;
  12401. },
  12402. enumerable: true,
  12403. configurable: true
  12404. });
  12405. Engine.prototype._prepareWorkingCanvas = function () {
  12406. if (this._workingCanvas) {
  12407. return;
  12408. }
  12409. this._workingCanvas = document.createElement("canvas");
  12410. var context = this._workingCanvas.getContext("2d");
  12411. if (context) {
  12412. this._workingContext = context;
  12413. }
  12414. };
  12415. /**
  12416. * Reset the texture cache to empty state
  12417. */
  12418. Engine.prototype.resetTextureCache = function () {
  12419. for (var key in this._boundTexturesCache) {
  12420. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12421. continue;
  12422. }
  12423. var boundTexture = this._boundTexturesCache[key];
  12424. if (boundTexture) {
  12425. this._removeDesignatedSlot(boundTexture);
  12426. }
  12427. this._boundTexturesCache[key] = null;
  12428. }
  12429. if (!this.disableTextureBindingOptimization) {
  12430. this._nextFreeTextureSlots = [];
  12431. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12432. this._nextFreeTextureSlots.push(slot);
  12433. }
  12434. }
  12435. this._currentTextureChannel = -1;
  12436. };
  12437. /**
  12438. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12439. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12440. * @returns true if engine is in deterministic lock step mode
  12441. */
  12442. Engine.prototype.isDeterministicLockStep = function () {
  12443. return this._deterministicLockstep;
  12444. };
  12445. /**
  12446. * Gets the max steps when engine is running in deterministic lock step
  12447. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12448. * @returns the max steps
  12449. */
  12450. Engine.prototype.getLockstepMaxSteps = function () {
  12451. return this._lockstepMaxSteps;
  12452. };
  12453. /**
  12454. * Gets an object containing information about the current webGL context
  12455. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12456. */
  12457. Engine.prototype.getGlInfo = function () {
  12458. return {
  12459. vendor: this._glVendor,
  12460. renderer: this._glRenderer,
  12461. version: this._glVersion
  12462. };
  12463. };
  12464. /**
  12465. * Gets current aspect ratio
  12466. * @param camera defines the camera to use to get the aspect ratio
  12467. * @param useScreen defines if screen size must be used (or the current render target if any)
  12468. * @returns a number defining the aspect ratio
  12469. */
  12470. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12471. if (useScreen === void 0) { useScreen = false; }
  12472. var viewport = camera.viewport;
  12473. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12474. };
  12475. /**
  12476. * Gets the current render width
  12477. * @param useScreen defines if screen size must be used (or the current render target if any)
  12478. * @returns a number defining the current render width
  12479. */
  12480. Engine.prototype.getRenderWidth = function (useScreen) {
  12481. if (useScreen === void 0) { useScreen = false; }
  12482. if (!useScreen && this._currentRenderTarget) {
  12483. return this._currentRenderTarget.width;
  12484. }
  12485. return this._gl.drawingBufferWidth;
  12486. };
  12487. /**
  12488. * Gets the current render height
  12489. * @param useScreen defines if screen size must be used (or the current render target if any)
  12490. * @returns a number defining the current render height
  12491. */
  12492. Engine.prototype.getRenderHeight = function (useScreen) {
  12493. if (useScreen === void 0) { useScreen = false; }
  12494. if (!useScreen && this._currentRenderTarget) {
  12495. return this._currentRenderTarget.height;
  12496. }
  12497. return this._gl.drawingBufferHeight;
  12498. };
  12499. /**
  12500. * Gets the HTML canvas attached with the current webGL context
  12501. * @returns a HTML canvas
  12502. */
  12503. Engine.prototype.getRenderingCanvas = function () {
  12504. return this._renderingCanvas;
  12505. };
  12506. /**
  12507. * Gets the client rect of the HTML canvas attached with the current webGL context
  12508. * @returns a client rectanglee
  12509. */
  12510. Engine.prototype.getRenderingCanvasClientRect = function () {
  12511. if (!this._renderingCanvas) {
  12512. return null;
  12513. }
  12514. return this._renderingCanvas.getBoundingClientRect();
  12515. };
  12516. /**
  12517. * Defines the hardware scaling level.
  12518. * By default the hardware scaling level is computed from the window device ratio.
  12519. * 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.
  12520. * @param level defines the level to use
  12521. */
  12522. Engine.prototype.setHardwareScalingLevel = function (level) {
  12523. this._hardwareScalingLevel = level;
  12524. this.resize();
  12525. };
  12526. /**
  12527. * Gets the current hardware scaling level.
  12528. * By default the hardware scaling level is computed from the window device ratio.
  12529. * 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.
  12530. * @returns a number indicating the current hardware scaling level
  12531. */
  12532. Engine.prototype.getHardwareScalingLevel = function () {
  12533. return this._hardwareScalingLevel;
  12534. };
  12535. /**
  12536. * Gets the list of loaded textures
  12537. * @returns an array containing all loaded textures
  12538. */
  12539. Engine.prototype.getLoadedTexturesCache = function () {
  12540. return this._internalTexturesCache;
  12541. };
  12542. /**
  12543. * Gets the object containing all engine capabilities
  12544. * @returns the EngineCapabilities object
  12545. */
  12546. Engine.prototype.getCaps = function () {
  12547. return this._caps;
  12548. };
  12549. Object.defineProperty(Engine.prototype, "drawCalls", {
  12550. /** @hidden */
  12551. get: function () {
  12552. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12553. return 0;
  12554. },
  12555. enumerable: true,
  12556. configurable: true
  12557. });
  12558. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12559. /** @hidden */
  12560. get: function () {
  12561. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12562. return null;
  12563. },
  12564. enumerable: true,
  12565. configurable: true
  12566. });
  12567. /**
  12568. * Gets the current depth function
  12569. * @returns a number defining the depth function
  12570. */
  12571. Engine.prototype.getDepthFunction = function () {
  12572. return this._depthCullingState.depthFunc;
  12573. };
  12574. /**
  12575. * Sets the current depth function
  12576. * @param depthFunc defines the function to use
  12577. */
  12578. Engine.prototype.setDepthFunction = function (depthFunc) {
  12579. this._depthCullingState.depthFunc = depthFunc;
  12580. };
  12581. /**
  12582. * Sets the current depth function to GREATER
  12583. */
  12584. Engine.prototype.setDepthFunctionToGreater = function () {
  12585. this._depthCullingState.depthFunc = this._gl.GREATER;
  12586. };
  12587. /**
  12588. * Sets the current depth function to GEQUAL
  12589. */
  12590. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12591. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12592. };
  12593. /**
  12594. * Sets the current depth function to LESS
  12595. */
  12596. Engine.prototype.setDepthFunctionToLess = function () {
  12597. this._depthCullingState.depthFunc = this._gl.LESS;
  12598. };
  12599. /**
  12600. * Sets the current depth function to LEQUAL
  12601. */
  12602. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12603. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12604. };
  12605. /**
  12606. * Gets a boolean indicating if stencil buffer is enabled
  12607. * @returns the current stencil buffer state
  12608. */
  12609. Engine.prototype.getStencilBuffer = function () {
  12610. return this._stencilState.stencilTest;
  12611. };
  12612. /**
  12613. * Enable or disable the stencil buffer
  12614. * @param enable defines if the stencil buffer must be enabled or disabled
  12615. */
  12616. Engine.prototype.setStencilBuffer = function (enable) {
  12617. this._stencilState.stencilTest = enable;
  12618. };
  12619. /**
  12620. * Gets the current stencil mask
  12621. * @returns a number defining the new stencil mask to use
  12622. */
  12623. Engine.prototype.getStencilMask = function () {
  12624. return this._stencilState.stencilMask;
  12625. };
  12626. /**
  12627. * Sets the current stencil mask
  12628. * @param mask defines the new stencil mask to use
  12629. */
  12630. Engine.prototype.setStencilMask = function (mask) {
  12631. this._stencilState.stencilMask = mask;
  12632. };
  12633. /**
  12634. * Gets the current stencil function
  12635. * @returns a number defining the stencil function to use
  12636. */
  12637. Engine.prototype.getStencilFunction = function () {
  12638. return this._stencilState.stencilFunc;
  12639. };
  12640. /**
  12641. * Gets the current stencil reference value
  12642. * @returns a number defining the stencil reference value to use
  12643. */
  12644. Engine.prototype.getStencilFunctionReference = function () {
  12645. return this._stencilState.stencilFuncRef;
  12646. };
  12647. /**
  12648. * Gets the current stencil mask
  12649. * @returns a number defining the stencil mask to use
  12650. */
  12651. Engine.prototype.getStencilFunctionMask = function () {
  12652. return this._stencilState.stencilFuncMask;
  12653. };
  12654. /**
  12655. * Sets the current stencil function
  12656. * @param stencilFunc defines the new stencil function to use
  12657. */
  12658. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12659. this._stencilState.stencilFunc = stencilFunc;
  12660. };
  12661. /**
  12662. * Sets the current stencil reference
  12663. * @param reference defines the new stencil reference to use
  12664. */
  12665. Engine.prototype.setStencilFunctionReference = function (reference) {
  12666. this._stencilState.stencilFuncRef = reference;
  12667. };
  12668. /**
  12669. * Sets the current stencil mask
  12670. * @param mask defines the new stencil mask to use
  12671. */
  12672. Engine.prototype.setStencilFunctionMask = function (mask) {
  12673. this._stencilState.stencilFuncMask = mask;
  12674. };
  12675. /**
  12676. * Gets the current stencil operation when stencil fails
  12677. * @returns a number defining stencil operation to use when stencil fails
  12678. */
  12679. Engine.prototype.getStencilOperationFail = function () {
  12680. return this._stencilState.stencilOpStencilFail;
  12681. };
  12682. /**
  12683. * Gets the current stencil operation when depth fails
  12684. * @returns a number defining stencil operation to use when depth fails
  12685. */
  12686. Engine.prototype.getStencilOperationDepthFail = function () {
  12687. return this._stencilState.stencilOpDepthFail;
  12688. };
  12689. /**
  12690. * Gets the current stencil operation when stencil passes
  12691. * @returns a number defining stencil operation to use when stencil passes
  12692. */
  12693. Engine.prototype.getStencilOperationPass = function () {
  12694. return this._stencilState.stencilOpStencilDepthPass;
  12695. };
  12696. /**
  12697. * Sets the stencil operation to use when stencil fails
  12698. * @param operation defines the stencil operation to use when stencil fails
  12699. */
  12700. Engine.prototype.setStencilOperationFail = function (operation) {
  12701. this._stencilState.stencilOpStencilFail = operation;
  12702. };
  12703. /**
  12704. * Sets the stencil operation to use when depth fails
  12705. * @param operation defines the stencil operation to use when depth fails
  12706. */
  12707. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12708. this._stencilState.stencilOpDepthFail = operation;
  12709. };
  12710. /**
  12711. * Sets the stencil operation to use when stencil passes
  12712. * @param operation defines the stencil operation to use when stencil passes
  12713. */
  12714. Engine.prototype.setStencilOperationPass = function (operation) {
  12715. this._stencilState.stencilOpStencilDepthPass = operation;
  12716. };
  12717. /**
  12718. * Sets a boolean indicating if the dithering state is enabled or disabled
  12719. * @param value defines the dithering state
  12720. */
  12721. Engine.prototype.setDitheringState = function (value) {
  12722. if (value) {
  12723. this._gl.enable(this._gl.DITHER);
  12724. }
  12725. else {
  12726. this._gl.disable(this._gl.DITHER);
  12727. }
  12728. };
  12729. /**
  12730. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12731. * @param value defines the rasterizer state
  12732. */
  12733. Engine.prototype.setRasterizerState = function (value) {
  12734. if (value) {
  12735. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12736. }
  12737. else {
  12738. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12739. }
  12740. };
  12741. /**
  12742. * stop executing a render loop function and remove it from the execution array
  12743. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12744. */
  12745. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12746. if (!renderFunction) {
  12747. this._activeRenderLoops = [];
  12748. return;
  12749. }
  12750. var index = this._activeRenderLoops.indexOf(renderFunction);
  12751. if (index >= 0) {
  12752. this._activeRenderLoops.splice(index, 1);
  12753. }
  12754. };
  12755. /** @hidden */
  12756. Engine.prototype._renderLoop = function () {
  12757. if (!this._contextWasLost) {
  12758. var shouldRender = true;
  12759. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12760. shouldRender = false;
  12761. }
  12762. if (shouldRender) {
  12763. // Start new frame
  12764. this.beginFrame();
  12765. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12766. var renderFunction = this._activeRenderLoops[index];
  12767. renderFunction();
  12768. }
  12769. // Present
  12770. this.endFrame();
  12771. }
  12772. }
  12773. if (this._activeRenderLoops.length > 0) {
  12774. // Register new frame
  12775. var requester = null;
  12776. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12777. requester = this._vrDisplay;
  12778. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12779. }
  12780. else {
  12781. this._renderingQueueLaunched = false;
  12782. }
  12783. };
  12784. /**
  12785. * Register and execute a render loop. The engine can have more than one render function
  12786. * @param renderFunction defines the function to continuously execute
  12787. */
  12788. Engine.prototype.runRenderLoop = function (renderFunction) {
  12789. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12790. return;
  12791. }
  12792. this._activeRenderLoops.push(renderFunction);
  12793. if (!this._renderingQueueLaunched) {
  12794. this._renderingQueueLaunched = true;
  12795. this._bindedRenderFunction = this._renderLoop.bind(this);
  12796. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12797. }
  12798. };
  12799. /**
  12800. * Toggle full screen mode
  12801. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12802. * @param options defines an option object to be sent to the requestFullscreen function
  12803. */
  12804. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12805. if (this.isFullscreen) {
  12806. BABYLON.Tools.ExitFullscreen();
  12807. }
  12808. else {
  12809. this._pointerLockRequested = requestPointerLock;
  12810. if (this._renderingCanvas) {
  12811. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12812. }
  12813. }
  12814. };
  12815. /**
  12816. * Clear the current render buffer or the current render target (if any is set up)
  12817. * @param color defines the color to use
  12818. * @param backBuffer defines if the back buffer must be cleared
  12819. * @param depth defines if the depth buffer must be cleared
  12820. * @param stencil defines if the stencil buffer must be cleared
  12821. */
  12822. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12823. if (stencil === void 0) { stencil = false; }
  12824. this.applyStates();
  12825. var mode = 0;
  12826. if (backBuffer && color) {
  12827. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12828. mode |= this._gl.COLOR_BUFFER_BIT;
  12829. }
  12830. if (depth) {
  12831. this._gl.clearDepth(1.0);
  12832. mode |= this._gl.DEPTH_BUFFER_BIT;
  12833. }
  12834. if (stencil) {
  12835. this._gl.clearStencil(0);
  12836. mode |= this._gl.STENCIL_BUFFER_BIT;
  12837. }
  12838. this._gl.clear(mode);
  12839. };
  12840. /**
  12841. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12842. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12843. * @param y defines the y-coordinate of the corner of the clear rectangle
  12844. * @param width defines the width of the clear rectangle
  12845. * @param height defines the height of the clear rectangle
  12846. * @param clearColor defines the clear color
  12847. */
  12848. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  12849. var gl = this._gl;
  12850. // Save state
  12851. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  12852. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  12853. // Change state
  12854. gl.enable(gl.SCISSOR_TEST);
  12855. gl.scissor(x, y, width, height);
  12856. // Clear
  12857. this.clear(clearColor, true, true, true);
  12858. // Restore state
  12859. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  12860. if (curScissor === true) {
  12861. gl.enable(gl.SCISSOR_TEST);
  12862. }
  12863. else {
  12864. gl.disable(gl.SCISSOR_TEST);
  12865. }
  12866. };
  12867. /**
  12868. * Set the WebGL's viewport
  12869. * @param viewport defines the viewport element to be used
  12870. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  12871. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  12872. */
  12873. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  12874. var width = requiredWidth || this.getRenderWidth();
  12875. var height = requiredHeight || this.getRenderHeight();
  12876. var x = viewport.x || 0;
  12877. var y = viewport.y || 0;
  12878. this._cachedViewport = viewport;
  12879. this._gl.viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  12880. };
  12881. /**
  12882. * Directly set the WebGL Viewport
  12883. * @param x defines the x coordinate of the viewport (in screen space)
  12884. * @param y defines the y coordinate of the viewport (in screen space)
  12885. * @param width defines the width of the viewport (in screen space)
  12886. * @param height defines the height of the viewport (in screen space)
  12887. * @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
  12888. */
  12889. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  12890. var currentViewport = this._cachedViewport;
  12891. this._cachedViewport = null;
  12892. this._gl.viewport(x, y, width, height);
  12893. return currentViewport;
  12894. };
  12895. /**
  12896. * Begin a new frame
  12897. */
  12898. Engine.prototype.beginFrame = function () {
  12899. this.onBeginFrameObservable.notifyObservers(this);
  12900. this._measureFps();
  12901. };
  12902. /**
  12903. * Enf the current frame
  12904. */
  12905. Engine.prototype.endFrame = function () {
  12906. // Force a flush in case we are using a bad OS.
  12907. if (this._badOS) {
  12908. this.flushFramebuffer();
  12909. }
  12910. // Submit frame to the vr device, if enabled
  12911. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  12912. // TODO: We should only submit the frame if we read frameData successfully.
  12913. this._vrDisplay.submitFrame();
  12914. }
  12915. this.onEndFrameObservable.notifyObservers(this);
  12916. };
  12917. /**
  12918. * Resize the view according to the canvas' size
  12919. */
  12920. Engine.prototype.resize = function () {
  12921. // We're not resizing the size of the canvas while in VR mode & presenting
  12922. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  12923. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  12924. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  12925. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  12926. }
  12927. };
  12928. /**
  12929. * Force a specific size of the canvas
  12930. * @param width defines the new canvas' width
  12931. * @param height defines the new canvas' height
  12932. */
  12933. Engine.prototype.setSize = function (width, height) {
  12934. if (!this._renderingCanvas) {
  12935. return;
  12936. }
  12937. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  12938. return;
  12939. }
  12940. this._renderingCanvas.width = width;
  12941. this._renderingCanvas.height = height;
  12942. for (var index = 0; index < this.scenes.length; index++) {
  12943. var scene = this.scenes[index];
  12944. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  12945. var cam = scene.cameras[camIndex];
  12946. cam._currentRenderId = 0;
  12947. }
  12948. }
  12949. if (this.onResizeObservable.hasObservers) {
  12950. this.onResizeObservable.notifyObservers(this);
  12951. }
  12952. };
  12953. // WebVR functions
  12954. /**
  12955. * Gets a boolean indicating if a webVR device was detected
  12956. * @returns true if a webVR device was detected
  12957. */
  12958. Engine.prototype.isVRDevicePresent = function () {
  12959. return !!this._vrDisplay;
  12960. };
  12961. /**
  12962. * Gets the current webVR device
  12963. * @returns the current webVR device (or null)
  12964. */
  12965. Engine.prototype.getVRDevice = function () {
  12966. return this._vrDisplay;
  12967. };
  12968. /**
  12969. * Initializes a webVR display and starts listening to display change events
  12970. * The onVRDisplayChangedObservable will be notified upon these changes
  12971. * @returns The onVRDisplayChangedObservable
  12972. */
  12973. Engine.prototype.initWebVR = function () {
  12974. this.initWebVRAsync();
  12975. return this.onVRDisplayChangedObservable;
  12976. };
  12977. /**
  12978. * Initializes a webVR display and starts listening to display change events
  12979. * The onVRDisplayChangedObservable will be notified upon these changes
  12980. * @returns A promise containing a VRDisplay and if vr is supported
  12981. */
  12982. Engine.prototype.initWebVRAsync = function () {
  12983. var _this = this;
  12984. var notifyObservers = function () {
  12985. var eventArgs = {
  12986. vrDisplay: _this._vrDisplay,
  12987. vrSupported: _this._vrSupported
  12988. };
  12989. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  12990. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  12991. };
  12992. if (!this._onVrDisplayConnect) {
  12993. this._onVrDisplayConnect = function (event) {
  12994. _this._vrDisplay = event.display;
  12995. notifyObservers();
  12996. };
  12997. this._onVrDisplayDisconnect = function () {
  12998. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  12999. _this._vrDisplay = undefined;
  13000. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13001. notifyObservers();
  13002. };
  13003. this._onVrDisplayPresentChange = function () {
  13004. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13005. };
  13006. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13007. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13008. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13009. }
  13010. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13011. this._webVRInitPromise.then(notifyObservers);
  13012. return this._webVRInitPromise;
  13013. };
  13014. /**
  13015. * Call this function to switch to webVR mode
  13016. * Will do nothing if webVR is not supported or if there is no webVR device
  13017. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13018. */
  13019. Engine.prototype.enableVR = function () {
  13020. var _this = this;
  13021. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13022. var onResolved = function () {
  13023. _this.onVRRequestPresentComplete.notifyObservers(true);
  13024. _this._onVRFullScreenTriggered();
  13025. };
  13026. var onRejected = function () {
  13027. _this.onVRRequestPresentComplete.notifyObservers(false);
  13028. };
  13029. this.onVRRequestPresentStart.notifyObservers(this);
  13030. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13031. }
  13032. };
  13033. /**
  13034. * Call this function to leave webVR mode
  13035. * Will do nothing if webVR is not supported or if there is no webVR device
  13036. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13037. */
  13038. Engine.prototype.disableVR = function () {
  13039. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13040. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13041. }
  13042. };
  13043. Engine.prototype._getVRDisplaysAsync = function () {
  13044. var _this = this;
  13045. return new Promise(function (res, rej) {
  13046. if (navigator.getVRDisplays) {
  13047. navigator.getVRDisplays().then(function (devices) {
  13048. _this._vrSupported = true;
  13049. // note that devices may actually be an empty array. This is fine;
  13050. // we expect this._vrDisplay to be undefined in this case.
  13051. _this._vrDisplay = devices[0];
  13052. res({
  13053. vrDisplay: _this._vrDisplay,
  13054. vrSupported: _this._vrSupported
  13055. });
  13056. });
  13057. }
  13058. else {
  13059. _this._vrDisplay = undefined;
  13060. _this._vrSupported = false;
  13061. res({
  13062. vrDisplay: _this._vrDisplay,
  13063. vrSupported: _this._vrSupported
  13064. });
  13065. }
  13066. });
  13067. };
  13068. /**
  13069. * Binds the frame buffer to the specified texture.
  13070. * @param texture The texture to render to or null for the default canvas
  13071. * @param faceIndex The face of the texture to render to in case of cube texture
  13072. * @param requiredWidth The width of the target to render to
  13073. * @param requiredHeight The height of the target to render to
  13074. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13075. * @param depthStencilTexture The depth stencil texture to use to render
  13076. */
  13077. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture) {
  13078. if (this._currentRenderTarget) {
  13079. this.unBindFramebuffer(this._currentRenderTarget);
  13080. }
  13081. this._currentRenderTarget = texture;
  13082. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13083. var gl = this._gl;
  13084. if (texture.isCube) {
  13085. if (faceIndex === undefined) {
  13086. faceIndex = 0;
  13087. }
  13088. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  13089. if (depthStencilTexture) {
  13090. if (depthStencilTexture._generateStencilBuffer) {
  13091. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13092. }
  13093. else {
  13094. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, 0);
  13095. }
  13096. }
  13097. }
  13098. if (this._cachedViewport && !forceFullscreenViewport) {
  13099. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13100. }
  13101. else {
  13102. gl.viewport(0, 0, requiredWidth || texture.width, requiredHeight || texture.height);
  13103. }
  13104. this.wipeCaches();
  13105. };
  13106. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13107. if (this._currentFramebuffer !== framebuffer) {
  13108. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13109. this._currentFramebuffer = framebuffer;
  13110. }
  13111. };
  13112. /**
  13113. * Unbind the current render target texture from the webGL context
  13114. * @param texture defines the render target texture to unbind
  13115. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13116. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13117. */
  13118. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13119. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13120. this._currentRenderTarget = null;
  13121. // If MSAA, we need to bitblt back to main texture
  13122. var gl = this._gl;
  13123. if (texture._MSAAFramebuffer) {
  13124. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13125. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13126. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13127. }
  13128. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13129. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13130. gl.generateMipmap(gl.TEXTURE_2D);
  13131. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13132. }
  13133. if (onBeforeUnbind) {
  13134. if (texture._MSAAFramebuffer) {
  13135. // Bind the correct framebuffer
  13136. this.bindUnboundFramebuffer(texture._framebuffer);
  13137. }
  13138. onBeforeUnbind();
  13139. }
  13140. this.bindUnboundFramebuffer(null);
  13141. };
  13142. /**
  13143. * Unbind a list of render target textures from the webGL context
  13144. * This is used only when drawBuffer extension or webGL2 are active
  13145. * @param textures defines the render target textures to unbind
  13146. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13147. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13148. */
  13149. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13150. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13151. this._currentRenderTarget = null;
  13152. // If MSAA, we need to bitblt back to main texture
  13153. var gl = this._gl;
  13154. if (textures[0]._MSAAFramebuffer) {
  13155. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13156. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13157. var attachments = textures[0]._attachments;
  13158. if (!attachments) {
  13159. attachments = new Array(textures.length);
  13160. textures[0]._attachments = attachments;
  13161. }
  13162. for (var i = 0; i < textures.length; i++) {
  13163. var texture = textures[i];
  13164. for (var j = 0; j < attachments.length; j++) {
  13165. attachments[j] = gl.NONE;
  13166. }
  13167. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13168. gl.readBuffer(attachments[i]);
  13169. gl.drawBuffers(attachments);
  13170. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13171. }
  13172. for (var i = 0; i < attachments.length; i++) {
  13173. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13174. }
  13175. gl.drawBuffers(attachments);
  13176. }
  13177. for (var i = 0; i < textures.length; i++) {
  13178. var texture = textures[i];
  13179. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13180. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13181. gl.generateMipmap(gl.TEXTURE_2D);
  13182. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13183. }
  13184. }
  13185. if (onBeforeUnbind) {
  13186. if (textures[0]._MSAAFramebuffer) {
  13187. // Bind the correct framebuffer
  13188. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13189. }
  13190. onBeforeUnbind();
  13191. }
  13192. this.bindUnboundFramebuffer(null);
  13193. };
  13194. /**
  13195. * Force the mipmap generation for the given render target texture
  13196. * @param texture defines the render target texture to use
  13197. */
  13198. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13199. if (texture.generateMipMaps) {
  13200. var gl = this._gl;
  13201. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13202. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13203. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13204. }
  13205. };
  13206. /**
  13207. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13208. */
  13209. Engine.prototype.flushFramebuffer = function () {
  13210. this._gl.flush();
  13211. };
  13212. /**
  13213. * Unbind the current render target and bind the default framebuffer
  13214. */
  13215. Engine.prototype.restoreDefaultFramebuffer = function () {
  13216. if (this._currentRenderTarget) {
  13217. this.unBindFramebuffer(this._currentRenderTarget);
  13218. }
  13219. else {
  13220. this.bindUnboundFramebuffer(null);
  13221. }
  13222. if (this._cachedViewport) {
  13223. this.setViewport(this._cachedViewport);
  13224. }
  13225. this.wipeCaches();
  13226. };
  13227. // UBOs
  13228. /**
  13229. * Create an uniform buffer
  13230. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13231. * @param elements defines the content of the uniform buffer
  13232. * @returns the webGL uniform buffer
  13233. */
  13234. Engine.prototype.createUniformBuffer = function (elements) {
  13235. var ubo = this._gl.createBuffer();
  13236. if (!ubo) {
  13237. throw new Error("Unable to create uniform buffer");
  13238. }
  13239. this.bindUniformBuffer(ubo);
  13240. if (elements instanceof Float32Array) {
  13241. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13242. }
  13243. else {
  13244. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13245. }
  13246. this.bindUniformBuffer(null);
  13247. ubo.references = 1;
  13248. return ubo;
  13249. };
  13250. /**
  13251. * Create a dynamic uniform buffer
  13252. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13253. * @param elements defines the content of the uniform buffer
  13254. * @returns the webGL uniform buffer
  13255. */
  13256. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13257. var ubo = this._gl.createBuffer();
  13258. if (!ubo) {
  13259. throw new Error("Unable to create dynamic uniform buffer");
  13260. }
  13261. this.bindUniformBuffer(ubo);
  13262. if (elements instanceof Float32Array) {
  13263. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13264. }
  13265. else {
  13266. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13267. }
  13268. this.bindUniformBuffer(null);
  13269. ubo.references = 1;
  13270. return ubo;
  13271. };
  13272. /**
  13273. * Update an existing uniform buffer
  13274. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13275. * @param uniformBuffer defines the target uniform buffer
  13276. * @param elements defines the content to update
  13277. * @param offset defines the offset in the uniform buffer where update should start
  13278. * @param count defines the size of the data to update
  13279. */
  13280. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13281. this.bindUniformBuffer(uniformBuffer);
  13282. if (offset === undefined) {
  13283. offset = 0;
  13284. }
  13285. if (count === undefined) {
  13286. if (elements instanceof Float32Array) {
  13287. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13288. }
  13289. else {
  13290. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13291. }
  13292. }
  13293. else {
  13294. if (elements instanceof Float32Array) {
  13295. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13296. }
  13297. else {
  13298. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13299. }
  13300. }
  13301. this.bindUniformBuffer(null);
  13302. };
  13303. // VBOs
  13304. Engine.prototype._resetVertexBufferBinding = function () {
  13305. this.bindArrayBuffer(null);
  13306. this._cachedVertexBuffers = null;
  13307. };
  13308. /**
  13309. * Creates a vertex buffer
  13310. * @param data the data for the vertex buffer
  13311. * @returns the new WebGL static buffer
  13312. */
  13313. Engine.prototype.createVertexBuffer = function (data) {
  13314. var vbo = this._gl.createBuffer();
  13315. if (!vbo) {
  13316. throw new Error("Unable to create vertex buffer");
  13317. }
  13318. this.bindArrayBuffer(vbo);
  13319. if (data instanceof Array) {
  13320. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13321. }
  13322. else {
  13323. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13324. }
  13325. this._resetVertexBufferBinding();
  13326. vbo.references = 1;
  13327. return vbo;
  13328. };
  13329. /**
  13330. * Creates a dynamic vertex buffer
  13331. * @param data the data for the dynamic vertex buffer
  13332. * @returns the new WebGL dynamic buffer
  13333. */
  13334. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13335. var vbo = this._gl.createBuffer();
  13336. if (!vbo) {
  13337. throw new Error("Unable to create dynamic 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.DYNAMIC_DRAW);
  13342. }
  13343. else {
  13344. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13345. }
  13346. this._resetVertexBufferBinding();
  13347. vbo.references = 1;
  13348. return vbo;
  13349. };
  13350. /**
  13351. * Update a dynamic index buffer
  13352. * @param indexBuffer defines the target index buffer
  13353. * @param indices defines the data to update
  13354. * @param offset defines the offset in the target index buffer where update should start
  13355. */
  13356. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13357. if (offset === void 0) { offset = 0; }
  13358. // Force cache update
  13359. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13360. this.bindIndexBuffer(indexBuffer);
  13361. var arrayBuffer;
  13362. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13363. arrayBuffer = indices;
  13364. }
  13365. else {
  13366. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13367. }
  13368. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13369. this._resetIndexBufferBinding();
  13370. };
  13371. /**
  13372. * Updates a dynamic vertex buffer.
  13373. * @param vertexBuffer the vertex buffer to update
  13374. * @param data the data used to update the vertex buffer
  13375. * @param byteOffset the byte offset of the data
  13376. * @param byteLength the byte length of the data
  13377. */
  13378. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13379. this.bindArrayBuffer(vertexBuffer);
  13380. if (byteOffset === undefined) {
  13381. byteOffset = 0;
  13382. }
  13383. if (byteLength === undefined) {
  13384. if (data instanceof Array) {
  13385. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13386. }
  13387. else {
  13388. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13389. }
  13390. }
  13391. else {
  13392. if (data instanceof Array) {
  13393. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13394. }
  13395. else {
  13396. if (data instanceof ArrayBuffer) {
  13397. data = new Uint8Array(data, byteOffset, byteLength);
  13398. }
  13399. else {
  13400. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13401. }
  13402. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13403. }
  13404. }
  13405. this._resetVertexBufferBinding();
  13406. };
  13407. Engine.prototype._resetIndexBufferBinding = function () {
  13408. this.bindIndexBuffer(null);
  13409. this._cachedIndexBuffer = null;
  13410. };
  13411. /**
  13412. * Creates a new index buffer
  13413. * @param indices defines the content of the index buffer
  13414. * @param updatable defines if the index buffer must be updatable
  13415. * @returns a new webGL buffer
  13416. */
  13417. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13418. var vbo = this._gl.createBuffer();
  13419. if (!vbo) {
  13420. throw new Error("Unable to create index buffer");
  13421. }
  13422. this.bindIndexBuffer(vbo);
  13423. // Check for 32 bits indices
  13424. var arrayBuffer;
  13425. var need32Bits = false;
  13426. if (indices instanceof Uint16Array) {
  13427. arrayBuffer = indices;
  13428. }
  13429. else {
  13430. //check 32 bit support
  13431. if (this._caps.uintIndices) {
  13432. if (indices instanceof Uint32Array) {
  13433. arrayBuffer = indices;
  13434. need32Bits = true;
  13435. }
  13436. else {
  13437. //number[] or Int32Array, check if 32 bit is necessary
  13438. for (var index = 0; index < indices.length; index++) {
  13439. if (indices[index] > 65535) {
  13440. need32Bits = true;
  13441. break;
  13442. }
  13443. }
  13444. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13445. }
  13446. }
  13447. else {
  13448. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13449. arrayBuffer = new Uint16Array(indices);
  13450. }
  13451. }
  13452. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13453. this._resetIndexBufferBinding();
  13454. vbo.references = 1;
  13455. vbo.is32Bits = need32Bits;
  13456. return vbo;
  13457. };
  13458. /**
  13459. * Bind a webGL buffer to the webGL context
  13460. * @param buffer defines the buffer to bind
  13461. */
  13462. Engine.prototype.bindArrayBuffer = function (buffer) {
  13463. if (!this._vaoRecordInProgress) {
  13464. this._unbindVertexArrayObject();
  13465. }
  13466. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13467. };
  13468. /**
  13469. * Bind an uniform buffer to the current webGL context
  13470. * @param buffer defines the buffer to bind
  13471. */
  13472. Engine.prototype.bindUniformBuffer = function (buffer) {
  13473. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13474. };
  13475. /**
  13476. * Bind a buffer to the current webGL context at a given location
  13477. * @param buffer defines the buffer to bind
  13478. * @param location defines the index where to bind the buffer
  13479. */
  13480. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13481. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13482. };
  13483. /**
  13484. * Bind a specific block at a given index in a specific shader program
  13485. * @param shaderProgram defines the shader program
  13486. * @param blockName defines the block name
  13487. * @param index defines the index where to bind the block
  13488. */
  13489. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13490. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13491. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13492. };
  13493. ;
  13494. Engine.prototype.bindIndexBuffer = function (buffer) {
  13495. if (!this._vaoRecordInProgress) {
  13496. this._unbindVertexArrayObject();
  13497. }
  13498. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13499. };
  13500. Engine.prototype.bindBuffer = function (buffer, target) {
  13501. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13502. this._gl.bindBuffer(target, buffer);
  13503. this._currentBoundBuffer[target] = buffer;
  13504. }
  13505. };
  13506. /**
  13507. * update the bound buffer with the given data
  13508. * @param data defines the data to update
  13509. */
  13510. Engine.prototype.updateArrayBuffer = function (data) {
  13511. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13512. };
  13513. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13514. var pointer = this._currentBufferPointers[indx];
  13515. var changed = false;
  13516. if (!pointer.active) {
  13517. changed = true;
  13518. pointer.active = true;
  13519. pointer.index = indx;
  13520. pointer.size = size;
  13521. pointer.type = type;
  13522. pointer.normalized = normalized;
  13523. pointer.stride = stride;
  13524. pointer.offset = offset;
  13525. pointer.buffer = buffer;
  13526. }
  13527. else {
  13528. if (pointer.buffer !== buffer) {
  13529. pointer.buffer = buffer;
  13530. changed = true;
  13531. }
  13532. if (pointer.size !== size) {
  13533. pointer.size = size;
  13534. changed = true;
  13535. }
  13536. if (pointer.type !== type) {
  13537. pointer.type = type;
  13538. changed = true;
  13539. }
  13540. if (pointer.normalized !== normalized) {
  13541. pointer.normalized = normalized;
  13542. changed = true;
  13543. }
  13544. if (pointer.stride !== stride) {
  13545. pointer.stride = stride;
  13546. changed = true;
  13547. }
  13548. if (pointer.offset !== offset) {
  13549. pointer.offset = offset;
  13550. changed = true;
  13551. }
  13552. }
  13553. if (changed || this._vaoRecordInProgress) {
  13554. this.bindArrayBuffer(buffer);
  13555. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13556. }
  13557. };
  13558. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13559. if (indexBuffer == null) {
  13560. return;
  13561. }
  13562. if (this._cachedIndexBuffer !== indexBuffer) {
  13563. this._cachedIndexBuffer = indexBuffer;
  13564. this.bindIndexBuffer(indexBuffer);
  13565. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13566. }
  13567. };
  13568. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13569. var attributes = effect.getAttributesNames();
  13570. if (!this._vaoRecordInProgress) {
  13571. this._unbindVertexArrayObject();
  13572. }
  13573. this.unbindAllAttributes();
  13574. for (var index = 0; index < attributes.length; index++) {
  13575. var order = effect.getAttributeLocation(index);
  13576. if (order >= 0) {
  13577. var vertexBuffer = vertexBuffers[attributes[index]];
  13578. if (!vertexBuffer) {
  13579. continue;
  13580. }
  13581. this._gl.enableVertexAttribArray(order);
  13582. if (!this._vaoRecordInProgress) {
  13583. this._vertexAttribArraysEnabled[order] = true;
  13584. }
  13585. var buffer = vertexBuffer.getBuffer();
  13586. if (buffer) {
  13587. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13588. if (vertexBuffer.getIsInstanced()) {
  13589. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13590. if (!this._vaoRecordInProgress) {
  13591. this._currentInstanceLocations.push(order);
  13592. this._currentInstanceBuffers.push(buffer);
  13593. }
  13594. }
  13595. }
  13596. }
  13597. }
  13598. };
  13599. /**
  13600. * Records a vertex array object
  13601. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13602. * @param vertexBuffers defines the list of vertex buffers to store
  13603. * @param indexBuffer defines the index buffer to store
  13604. * @param effect defines the effect to store
  13605. * @returns the new vertex array object
  13606. */
  13607. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13608. var vao = this._gl.createVertexArray();
  13609. this._vaoRecordInProgress = true;
  13610. this._gl.bindVertexArray(vao);
  13611. this._mustWipeVertexAttributes = true;
  13612. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13613. this.bindIndexBuffer(indexBuffer);
  13614. this._vaoRecordInProgress = false;
  13615. this._gl.bindVertexArray(null);
  13616. return vao;
  13617. };
  13618. /**
  13619. * Bind a specific vertex array object
  13620. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13621. * @param vertexArrayObject defines the vertex array object to bind
  13622. * @param indexBuffer defines the index buffer to bind
  13623. */
  13624. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13625. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13626. this._cachedVertexArrayObject = vertexArrayObject;
  13627. this._gl.bindVertexArray(vertexArrayObject);
  13628. this._cachedVertexBuffers = null;
  13629. this._cachedIndexBuffer = null;
  13630. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13631. this._mustWipeVertexAttributes = true;
  13632. }
  13633. };
  13634. /**
  13635. * Bind webGl buffers directly to the webGL context
  13636. * @param vertexBuffer defines the vertex buffer to bind
  13637. * @param indexBuffer defines the index buffer to bind
  13638. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13639. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13640. * @param effect defines the effect associated with the vertex buffer
  13641. */
  13642. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13643. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13644. this._cachedVertexBuffers = vertexBuffer;
  13645. this._cachedEffectForVertexBuffers = effect;
  13646. var attributesCount = effect.getAttributesCount();
  13647. this._unbindVertexArrayObject();
  13648. this.unbindAllAttributes();
  13649. var offset = 0;
  13650. for (var index = 0; index < attributesCount; index++) {
  13651. if (index < vertexDeclaration.length) {
  13652. var order = effect.getAttributeLocation(index);
  13653. if (order >= 0) {
  13654. this._gl.enableVertexAttribArray(order);
  13655. this._vertexAttribArraysEnabled[order] = true;
  13656. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13657. }
  13658. offset += vertexDeclaration[index] * 4;
  13659. }
  13660. }
  13661. }
  13662. this._bindIndexBufferWithCache(indexBuffer);
  13663. };
  13664. Engine.prototype._unbindVertexArrayObject = function () {
  13665. if (!this._cachedVertexArrayObject) {
  13666. return;
  13667. }
  13668. this._cachedVertexArrayObject = null;
  13669. this._gl.bindVertexArray(null);
  13670. };
  13671. /**
  13672. * Bind a list of vertex buffers to the webGL context
  13673. * @param vertexBuffers defines the list of vertex buffers to bind
  13674. * @param indexBuffer defines the index buffer to bind
  13675. * @param effect defines the effect associated with the vertex buffers
  13676. */
  13677. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13678. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13679. this._cachedVertexBuffers = vertexBuffers;
  13680. this._cachedEffectForVertexBuffers = effect;
  13681. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13682. }
  13683. this._bindIndexBufferWithCache(indexBuffer);
  13684. };
  13685. /**
  13686. * Unbind all instance attributes
  13687. */
  13688. Engine.prototype.unbindInstanceAttributes = function () {
  13689. var boundBuffer;
  13690. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13691. var instancesBuffer = this._currentInstanceBuffers[i];
  13692. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13693. boundBuffer = instancesBuffer;
  13694. this.bindArrayBuffer(instancesBuffer);
  13695. }
  13696. var offsetLocation = this._currentInstanceLocations[i];
  13697. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13698. }
  13699. this._currentInstanceBuffers.length = 0;
  13700. this._currentInstanceLocations.length = 0;
  13701. };
  13702. /**
  13703. * Release and free the memory of a vertex array object
  13704. * @param vao defines the vertex array object to delete
  13705. */
  13706. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13707. this._gl.deleteVertexArray(vao);
  13708. };
  13709. /** @hidden */
  13710. Engine.prototype._releaseBuffer = function (buffer) {
  13711. buffer.references--;
  13712. if (buffer.references === 0) {
  13713. this._gl.deleteBuffer(buffer);
  13714. return true;
  13715. }
  13716. return false;
  13717. };
  13718. /**
  13719. * Creates a webGL buffer to use with instanciation
  13720. * @param capacity defines the size of the buffer
  13721. * @returns the webGL buffer
  13722. */
  13723. Engine.prototype.createInstancesBuffer = function (capacity) {
  13724. var buffer = this._gl.createBuffer();
  13725. if (!buffer) {
  13726. throw new Error("Unable to create instance buffer");
  13727. }
  13728. buffer.capacity = capacity;
  13729. this.bindArrayBuffer(buffer);
  13730. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13731. return buffer;
  13732. };
  13733. /**
  13734. * Delete a webGL buffer used with instanciation
  13735. * @param buffer defines the webGL buffer to delete
  13736. */
  13737. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13738. this._gl.deleteBuffer(buffer);
  13739. };
  13740. /**
  13741. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13742. * @param instancesBuffer defines the webGL buffer to update and bind
  13743. * @param data defines the data to store in the buffer
  13744. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13745. */
  13746. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13747. this.bindArrayBuffer(instancesBuffer);
  13748. if (data) {
  13749. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13750. }
  13751. if (offsetLocations[0].index !== undefined) {
  13752. var stride = 0;
  13753. for (var i = 0; i < offsetLocations.length; i++) {
  13754. var ai = offsetLocations[i];
  13755. stride += ai.attributeSize * 4;
  13756. }
  13757. for (var i = 0; i < offsetLocations.length; i++) {
  13758. var ai = offsetLocations[i];
  13759. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13760. this._gl.enableVertexAttribArray(ai.index);
  13761. this._vertexAttribArraysEnabled[ai.index] = true;
  13762. }
  13763. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13764. this._gl.vertexAttribDivisor(ai.index, 1);
  13765. this._currentInstanceLocations.push(ai.index);
  13766. this._currentInstanceBuffers.push(instancesBuffer);
  13767. }
  13768. }
  13769. else {
  13770. for (var index = 0; index < 4; index++) {
  13771. var offsetLocation = offsetLocations[index];
  13772. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13773. this._gl.enableVertexAttribArray(offsetLocation);
  13774. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13775. }
  13776. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13777. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13778. this._currentInstanceLocations.push(offsetLocation);
  13779. this._currentInstanceBuffers.push(instancesBuffer);
  13780. }
  13781. }
  13782. };
  13783. /**
  13784. * Apply all cached states (depth, culling, stencil and alpha)
  13785. */
  13786. Engine.prototype.applyStates = function () {
  13787. this._depthCullingState.apply(this._gl);
  13788. this._stencilState.apply(this._gl);
  13789. this._alphaState.apply(this._gl);
  13790. };
  13791. /**
  13792. * Send a draw order
  13793. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13794. * @param indexStart defines the starting index
  13795. * @param indexCount defines the number of index to draw
  13796. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13797. */
  13798. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13799. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13800. };
  13801. /**
  13802. * Draw a list of points
  13803. * @param verticesStart defines the index of first vertex to draw
  13804. * @param verticesCount defines the count of vertices to draw
  13805. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13806. */
  13807. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13808. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13809. };
  13810. /**
  13811. * Draw a list of unindexed primitives
  13812. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13813. * @param verticesStart defines the index of first vertex to draw
  13814. * @param verticesCount defines the count of vertices to draw
  13815. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13816. */
  13817. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13818. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  13819. };
  13820. /**
  13821. * Draw a list of indexed primitives
  13822. * @param fillMode defines the primitive to use
  13823. * @param indexStart defines the starting index
  13824. * @param indexCount defines the number of index to draw
  13825. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13826. */
  13827. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  13828. // Apply states
  13829. this.applyStates();
  13830. this._drawCalls.addCount(1, false);
  13831. // Render
  13832. var drawMode = this._drawMode(fillMode);
  13833. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  13834. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  13835. if (instancesCount) {
  13836. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  13837. }
  13838. else {
  13839. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  13840. }
  13841. };
  13842. /**
  13843. * Draw a list of unindexed primitives
  13844. * @param fillMode defines the primitive to use
  13845. * @param verticesStart defines the index of first vertex to draw
  13846. * @param verticesCount defines the count of vertices to draw
  13847. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13848. */
  13849. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  13850. // Apply states
  13851. this.applyStates();
  13852. this._drawCalls.addCount(1, false);
  13853. var drawMode = this._drawMode(fillMode);
  13854. if (instancesCount) {
  13855. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  13856. }
  13857. else {
  13858. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  13859. }
  13860. };
  13861. Engine.prototype._drawMode = function (fillMode) {
  13862. switch (fillMode) {
  13863. // Triangle views
  13864. case BABYLON.Material.TriangleFillMode:
  13865. return this._gl.TRIANGLES;
  13866. case BABYLON.Material.PointFillMode:
  13867. return this._gl.POINTS;
  13868. case BABYLON.Material.WireFrameFillMode:
  13869. return this._gl.LINES;
  13870. // Draw modes
  13871. case BABYLON.Material.PointListDrawMode:
  13872. return this._gl.POINTS;
  13873. case BABYLON.Material.LineListDrawMode:
  13874. return this._gl.LINES;
  13875. case BABYLON.Material.LineLoopDrawMode:
  13876. return this._gl.LINE_LOOP;
  13877. case BABYLON.Material.LineStripDrawMode:
  13878. return this._gl.LINE_STRIP;
  13879. case BABYLON.Material.TriangleStripDrawMode:
  13880. return this._gl.TRIANGLE_STRIP;
  13881. case BABYLON.Material.TriangleFanDrawMode:
  13882. return this._gl.TRIANGLE_FAN;
  13883. default:
  13884. return this._gl.TRIANGLES;
  13885. }
  13886. };
  13887. // Shaders
  13888. /** @hidden */
  13889. Engine.prototype._releaseEffect = function (effect) {
  13890. if (this._compiledEffects[effect._key]) {
  13891. delete this._compiledEffects[effect._key];
  13892. this._deleteProgram(effect.getProgram());
  13893. }
  13894. };
  13895. /** @hidden */
  13896. Engine.prototype._deleteProgram = function (program) {
  13897. if (program) {
  13898. program.__SPECTOR_rebuildProgram = null;
  13899. if (program.transformFeedback) {
  13900. this.deleteTransformFeedback(program.transformFeedback);
  13901. program.transformFeedback = null;
  13902. }
  13903. this._gl.deleteProgram(program);
  13904. }
  13905. };
  13906. /**
  13907. * Create a new effect (used to store vertex/fragment shaders)
  13908. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  13909. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  13910. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  13911. * @param samplers defines an array of string used to represent textures
  13912. * @param defines defines the string containing the defines to use to compile the shaders
  13913. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13914. * @param onCompiled defines a function to call when the effect creation is successful
  13915. * @param onError defines a function to call when the effect creation has failed
  13916. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  13917. * @returns the new Effect
  13918. */
  13919. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  13920. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  13921. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  13922. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  13923. if (this._compiledEffects[name]) {
  13924. var compiledEffect = this._compiledEffects[name];
  13925. if (onCompiled && compiledEffect.isReady()) {
  13926. onCompiled(compiledEffect);
  13927. }
  13928. return compiledEffect;
  13929. }
  13930. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  13931. effect._key = name;
  13932. this._compiledEffects[name] = effect;
  13933. return effect;
  13934. };
  13935. /**
  13936. * Create an effect to use with particle systems
  13937. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  13938. * @param uniformsNames defines a list of attribute names
  13939. * @param samplers defines an array of string used to represent textures
  13940. * @param defines defines the string containing the defines to use to compile the shaders
  13941. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  13942. * @param onCompiled defines a function to call when the effect creation is successful
  13943. * @param onError defines a function to call when the effect creation has failed
  13944. * @returns the new Effect
  13945. */
  13946. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  13947. if (uniformsNames === void 0) { uniformsNames = []; }
  13948. if (samplers === void 0) { samplers = []; }
  13949. if (defines === void 0) { defines = ""; }
  13950. return this.createEffect({
  13951. vertex: "particles",
  13952. fragmentElement: fragmentName
  13953. }, ["position", "color", "options"], ["view", "projection"].concat(uniformsNames), ["diffuseSampler"].concat(samplers), defines, fallbacks, onCompiled, onError);
  13954. };
  13955. /**
  13956. * Directly creates a webGL program
  13957. * @param vertexCode defines the vertex shader code to use
  13958. * @param fragmentCode defines the fragment shader code to use
  13959. * @param context defines the webGL context to use (if not set, the current one will be used)
  13960. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13961. * @returns the new webGL program
  13962. */
  13963. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  13964. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13965. context = context || this._gl;
  13966. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  13967. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  13968. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13969. };
  13970. /**
  13971. * Creates a webGL program
  13972. * @param vertexCode defines the vertex shader code to use
  13973. * @param fragmentCode defines the fragment shader code to use
  13974. * @param defines defines the string containing the defines to use to compile the shaders
  13975. * @param context defines the webGL context to use (if not set, the current one will be used)
  13976. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  13977. * @returns the new webGL program
  13978. */
  13979. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  13980. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13981. context = context || this._gl;
  13982. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  13983. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  13984. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  13985. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  13986. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  13987. this.onAfterShaderCompilationObservable.notifyObservers(this);
  13988. return program;
  13989. };
  13990. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  13991. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  13992. var shaderProgram = context.createProgram();
  13993. if (!shaderProgram) {
  13994. throw new Error("Unable to create program");
  13995. }
  13996. context.attachShader(shaderProgram, vertexShader);
  13997. context.attachShader(shaderProgram, fragmentShader);
  13998. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  13999. var transformFeedback = this.createTransformFeedback();
  14000. this.bindTransformFeedback(transformFeedback);
  14001. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14002. shaderProgram.transformFeedback = transformFeedback;
  14003. }
  14004. context.linkProgram(shaderProgram);
  14005. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14006. this.bindTransformFeedback(null);
  14007. }
  14008. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14009. if (!linked) {
  14010. context.validateProgram(shaderProgram);
  14011. var error = context.getProgramInfoLog(shaderProgram);
  14012. if (error) {
  14013. throw new Error(error);
  14014. }
  14015. }
  14016. context.deleteShader(vertexShader);
  14017. context.deleteShader(fragmentShader);
  14018. return shaderProgram;
  14019. };
  14020. /**
  14021. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14022. * @param shaderProgram defines the webGL program to use
  14023. * @param uniformsNames defines the list of uniform names
  14024. * @returns an array of webGL uniform locations
  14025. */
  14026. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14027. var results = new Array();
  14028. for (var index = 0; index < uniformsNames.length; index++) {
  14029. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14030. }
  14031. return results;
  14032. };
  14033. /**
  14034. * Gets the lsit of active attributes for a given webGL program
  14035. * @param shaderProgram defines the webGL program to use
  14036. * @param attributesNames defines the list of attribute names to get
  14037. * @returns an array of indices indicating the offset of each attribute
  14038. */
  14039. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14040. var results = [];
  14041. for (var index = 0; index < attributesNames.length; index++) {
  14042. try {
  14043. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14044. }
  14045. catch (e) {
  14046. results.push(-1);
  14047. }
  14048. }
  14049. return results;
  14050. };
  14051. /**
  14052. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14053. * @param effect defines the effect to activate
  14054. */
  14055. Engine.prototype.enableEffect = function (effect) {
  14056. if (!effect) {
  14057. return;
  14058. }
  14059. // Use program
  14060. this.bindSamplers(effect);
  14061. this._currentEffect = effect;
  14062. if (effect.onBind) {
  14063. effect.onBind(effect);
  14064. }
  14065. effect.onBindObservable.notifyObservers(effect);
  14066. };
  14067. /**
  14068. * Set the value of an uniform to an array of int32
  14069. * @param uniform defines the webGL uniform location where to store the value
  14070. * @param array defines the array of int32 to store
  14071. */
  14072. Engine.prototype.setIntArray = function (uniform, array) {
  14073. if (!uniform)
  14074. return;
  14075. this._gl.uniform1iv(uniform, array);
  14076. };
  14077. /**
  14078. * Set the value of an uniform to an array of int32 (stored as vec2)
  14079. * @param uniform defines the webGL uniform location where to store the value
  14080. * @param array defines the array of int32 to store
  14081. */
  14082. Engine.prototype.setIntArray2 = function (uniform, array) {
  14083. if (!uniform || array.length % 2 !== 0)
  14084. return;
  14085. this._gl.uniform2iv(uniform, array);
  14086. };
  14087. /**
  14088. * Set the value of an uniform to an array of int32 (stored as vec3)
  14089. * @param uniform defines the webGL uniform location where to store the value
  14090. * @param array defines the array of int32 to store
  14091. */
  14092. Engine.prototype.setIntArray3 = function (uniform, array) {
  14093. if (!uniform || array.length % 3 !== 0)
  14094. return;
  14095. this._gl.uniform3iv(uniform, array);
  14096. };
  14097. /**
  14098. * Set the value of an uniform to an array of int32 (stored as vec4)
  14099. * @param uniform defines the webGL uniform location where to store the value
  14100. * @param array defines the array of int32 to store
  14101. */
  14102. Engine.prototype.setIntArray4 = function (uniform, array) {
  14103. if (!uniform || array.length % 4 !== 0)
  14104. return;
  14105. this._gl.uniform4iv(uniform, array);
  14106. };
  14107. /**
  14108. * Set the value of an uniform to an array of float32
  14109. * @param uniform defines the webGL uniform location where to store the value
  14110. * @param array defines the array of float32 to store
  14111. */
  14112. Engine.prototype.setFloatArray = function (uniform, array) {
  14113. if (!uniform)
  14114. return;
  14115. this._gl.uniform1fv(uniform, array);
  14116. };
  14117. /**
  14118. * Set the value of an uniform to an array of float32 (stored as vec2)
  14119. * @param uniform defines the webGL uniform location where to store the value
  14120. * @param array defines the array of float32 to store
  14121. */
  14122. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14123. if (!uniform || array.length % 2 !== 0)
  14124. return;
  14125. this._gl.uniform2fv(uniform, array);
  14126. };
  14127. /**
  14128. * Set the value of an uniform to an array of float32 (stored as vec3)
  14129. * @param uniform defines the webGL uniform location where to store the value
  14130. * @param array defines the array of float32 to store
  14131. */
  14132. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14133. if (!uniform || array.length % 3 !== 0)
  14134. return;
  14135. this._gl.uniform3fv(uniform, array);
  14136. };
  14137. /**
  14138. * Set the value of an uniform to an array of float32 (stored as vec4)
  14139. * @param uniform defines the webGL uniform location where to store the value
  14140. * @param array defines the array of float32 to store
  14141. */
  14142. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14143. if (!uniform || array.length % 4 !== 0)
  14144. return;
  14145. this._gl.uniform4fv(uniform, array);
  14146. };
  14147. /**
  14148. * Set the value of an uniform to an array of number
  14149. * @param uniform defines the webGL uniform location where to store the value
  14150. * @param array defines the array of number to store
  14151. */
  14152. Engine.prototype.setArray = function (uniform, array) {
  14153. if (!uniform)
  14154. return;
  14155. this._gl.uniform1fv(uniform, array);
  14156. };
  14157. /**
  14158. * Set the value of an uniform to an array of number (stored as vec2)
  14159. * @param uniform defines the webGL uniform location where to store the value
  14160. * @param array defines the array of number to store
  14161. */
  14162. Engine.prototype.setArray2 = function (uniform, array) {
  14163. if (!uniform || array.length % 2 !== 0)
  14164. return;
  14165. this._gl.uniform2fv(uniform, array);
  14166. };
  14167. /**
  14168. * Set the value of an uniform to an array of number (stored as vec3)
  14169. * @param uniform defines the webGL uniform location where to store the value
  14170. * @param array defines the array of number to store
  14171. */
  14172. Engine.prototype.setArray3 = function (uniform, array) {
  14173. if (!uniform || array.length % 3 !== 0)
  14174. return;
  14175. this._gl.uniform3fv(uniform, array);
  14176. };
  14177. /**
  14178. * Set the value of an uniform to an array of number (stored as vec4)
  14179. * @param uniform defines the webGL uniform location where to store the value
  14180. * @param array defines the array of number to store
  14181. */
  14182. Engine.prototype.setArray4 = function (uniform, array) {
  14183. if (!uniform || array.length % 4 !== 0)
  14184. return;
  14185. this._gl.uniform4fv(uniform, array);
  14186. };
  14187. /**
  14188. * Set the value of an uniform to an array of float32 (stored as matrices)
  14189. * @param uniform defines the webGL uniform location where to store the value
  14190. * @param matrices defines the array of float32 to store
  14191. */
  14192. Engine.prototype.setMatrices = function (uniform, matrices) {
  14193. if (!uniform)
  14194. return;
  14195. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14196. };
  14197. /**
  14198. * Set the value of an uniform to a matrix
  14199. * @param uniform defines the webGL uniform location where to store the value
  14200. * @param matrix defines the matrix to store
  14201. */
  14202. Engine.prototype.setMatrix = function (uniform, matrix) {
  14203. if (!uniform)
  14204. return;
  14205. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14206. };
  14207. /**
  14208. * Set the value of an uniform to a matrix (3x3)
  14209. * @param uniform defines the webGL uniform location where to store the value
  14210. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14211. */
  14212. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14213. if (!uniform)
  14214. return;
  14215. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14216. };
  14217. /**
  14218. * Set the value of an uniform to a matrix (2x2)
  14219. * @param uniform defines the webGL uniform location where to store the value
  14220. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14221. */
  14222. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14223. if (!uniform)
  14224. return;
  14225. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14226. };
  14227. /**
  14228. * Set the value of an uniform to a number (int)
  14229. * @param uniform defines the webGL uniform location where to store the value
  14230. * @param value defines the int number to store
  14231. */
  14232. Engine.prototype.setInt = function (uniform, value) {
  14233. if (!uniform)
  14234. return;
  14235. this._gl.uniform1i(uniform, value);
  14236. };
  14237. /**
  14238. * Set the value of an uniform to a number (float)
  14239. * @param uniform defines the webGL uniform location where to store the value
  14240. * @param value defines the float number to store
  14241. */
  14242. Engine.prototype.setFloat = function (uniform, value) {
  14243. if (!uniform)
  14244. return;
  14245. this._gl.uniform1f(uniform, value);
  14246. };
  14247. /**
  14248. * Set the value of an uniform to a vec2
  14249. * @param uniform defines the webGL uniform location where to store the value
  14250. * @param x defines the 1st component of the value
  14251. * @param y defines the 2nd component of the value
  14252. */
  14253. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14254. if (!uniform)
  14255. return;
  14256. this._gl.uniform2f(uniform, x, y);
  14257. };
  14258. /**
  14259. * Set the value of an uniform to a vec3
  14260. * @param uniform defines the webGL uniform location where to store the value
  14261. * @param x defines the 1st component of the value
  14262. * @param y defines the 2nd component of the value
  14263. * @param z defines the 3rd component of the value
  14264. */
  14265. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14266. if (!uniform)
  14267. return;
  14268. this._gl.uniform3f(uniform, x, y, z);
  14269. };
  14270. /**
  14271. * Set the value of an uniform to a boolean
  14272. * @param uniform defines the webGL uniform location where to store the value
  14273. * @param bool defines the boolean to store
  14274. */
  14275. Engine.prototype.setBool = function (uniform, bool) {
  14276. if (!uniform)
  14277. return;
  14278. this._gl.uniform1i(uniform, bool);
  14279. };
  14280. /**
  14281. * Set the value of an uniform to a vec4
  14282. * @param uniform defines the webGL uniform location where to store the value
  14283. * @param x defines the 1st component of the value
  14284. * @param y defines the 2nd component of the value
  14285. * @param z defines the 3rd component of the value
  14286. * @param w defines the 4th component of the value
  14287. */
  14288. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14289. if (!uniform)
  14290. return;
  14291. this._gl.uniform4f(uniform, x, y, z, w);
  14292. };
  14293. /**
  14294. * Set the value of an uniform to a Color3
  14295. * @param uniform defines the webGL uniform location where to store the value
  14296. * @param color3 defines the color to store
  14297. */
  14298. Engine.prototype.setColor3 = function (uniform, color3) {
  14299. if (!uniform)
  14300. return;
  14301. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14302. };
  14303. /**
  14304. * Set the value of an uniform to a Color3 and an alpha value
  14305. * @param uniform defines the webGL uniform location where to store the value
  14306. * @param color3 defines the color to store
  14307. * @param alpha defines the alpha component to store
  14308. */
  14309. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14313. };
  14314. /**
  14315. * Sets a Color4 on a uniform variable
  14316. * @param uniform defines the uniform location
  14317. * @param color4 defines the value to be set
  14318. */
  14319. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14320. if (!uniform)
  14321. return;
  14322. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14323. };
  14324. // States
  14325. /**
  14326. * Set various states to the webGL context
  14327. * @param culling defines backface culling state
  14328. * @param zOffset defines the value to apply to zOffset (0 by default)
  14329. * @param force defines if states must be applied even if cache is up to date
  14330. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14331. */
  14332. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14333. if (zOffset === void 0) { zOffset = 0; }
  14334. if (reverseSide === void 0) { reverseSide = false; }
  14335. // Culling
  14336. if (this._depthCullingState.cull !== culling || force) {
  14337. this._depthCullingState.cull = culling;
  14338. }
  14339. // Cull face
  14340. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14341. if (this._depthCullingState.cullFace !== cullFace || force) {
  14342. this._depthCullingState.cullFace = cullFace;
  14343. }
  14344. // Z offset
  14345. this.setZOffset(zOffset);
  14346. // Front face
  14347. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14348. if (this._depthCullingState.frontFace !== frontFace || force) {
  14349. this._depthCullingState.frontFace = frontFace;
  14350. }
  14351. };
  14352. /**
  14353. * Set the z offset to apply to current rendering
  14354. * @param value defines the offset to apply
  14355. */
  14356. Engine.prototype.setZOffset = function (value) {
  14357. this._depthCullingState.zOffset = value;
  14358. };
  14359. /**
  14360. * Gets the current value of the zOffset
  14361. * @returns the current zOffset state
  14362. */
  14363. Engine.prototype.getZOffset = function () {
  14364. return this._depthCullingState.zOffset;
  14365. };
  14366. /**
  14367. * Enable or disable depth buffering
  14368. * @param enable defines the state to set
  14369. */
  14370. Engine.prototype.setDepthBuffer = function (enable) {
  14371. this._depthCullingState.depthTest = enable;
  14372. };
  14373. /**
  14374. * Gets a boolean indicating if depth writing is enabled
  14375. * @returns the current depth writing state
  14376. */
  14377. Engine.prototype.getDepthWrite = function () {
  14378. return this._depthCullingState.depthMask;
  14379. };
  14380. /**
  14381. * Enable or disable depth writing
  14382. * @param enable defines the state to set
  14383. */
  14384. Engine.prototype.setDepthWrite = function (enable) {
  14385. this._depthCullingState.depthMask = enable;
  14386. };
  14387. /**
  14388. * Enable or disable color writing
  14389. * @param enable defines the state to set
  14390. */
  14391. Engine.prototype.setColorWrite = function (enable) {
  14392. this._gl.colorMask(enable, enable, enable, enable);
  14393. this._colorWrite = enable;
  14394. };
  14395. /**
  14396. * Gets a boolean indicating if color writing is enabled
  14397. * @returns the current color writing state
  14398. */
  14399. Engine.prototype.getColorWrite = function () {
  14400. return this._colorWrite;
  14401. };
  14402. /**
  14403. * Sets alpha constants used by some alpha blending modes
  14404. * @param r defines the red component
  14405. * @param g defines the green component
  14406. * @param b defines the blue component
  14407. * @param a defines the alpha component
  14408. */
  14409. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14410. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14411. };
  14412. /**
  14413. * Sets the current alpha mode
  14414. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14415. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14416. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14417. */
  14418. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14419. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14420. if (this._alphaMode === mode) {
  14421. return;
  14422. }
  14423. switch (mode) {
  14424. case Engine.ALPHA_DISABLE:
  14425. this._alphaState.alphaBlend = false;
  14426. break;
  14427. case Engine.ALPHA_PREMULTIPLIED:
  14428. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14429. this._alphaState.alphaBlend = true;
  14430. break;
  14431. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14432. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14433. this._alphaState.alphaBlend = true;
  14434. break;
  14435. case Engine.ALPHA_COMBINE:
  14436. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14437. this._alphaState.alphaBlend = true;
  14438. break;
  14439. case Engine.ALPHA_ONEONE:
  14440. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14441. this._alphaState.alphaBlend = true;
  14442. break;
  14443. case Engine.ALPHA_ADD:
  14444. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14445. this._alphaState.alphaBlend = true;
  14446. break;
  14447. case Engine.ALPHA_SUBTRACT:
  14448. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14449. this._alphaState.alphaBlend = true;
  14450. break;
  14451. case Engine.ALPHA_MULTIPLY:
  14452. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14453. this._alphaState.alphaBlend = true;
  14454. break;
  14455. case Engine.ALPHA_MAXIMIZED:
  14456. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14457. this._alphaState.alphaBlend = true;
  14458. break;
  14459. case Engine.ALPHA_INTERPOLATE:
  14460. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14461. this._alphaState.alphaBlend = true;
  14462. break;
  14463. case Engine.ALPHA_SCREENMODE:
  14464. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14465. this._alphaState.alphaBlend = true;
  14466. break;
  14467. }
  14468. if (!noDepthWriteChange) {
  14469. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14470. }
  14471. this._alphaMode = mode;
  14472. };
  14473. /**
  14474. * Gets the current alpha mode
  14475. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14476. * @returns the current alpha mode
  14477. */
  14478. Engine.prototype.getAlphaMode = function () {
  14479. return this._alphaMode;
  14480. };
  14481. // Textures
  14482. /**
  14483. * Force the entire cache to be cleared
  14484. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14485. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14486. */
  14487. Engine.prototype.wipeCaches = function (bruteForce) {
  14488. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14489. return;
  14490. }
  14491. this._currentEffect = null;
  14492. if (bruteForce) {
  14493. this.resetTextureCache();
  14494. this._currentProgram = null;
  14495. this._stencilState.reset();
  14496. this._depthCullingState.reset();
  14497. this.setDepthFunctionToLessOrEqual();
  14498. this._alphaState.reset();
  14499. }
  14500. this._resetVertexBufferBinding();
  14501. this._cachedIndexBuffer = null;
  14502. this._cachedEffectForVertexBuffers = null;
  14503. this._unbindVertexArrayObject();
  14504. this.bindIndexBuffer(null);
  14505. };
  14506. /**
  14507. * Set the compressed texture format to use, based on the formats you have, and the formats
  14508. * supported by the hardware / browser.
  14509. *
  14510. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14511. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14512. * to API arguments needed to compressed textures. This puts the burden on the container
  14513. * generator to house the arcane code for determining these for current & future formats.
  14514. *
  14515. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14516. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14517. *
  14518. * Note: The result of this call is not taken into account when a texture is base64.
  14519. *
  14520. * @param formatsAvailable defines the list of those format families you have created
  14521. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14522. *
  14523. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14524. * @returns The extension selected.
  14525. */
  14526. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14527. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14528. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14529. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14530. return this._textureFormatInUse = this._texturesSupported[i];
  14531. }
  14532. }
  14533. }
  14534. // actively set format to nothing, to allow this to be called more than once
  14535. // and possibly fail the 2nd time
  14536. this._textureFormatInUse = null;
  14537. return null;
  14538. };
  14539. /** @hidden */
  14540. Engine.prototype._createTexture = function () {
  14541. var texture = this._gl.createTexture();
  14542. if (!texture) {
  14543. throw new Error("Unable to create texture");
  14544. }
  14545. return texture;
  14546. };
  14547. /**
  14548. * Usually called from BABYLON.Texture.ts.
  14549. * Passed information to create a WebGLTexture
  14550. * @param urlArg defines a value which contains one of the following:
  14551. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14552. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14553. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14554. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14555. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14556. * @param scene needed for loading to the correct scene
  14557. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14558. * @param onLoad optional callback to be called upon successful completion
  14559. * @param onError optional callback to be called upon failure
  14560. * @param buffer a source of a file previously fetched as either an ArrayBuffer (compressed or image format) or HTMLImageElement (image format)
  14561. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14562. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14563. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14564. */
  14565. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14566. var _this = this;
  14567. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14568. if (onLoad === void 0) { onLoad = null; }
  14569. if (onError === void 0) { onError = null; }
  14570. if (buffer === void 0) { buffer = null; }
  14571. if (fallback === void 0) { fallback = null; }
  14572. if (format === void 0) { format = null; }
  14573. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14574. var fromData = url.substr(0, 5) === "data:";
  14575. var fromBlob = url.substr(0, 5) === "blob:";
  14576. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14577. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14578. // establish the file extension, if possible
  14579. var lastDot = url.lastIndexOf('.');
  14580. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14581. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14582. var isTGA = (extension.indexOf(".tga") === 0);
  14583. // determine if a ktx file should be substituted
  14584. var isKTX = false;
  14585. if (this._textureFormatInUse && !isBase64 && !fallback) {
  14586. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14587. isKTX = true;
  14588. }
  14589. if (scene) {
  14590. scene._addPendingData(texture);
  14591. }
  14592. texture.url = url;
  14593. texture.generateMipMaps = !noMipmap;
  14594. texture.samplingMode = samplingMode;
  14595. texture.invertY = invertY;
  14596. if (!this._doNotHandleContextLost) {
  14597. // Keep a link to the buffer only if we plan to handle context lost
  14598. texture._buffer = buffer;
  14599. }
  14600. var onLoadObserver = null;
  14601. if (onLoad && !fallback) {
  14602. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14603. }
  14604. if (!fallback)
  14605. this._internalTexturesCache.push(texture);
  14606. var onerror = function (message, exception) {
  14607. if (scene) {
  14608. scene._removePendingData(texture);
  14609. }
  14610. if (onLoadObserver) {
  14611. texture.onLoadedObservable.remove(onLoadObserver);
  14612. }
  14613. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14614. if (isKTX) {
  14615. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14616. }
  14617. else if (BABYLON.Tools.UseFallbackTexture) {
  14618. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14619. }
  14620. if (onError) {
  14621. onError(message || "Unknown error", exception);
  14622. }
  14623. };
  14624. var callback = null;
  14625. // processing for non-image formats
  14626. if (isKTX || isTGA || isDDS) {
  14627. if (isKTX) {
  14628. callback = function (data) {
  14629. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14630. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14631. ktx.uploadLevels(_this._gl, !noMipmap);
  14632. return false;
  14633. }, samplingMode);
  14634. };
  14635. }
  14636. else if (isTGA) {
  14637. callback = function (arrayBuffer) {
  14638. var data = new Uint8Array(arrayBuffer);
  14639. var header = BABYLON.TGATools.GetTGAHeader(data);
  14640. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14641. BABYLON.TGATools.UploadContent(_this._gl, data);
  14642. return false;
  14643. }, samplingMode);
  14644. };
  14645. }
  14646. else if (isDDS) {
  14647. callback = function (data) {
  14648. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14649. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14650. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14651. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14652. return false;
  14653. }, samplingMode);
  14654. };
  14655. }
  14656. if (!buffer) {
  14657. this._loadFile(url, function (data) {
  14658. if (callback) {
  14659. callback(data);
  14660. }
  14661. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14662. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14663. });
  14664. }
  14665. else {
  14666. if (callback) {
  14667. callback(buffer);
  14668. }
  14669. }
  14670. // image format processing
  14671. }
  14672. else {
  14673. var onload = function (img) {
  14674. if (fromBlob && !_this._doNotHandleContextLost) {
  14675. // We need to store the image if we need to rebuild the texture
  14676. // in case of a webgl context lost
  14677. texture._buffer = img;
  14678. }
  14679. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14680. var gl = _this._gl;
  14681. var isPot = (img.width === potWidth && img.height === potHeight);
  14682. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14683. if (isPot) {
  14684. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14685. return false;
  14686. }
  14687. // Using shaders to rescale because canvas.drawImage is lossy
  14688. var source = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14689. _this._bindTextureDirectly(gl.TEXTURE_2D, source, true);
  14690. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14691. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14692. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14693. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14694. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14695. _this._rescaleTexture(source, texture, scene, internalFormat, function () {
  14696. _this._releaseTexture(source);
  14697. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14698. continuationCallback();
  14699. });
  14700. return true;
  14701. }, samplingMode);
  14702. };
  14703. if (!fromData || isBase64)
  14704. if (buffer instanceof HTMLImageElement) {
  14705. onload(buffer);
  14706. }
  14707. else {
  14708. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14709. }
  14710. else if (buffer instanceof Array || typeof buffer === "string" || buffer instanceof ArrayBuffer)
  14711. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14712. else
  14713. onload(buffer);
  14714. }
  14715. return texture;
  14716. };
  14717. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14718. var _this = this;
  14719. var rtt = this.createRenderTargetTexture({
  14720. width: destination.width,
  14721. height: destination.height,
  14722. }, {
  14723. generateMipMaps: false,
  14724. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14725. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14726. generateDepthBuffer: false,
  14727. generateStencilBuffer: false
  14728. });
  14729. if (!this._rescalePostProcess) {
  14730. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14731. }
  14732. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14733. _this._rescalePostProcess.onApply = function (effect) {
  14734. effect._bindTexture("textureSampler", source);
  14735. };
  14736. var hostingScene = scene;
  14737. if (!hostingScene) {
  14738. hostingScene = _this.scenes[_this.scenes.length - 1];
  14739. }
  14740. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14741. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14742. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14743. _this.unBindFramebuffer(rtt);
  14744. _this._releaseTexture(rtt);
  14745. if (onComplete) {
  14746. onComplete();
  14747. }
  14748. });
  14749. };
  14750. /**
  14751. * Update a raw texture
  14752. * @param texture defines the texture to update
  14753. * @param data defines the data to store in the texture
  14754. * @param format defines the format of the data
  14755. * @param invertY defines if data must be stored with Y axis inverted
  14756. * @param compression defines the compression used (null by default)
  14757. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14758. */
  14759. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14760. if (compression === void 0) { compression = null; }
  14761. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14762. if (!texture) {
  14763. return;
  14764. }
  14765. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14766. var internalFormat = this._getInternalFormat(format);
  14767. var textureType = this._getWebGLTextureType(type);
  14768. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14769. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  14770. if (!this._doNotHandleContextLost) {
  14771. texture._bufferView = data;
  14772. texture.format = format;
  14773. texture.type = type;
  14774. texture.invertY = invertY;
  14775. texture._compression = compression;
  14776. }
  14777. if (texture.width % 4 !== 0) {
  14778. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  14779. }
  14780. if (compression && data) {
  14781. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  14782. }
  14783. else {
  14784. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  14785. }
  14786. if (texture.generateMipMaps) {
  14787. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14788. }
  14789. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14790. // this.resetTextureCache();
  14791. texture.isReady = true;
  14792. };
  14793. /**
  14794. * Creates a raw texture
  14795. * @param data defines the data to store in the texture
  14796. * @param width defines the width of the texture
  14797. * @param height defines the height of the texture
  14798. * @param format defines the format of the data
  14799. * @param generateMipMaps defines if the engine should generate the mip levels
  14800. * @param invertY defines if data must be stored with Y axis inverted
  14801. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14802. * @param compression defines the compression used (null by default)
  14803. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14804. * @returns the raw texture inside an InternalTexture
  14805. */
  14806. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  14807. if (compression === void 0) { compression = null; }
  14808. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14809. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  14810. texture.baseWidth = width;
  14811. texture.baseHeight = height;
  14812. texture.width = width;
  14813. texture.height = height;
  14814. texture.format = format;
  14815. texture.generateMipMaps = generateMipMaps;
  14816. texture.samplingMode = samplingMode;
  14817. texture.invertY = invertY;
  14818. texture._compression = compression;
  14819. texture.type = type;
  14820. if (!this._doNotHandleContextLost) {
  14821. texture._bufferView = data;
  14822. }
  14823. this.updateRawTexture(texture, data, format, invertY, compression, type);
  14824. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14825. // Filters
  14826. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  14827. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  14828. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14829. if (generateMipMaps) {
  14830. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14831. }
  14832. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14833. this._internalTexturesCache.push(texture);
  14834. return texture;
  14835. };
  14836. /**
  14837. * Creates a dynamic texture
  14838. * @param width defines the width of the texture
  14839. * @param height defines the height of the texture
  14840. * @param generateMipMaps defines if the engine should generate the mip levels
  14841. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  14842. * @returns the dynamic texture inside an InternalTexture
  14843. */
  14844. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  14845. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  14846. texture.baseWidth = width;
  14847. texture.baseHeight = height;
  14848. if (generateMipMaps) {
  14849. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  14850. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  14851. }
  14852. // this.resetTextureCache();
  14853. texture.width = width;
  14854. texture.height = height;
  14855. texture.isReady = false;
  14856. texture.generateMipMaps = generateMipMaps;
  14857. texture.samplingMode = samplingMode;
  14858. this.updateTextureSamplingMode(samplingMode, texture);
  14859. this._internalTexturesCache.push(texture);
  14860. return texture;
  14861. };
  14862. /**
  14863. * Update the sampling mode of a given texture
  14864. * @param samplingMode defines the required sampling mode
  14865. * @param texture defines the texture to update
  14866. */
  14867. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  14868. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  14869. if (texture.isCube) {
  14870. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14871. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14872. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14873. }
  14874. else if (texture.is3D) {
  14875. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14876. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14877. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  14878. }
  14879. else {
  14880. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  14881. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  14882. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14883. }
  14884. texture.samplingMode = samplingMode;
  14885. };
  14886. /**
  14887. * Update the content of a dynamic texture
  14888. * @param texture defines the texture to update
  14889. * @param canvas defines the canvas containing the source
  14890. * @param invertY defines if data must be stored with Y axis inverted
  14891. * @param premulAlpha defines if alpha is stored as premultiplied
  14892. * @param format defines the format of the data
  14893. */
  14894. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  14895. if (premulAlpha === void 0) { premulAlpha = false; }
  14896. if (!texture) {
  14897. return;
  14898. }
  14899. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14900. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 1 : 0);
  14901. if (premulAlpha) {
  14902. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  14903. }
  14904. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  14905. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  14906. if (texture.generateMipMaps) {
  14907. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14908. }
  14909. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14910. if (premulAlpha) {
  14911. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  14912. }
  14913. texture.isReady = true;
  14914. };
  14915. /**
  14916. * Update a video texture
  14917. * @param texture defines the texture to update
  14918. * @param video defines the video element to use
  14919. * @param invertY defines if data must be stored with Y axis inverted
  14920. */
  14921. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  14922. if (!texture || texture._isDisabled) {
  14923. return;
  14924. }
  14925. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14926. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY ? 0 : 1); // Video are upside down by default
  14927. try {
  14928. // Testing video texture support
  14929. if (this._videoTextureSupported === undefined) {
  14930. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14931. if (this._gl.getError() !== 0) {
  14932. this._videoTextureSupported = false;
  14933. }
  14934. else {
  14935. this._videoTextureSupported = true;
  14936. }
  14937. }
  14938. // Copy video through the current working canvas if video texture is not supported
  14939. if (!this._videoTextureSupported) {
  14940. if (!texture._workingCanvas) {
  14941. texture._workingCanvas = document.createElement("canvas");
  14942. var context = texture._workingCanvas.getContext("2d");
  14943. if (!context) {
  14944. throw new Error("Unable to get 2d context");
  14945. }
  14946. texture._workingContext = context;
  14947. texture._workingCanvas.width = texture.width;
  14948. texture._workingCanvas.height = texture.height;
  14949. }
  14950. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  14951. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  14952. }
  14953. else {
  14954. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  14955. }
  14956. if (texture.generateMipMaps) {
  14957. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  14958. }
  14959. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  14960. // this.resetTextureCache();
  14961. texture.isReady = true;
  14962. }
  14963. catch (ex) {
  14964. // Something unexpected
  14965. // Let's disable the texture
  14966. texture._isDisabled = true;
  14967. }
  14968. };
  14969. /**
  14970. * Updates a depth texture Comparison Mode and Function.
  14971. * If the comparison Function is equal to 0, the mode will be set to none.
  14972. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  14973. * @param texture The texture to set the comparison function for
  14974. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  14975. */
  14976. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  14977. if (this.webGLVersion === 1) {
  14978. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  14979. return;
  14980. }
  14981. var gl = this._gl;
  14982. if (texture.isCube) {
  14983. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  14984. if (comparisonFunction === 0) {
  14985. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14986. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14987. }
  14988. else {
  14989. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  14990. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  14991. }
  14992. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  14993. }
  14994. else {
  14995. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  14996. if (comparisonFunction === 0) {
  14997. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  14998. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  14999. }
  15000. else {
  15001. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15002. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15003. }
  15004. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15005. }
  15006. texture._comparisonFunction = comparisonFunction;
  15007. };
  15008. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15009. var width = size.width || size;
  15010. var height = size.height || size;
  15011. internalTexture.baseWidth = width;
  15012. internalTexture.baseHeight = height;
  15013. internalTexture.width = width;
  15014. internalTexture.height = height;
  15015. internalTexture.isReady = true;
  15016. internalTexture.samples = 1;
  15017. internalTexture.generateMipMaps = false;
  15018. internalTexture._generateDepthBuffer = true;
  15019. internalTexture._generateStencilBuffer = generateStencil;
  15020. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15021. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15022. internalTexture._comparisonFunction = comparisonFunction;
  15023. var gl = this._gl;
  15024. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15025. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15026. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15027. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15028. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15029. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15030. if (comparisonFunction === 0) {
  15031. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15032. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15033. }
  15034. else {
  15035. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15036. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15037. }
  15038. };
  15039. /**
  15040. * Creates a depth stencil texture.
  15041. * This is only available in WebGL 2 or with the depth texture extension available.
  15042. * @param size The size of face edge in the texture.
  15043. * @param options The options defining the texture.
  15044. * @returns The texture
  15045. */
  15046. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15047. if (options.isCube) {
  15048. var width = size.width || size;
  15049. return this._createDepthStencilCubeTexture(width, options);
  15050. }
  15051. else {
  15052. return this._createDepthStencilTexture(size, options);
  15053. }
  15054. };
  15055. /**
  15056. * Creates a depth stencil texture.
  15057. * This is only available in WebGL 2 or with the depth texture extension available.
  15058. * @param size The size of face edge in the texture.
  15059. * @param options The options defining the texture.
  15060. * @returns The texture
  15061. */
  15062. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15063. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15064. if (!this._caps.depthTextureExtension) {
  15065. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15066. return internalTexture;
  15067. }
  15068. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15069. var gl = this._gl;
  15070. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15071. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15072. if (this.webGLVersion > 1) {
  15073. if (internalOptions.generateStencil) {
  15074. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15075. }
  15076. else {
  15077. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15078. }
  15079. }
  15080. else {
  15081. if (internalOptions.generateStencil) {
  15082. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15083. }
  15084. else {
  15085. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15086. }
  15087. }
  15088. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15089. return internalTexture;
  15090. };
  15091. /**
  15092. * Creates a depth stencil cube texture.
  15093. * This is only available in WebGL 2.
  15094. * @param size The size of face edge in the cube texture.
  15095. * @param options The options defining the cube texture.
  15096. * @returns The cube texture
  15097. */
  15098. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15099. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15100. internalTexture.isCube = true;
  15101. if (this.webGLVersion === 1) {
  15102. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15103. return internalTexture;
  15104. }
  15105. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15106. var gl = this._gl;
  15107. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15108. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15109. // Create the depth/stencil buffer
  15110. for (var face = 0; face < 6; face++) {
  15111. if (internalOptions.generateStencil) {
  15112. 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);
  15113. }
  15114. else {
  15115. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15116. }
  15117. }
  15118. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15119. return internalTexture;
  15120. };
  15121. /**
  15122. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15123. * @param renderTarget The render target to set the frame buffer for
  15124. */
  15125. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15126. // Create the framebuffer
  15127. var internalTexture = renderTarget.getInternalTexture();
  15128. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15129. return;
  15130. }
  15131. var gl = this._gl;
  15132. var depthStencilTexture = renderTarget.depthStencilTexture;
  15133. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15134. if (depthStencilTexture.isCube) {
  15135. if (depthStencilTexture._generateStencilBuffer) {
  15136. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15137. }
  15138. else {
  15139. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15140. }
  15141. }
  15142. else {
  15143. if (depthStencilTexture._generateStencilBuffer) {
  15144. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15145. }
  15146. else {
  15147. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15148. }
  15149. }
  15150. this.bindUnboundFramebuffer(null);
  15151. };
  15152. /**
  15153. * Creates a new render target texture
  15154. * @param size defines the size of the texture
  15155. * @param options defines the options used to create the texture
  15156. * @returns a new render target texture stored in an InternalTexture
  15157. */
  15158. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15159. var fullOptions = new RenderTargetCreationOptions();
  15160. if (options !== undefined && typeof options === "object") {
  15161. fullOptions.generateMipMaps = options.generateMipMaps;
  15162. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15163. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15164. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15165. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15166. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15167. }
  15168. else {
  15169. fullOptions.generateMipMaps = options;
  15170. fullOptions.generateDepthBuffer = true;
  15171. fullOptions.generateStencilBuffer = false;
  15172. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15173. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15174. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15175. }
  15176. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15177. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15178. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15179. }
  15180. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15181. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15182. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15183. }
  15184. var gl = this._gl;
  15185. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15186. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15187. var width = size.width || size;
  15188. var height = size.height || size;
  15189. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15190. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15191. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15192. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15193. }
  15194. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15195. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15196. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15197. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15198. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15199. // Create the framebuffer
  15200. var framebuffer = gl.createFramebuffer();
  15201. this.bindUnboundFramebuffer(framebuffer);
  15202. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15203. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15204. if (fullOptions.generateMipMaps) {
  15205. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15206. }
  15207. // Unbind
  15208. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15209. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15210. this.bindUnboundFramebuffer(null);
  15211. texture._framebuffer = framebuffer;
  15212. texture.baseWidth = width;
  15213. texture.baseHeight = height;
  15214. texture.width = width;
  15215. texture.height = height;
  15216. texture.isReady = true;
  15217. texture.samples = 1;
  15218. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15219. texture.samplingMode = fullOptions.samplingMode;
  15220. texture.type = fullOptions.type;
  15221. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15222. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15223. // this.resetTextureCache();
  15224. this._internalTexturesCache.push(texture);
  15225. return texture;
  15226. };
  15227. /**
  15228. * Create a multi render target texture
  15229. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15230. * @param size defines the size of the texture
  15231. * @param options defines the creation options
  15232. * @returns the cube texture as an InternalTexture
  15233. */
  15234. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15235. var generateMipMaps = false;
  15236. var generateDepthBuffer = true;
  15237. var generateStencilBuffer = false;
  15238. var generateDepthTexture = false;
  15239. var textureCount = 1;
  15240. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15241. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15242. var types = new Array();
  15243. var samplingModes = new Array();
  15244. if (options !== undefined) {
  15245. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15246. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15247. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15248. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15249. textureCount = options.textureCount || 1;
  15250. if (options.types) {
  15251. types = options.types;
  15252. }
  15253. if (options.samplingModes) {
  15254. samplingModes = options.samplingModes;
  15255. }
  15256. }
  15257. var gl = this._gl;
  15258. // Create the framebuffer
  15259. var framebuffer = gl.createFramebuffer();
  15260. this.bindUnboundFramebuffer(framebuffer);
  15261. var width = size.width || size;
  15262. var height = size.height || size;
  15263. var textures = [];
  15264. var attachments = [];
  15265. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15266. for (var i = 0; i < textureCount; i++) {
  15267. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15268. var type = types[i] || defaultType;
  15269. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15270. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15271. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15272. }
  15273. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15274. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15275. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15276. }
  15277. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15278. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15279. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15280. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15281. }
  15282. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15283. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15284. textures.push(texture);
  15285. attachments.push(attachment);
  15286. gl.activeTexture(gl["TEXTURE" + i]);
  15287. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15288. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15289. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15290. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15291. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15292. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15293. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15294. if (generateMipMaps) {
  15295. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15296. }
  15297. // Unbind
  15298. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15299. texture._framebuffer = framebuffer;
  15300. texture._depthStencilBuffer = depthStencilBuffer;
  15301. texture.baseWidth = width;
  15302. texture.baseHeight = height;
  15303. texture.width = width;
  15304. texture.height = height;
  15305. texture.isReady = true;
  15306. texture.samples = 1;
  15307. texture.generateMipMaps = generateMipMaps;
  15308. texture.samplingMode = samplingMode;
  15309. texture.type = type;
  15310. texture._generateDepthBuffer = generateDepthBuffer;
  15311. texture._generateStencilBuffer = generateStencilBuffer;
  15312. texture._attachments = attachments;
  15313. this._internalTexturesCache.push(texture);
  15314. }
  15315. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15316. // Depth texture
  15317. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15318. gl.activeTexture(gl.TEXTURE0);
  15319. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15320. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15321. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15322. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15323. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15324. 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);
  15325. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15326. depthTexture._framebuffer = framebuffer;
  15327. depthTexture.baseWidth = width;
  15328. depthTexture.baseHeight = height;
  15329. depthTexture.width = width;
  15330. depthTexture.height = height;
  15331. depthTexture.isReady = true;
  15332. depthTexture.samples = 1;
  15333. depthTexture.generateMipMaps = generateMipMaps;
  15334. depthTexture.samplingMode = gl.NEAREST;
  15335. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15336. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15337. textures.push(depthTexture);
  15338. this._internalTexturesCache.push(depthTexture);
  15339. }
  15340. gl.drawBuffers(attachments);
  15341. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15342. this.bindUnboundFramebuffer(null);
  15343. this.resetTextureCache();
  15344. return textures;
  15345. };
  15346. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15347. if (samples === void 0) { samples = 1; }
  15348. var depthStencilBuffer = null;
  15349. var gl = this._gl;
  15350. // Create the depth/stencil buffer
  15351. if (generateStencilBuffer) {
  15352. depthStencilBuffer = gl.createRenderbuffer();
  15353. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15354. if (samples > 1) {
  15355. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15356. }
  15357. else {
  15358. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15359. }
  15360. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15361. }
  15362. else if (generateDepthBuffer) {
  15363. depthStencilBuffer = gl.createRenderbuffer();
  15364. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15365. if (samples > 1) {
  15366. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15367. }
  15368. else {
  15369. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15370. }
  15371. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15372. }
  15373. return depthStencilBuffer;
  15374. };
  15375. /**
  15376. * Updates the sample count of a render target texture
  15377. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15378. * @param texture defines the texture to update
  15379. * @param samples defines the sample count to set
  15380. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15381. */
  15382. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15383. if (this.webGLVersion < 2 || !texture) {
  15384. return 1;
  15385. }
  15386. if (texture.samples === samples) {
  15387. return samples;
  15388. }
  15389. var gl = this._gl;
  15390. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15391. // Dispose previous render buffers
  15392. if (texture._depthStencilBuffer) {
  15393. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15394. texture._depthStencilBuffer = null;
  15395. }
  15396. if (texture._MSAAFramebuffer) {
  15397. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15398. texture._MSAAFramebuffer = null;
  15399. }
  15400. if (texture._MSAARenderBuffer) {
  15401. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15402. texture._MSAARenderBuffer = null;
  15403. }
  15404. if (samples > 1) {
  15405. var framebuffer = gl.createFramebuffer();
  15406. if (!framebuffer) {
  15407. throw new Error("Unable to create multi sampled framebuffer");
  15408. }
  15409. texture._MSAAFramebuffer = framebuffer;
  15410. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15411. var colorRenderbuffer = gl.createRenderbuffer();
  15412. if (!colorRenderbuffer) {
  15413. throw new Error("Unable to create multi sampled framebuffer");
  15414. }
  15415. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15416. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15417. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15418. texture._MSAARenderBuffer = colorRenderbuffer;
  15419. }
  15420. else {
  15421. this.bindUnboundFramebuffer(texture._framebuffer);
  15422. }
  15423. texture.samples = samples;
  15424. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15425. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15426. this.bindUnboundFramebuffer(null);
  15427. return samples;
  15428. };
  15429. /**
  15430. * Update the sample count for a given multiple render target texture
  15431. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15432. * @param textures defines the textures to update
  15433. * @param samples defines the sample count to set
  15434. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15435. */
  15436. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15437. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15438. return 1;
  15439. }
  15440. if (textures[0].samples === samples) {
  15441. return samples;
  15442. }
  15443. var gl = this._gl;
  15444. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15445. // Dispose previous render buffers
  15446. if (textures[0]._depthStencilBuffer) {
  15447. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15448. textures[0]._depthStencilBuffer = null;
  15449. }
  15450. if (textures[0]._MSAAFramebuffer) {
  15451. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15452. textures[0]._MSAAFramebuffer = null;
  15453. }
  15454. for (var i = 0; i < textures.length; i++) {
  15455. if (textures[i]._MSAARenderBuffer) {
  15456. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15457. textures[i]._MSAARenderBuffer = null;
  15458. }
  15459. }
  15460. if (samples > 1) {
  15461. var framebuffer = gl.createFramebuffer();
  15462. if (!framebuffer) {
  15463. throw new Error("Unable to create multi sampled framebuffer");
  15464. }
  15465. this.bindUnboundFramebuffer(framebuffer);
  15466. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15467. var attachments = [];
  15468. for (var i = 0; i < textures.length; i++) {
  15469. var texture = textures[i];
  15470. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15471. var colorRenderbuffer = gl.createRenderbuffer();
  15472. if (!colorRenderbuffer) {
  15473. throw new Error("Unable to create multi sampled framebuffer");
  15474. }
  15475. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15476. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15477. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15478. texture._MSAAFramebuffer = framebuffer;
  15479. texture._MSAARenderBuffer = colorRenderbuffer;
  15480. texture.samples = samples;
  15481. texture._depthStencilBuffer = depthStencilBuffer;
  15482. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15483. attachments.push(attachment);
  15484. }
  15485. gl.drawBuffers(attachments);
  15486. }
  15487. else {
  15488. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15489. }
  15490. this.bindUnboundFramebuffer(null);
  15491. return samples;
  15492. };
  15493. /** @hidden */
  15494. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15495. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15496. };
  15497. /** @hidden */
  15498. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15499. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15500. };
  15501. /**
  15502. * Creates a new render target cube texture
  15503. * @param size defines the size of the texture
  15504. * @param options defines the options used to create the texture
  15505. * @returns a new render target cube texture stored in an InternalTexture
  15506. */
  15507. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15508. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15509. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15510. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15511. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15512. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15513. }
  15514. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15515. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15516. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15517. }
  15518. var gl = this._gl;
  15519. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15520. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15521. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15522. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15523. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15524. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15525. }
  15526. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15527. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15528. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15529. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15530. for (var face = 0; face < 6; face++) {
  15531. 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);
  15532. }
  15533. // Create the framebuffer
  15534. var framebuffer = gl.createFramebuffer();
  15535. this.bindUnboundFramebuffer(framebuffer);
  15536. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15537. // MipMaps
  15538. if (fullOptions.generateMipMaps) {
  15539. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15540. }
  15541. // Unbind
  15542. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15543. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15544. this.bindUnboundFramebuffer(null);
  15545. texture._framebuffer = framebuffer;
  15546. texture.width = size;
  15547. texture.height = size;
  15548. texture.isReady = true;
  15549. texture.isCube = true;
  15550. texture.samples = 1;
  15551. texture.generateMipMaps = fullOptions.generateMipMaps;
  15552. texture.samplingMode = fullOptions.samplingMode;
  15553. texture.type = fullOptions.type;
  15554. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15555. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15556. this._internalTexturesCache.push(texture);
  15557. return texture;
  15558. };
  15559. /**
  15560. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15561. * @param rootUrl defines the url where the file to load is located
  15562. * @param scene defines the current scene
  15563. * @param scale defines scale to apply to the mip map selection
  15564. * @param offset defines offset to apply to the mip map selection
  15565. * @param onLoad defines an optional callback raised when the texture is loaded
  15566. * @param onError defines an optional callback raised if there is an issue to load the texture
  15567. * @param format defines the format of the data
  15568. * @param forcedExtension defines the extension to use to pick the right loader
  15569. * @returns the cube texture as an InternalTexture
  15570. */
  15571. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, scale, offset, onLoad, onError, format, forcedExtension) {
  15572. var _this = this;
  15573. if (onLoad === void 0) { onLoad = null; }
  15574. if (onError === void 0) { onError = null; }
  15575. if (forcedExtension === void 0) { forcedExtension = null; }
  15576. var callback = function (loadData) {
  15577. if (!loadData) {
  15578. if (onLoad) {
  15579. onLoad(null);
  15580. }
  15581. return;
  15582. }
  15583. var texture = loadData.texture;
  15584. if (loadData.info.sphericalPolynomial) {
  15585. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15586. }
  15587. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15588. texture._lodGenerationScale = scale;
  15589. texture._lodGenerationOffset = offset;
  15590. if (_this._caps.textureLOD) {
  15591. // Do not add extra process if texture lod is supported.
  15592. if (onLoad) {
  15593. onLoad(texture);
  15594. }
  15595. return;
  15596. }
  15597. var mipSlices = 3;
  15598. var gl = _this._gl;
  15599. var width = loadData.width;
  15600. if (!width) {
  15601. return;
  15602. }
  15603. var textures = [];
  15604. for (var i = 0; i < mipSlices; i++) {
  15605. //compute LOD from even spacing in smoothness (matching shader calculation)
  15606. var smoothness = i / (mipSlices - 1);
  15607. var roughness = 1 - smoothness;
  15608. var minLODIndex = offset; // roughness = 0
  15609. var maxLODIndex = BABYLON.Scalar.Log2(width) * scale + offset; // roughness = 1
  15610. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15611. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15612. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15613. glTextureFromLod.isCube = true;
  15614. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15615. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15616. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15617. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15618. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15619. if (loadData.isDDS) {
  15620. var info = loadData.info;
  15621. var data = loadData.data;
  15622. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15623. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15624. }
  15625. else {
  15626. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15627. }
  15628. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15629. // Wrap in a base texture for easy binding.
  15630. var lodTexture = new BABYLON.BaseTexture(scene);
  15631. lodTexture.isCube = true;
  15632. lodTexture._texture = glTextureFromLod;
  15633. glTextureFromLod.isReady = true;
  15634. textures.push(lodTexture);
  15635. }
  15636. texture._lodTextureHigh = textures[2];
  15637. texture._lodTextureMid = textures[1];
  15638. texture._lodTextureLow = textures[0];
  15639. if (onLoad) {
  15640. onLoad(texture);
  15641. }
  15642. };
  15643. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, true);
  15644. };
  15645. /**
  15646. * Creates a cube texture
  15647. * @param rootUrl defines the url where the files to load is located
  15648. * @param scene defines the current scene
  15649. * @param files defines the list of files to load (1 per face)
  15650. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15651. * @param onLoad defines an optional callback raised when the texture is loaded
  15652. * @param onError defines an optional callback raised if there is an issue to load the texture
  15653. * @param format defines the format of the data
  15654. * @param forcedExtension defines the extension to use to pick the right loader
  15655. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15656. * @returns the cube texture as an InternalTexture
  15657. */
  15658. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials) {
  15659. var _this = this;
  15660. if (onLoad === void 0) { onLoad = null; }
  15661. if (onError === void 0) { onError = null; }
  15662. if (forcedExtension === void 0) { forcedExtension = null; }
  15663. if (createPolynomials === void 0) { createPolynomials = false; }
  15664. var gl = this._gl;
  15665. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15666. texture.isCube = true;
  15667. texture.url = rootUrl;
  15668. texture.generateMipMaps = !noMipmap;
  15669. if (!this._doNotHandleContextLost) {
  15670. texture._extension = forcedExtension;
  15671. texture._files = files;
  15672. }
  15673. var isKTX = false;
  15674. var isDDS = false;
  15675. var lastDot = rootUrl.lastIndexOf('.');
  15676. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15677. if (this._textureFormatInUse) {
  15678. extension = this._textureFormatInUse;
  15679. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15680. isKTX = true;
  15681. }
  15682. else {
  15683. isDDS = (extension === ".dds");
  15684. }
  15685. var onerror = function (request, exception) {
  15686. if (onError && request) {
  15687. onError(request.status + " " + request.statusText, exception);
  15688. }
  15689. };
  15690. if (isKTX) {
  15691. this._loadFile(rootUrl, function (data) {
  15692. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15693. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15694. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15695. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 1);
  15696. ktx.uploadLevels(_this._gl, !noMipmap);
  15697. _this.setCubeMapTextureParams(gl, loadMipmap);
  15698. texture.width = ktx.pixelWidth;
  15699. texture.height = ktx.pixelHeight;
  15700. texture.isReady = true;
  15701. }, undefined, undefined, true, onerror);
  15702. }
  15703. else if (isDDS) {
  15704. if (files && files.length === 6) {
  15705. this._cascadeLoadFiles(scene, function (imgs) {
  15706. var info;
  15707. var loadMipmap = false;
  15708. var width = 0;
  15709. for (var index = 0; index < imgs.length; index++) {
  15710. var data = imgs[index];
  15711. info = BABYLON.DDSTools.GetDDSInfo(data);
  15712. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15713. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15714. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15715. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  15716. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15717. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15718. }
  15719. texture.width = info.width;
  15720. texture.height = info.height;
  15721. texture.type = info.textureType;
  15722. width = info.width;
  15723. }
  15724. _this.setCubeMapTextureParams(gl, loadMipmap);
  15725. texture.isReady = true;
  15726. if (onLoad) {
  15727. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  15728. }
  15729. }, files, onError);
  15730. }
  15731. else {
  15732. this._loadFile(rootUrl, function (data) {
  15733. var info = BABYLON.DDSTools.GetDDSInfo(data);
  15734. if (createPolynomials) {
  15735. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15736. }
  15737. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  15738. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15739. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, info.isCompressed ? 1 : 0);
  15740. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  15741. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  15742. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15743. }
  15744. _this.setCubeMapTextureParams(gl, loadMipmap);
  15745. texture.width = info.width;
  15746. texture.height = info.height;
  15747. texture.isReady = true;
  15748. texture.type = info.textureType;
  15749. if (onLoad) {
  15750. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  15751. }
  15752. }, undefined, undefined, true, onerror);
  15753. }
  15754. }
  15755. else {
  15756. if (!files) {
  15757. throw new Error("Cannot load cubemap because files were not defined");
  15758. }
  15759. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  15760. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  15761. var height = width;
  15762. _this._prepareWorkingCanvas();
  15763. if (!_this._workingCanvas || !_this._workingContext) {
  15764. return;
  15765. }
  15766. _this._workingCanvas.width = width;
  15767. _this._workingCanvas.height = height;
  15768. var faces = [
  15769. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  15770. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  15771. ];
  15772. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15773. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15774. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  15775. for (var index = 0; index < faces.length; index++) {
  15776. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  15777. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  15778. }
  15779. if (!noMipmap) {
  15780. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15781. }
  15782. _this.setCubeMapTextureParams(gl, !noMipmap);
  15783. texture.width = width;
  15784. texture.height = height;
  15785. texture.isReady = true;
  15786. if (format) {
  15787. texture.format = format;
  15788. }
  15789. texture.onLoadedObservable.notifyObservers(texture);
  15790. texture.onLoadedObservable.clear();
  15791. if (onLoad) {
  15792. onLoad();
  15793. }
  15794. }, files, onError);
  15795. }
  15796. this._internalTexturesCache.push(texture);
  15797. return texture;
  15798. };
  15799. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  15800. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15801. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  15802. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15803. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15804. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15805. // this.resetTextureCache();
  15806. };
  15807. /**
  15808. * Update a raw cube texture
  15809. * @param texture defines the texture to udpdate
  15810. * @param data defines the data to store
  15811. * @param format defines the data format
  15812. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15813. * @param invertY defines if data must be stored with Y axis inverted
  15814. * @param compression defines the compression used (null by default)
  15815. * @param level defines which level of the texture to update
  15816. */
  15817. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  15818. if (compression === void 0) { compression = null; }
  15819. if (level === void 0) { level = 0; }
  15820. texture._bufferViewArray = data;
  15821. texture.format = format;
  15822. texture.type = type;
  15823. texture.invertY = invertY;
  15824. texture._compression = compression;
  15825. var gl = this._gl;
  15826. var textureType = this._getWebGLTextureType(type);
  15827. var internalFormat = this._getInternalFormat(format);
  15828. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  15829. var needConversion = false;
  15830. if (internalFormat === gl.RGB) {
  15831. internalFormat = gl.RGBA;
  15832. needConversion = true;
  15833. }
  15834. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15835. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  15836. if (texture.width % 4 !== 0) {
  15837. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  15838. }
  15839. // Data are known to be in +X +Y +Z -X -Y -Z
  15840. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15841. var faceData = data[faceIndex];
  15842. if (compression) {
  15843. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  15844. }
  15845. else {
  15846. if (needConversion) {
  15847. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  15848. }
  15849. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  15850. }
  15851. }
  15852. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15853. if (isPot && texture.generateMipMaps && level === 0) {
  15854. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15855. }
  15856. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15857. // this.resetTextureCache();
  15858. texture.isReady = true;
  15859. };
  15860. /**
  15861. * Creates a new raw cube texture
  15862. * @param data defines the array of data to use to create each face
  15863. * @param size defines the size of the textures
  15864. * @param format defines the format of the data
  15865. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15866. * @param generateMipMaps defines if the engine should generate the mip levels
  15867. * @param invertY defines if data must be stored with Y axis inverted
  15868. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15869. * @param compression defines the compression used (null by default)
  15870. * @returns the cube texture as an InternalTexture
  15871. */
  15872. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  15873. if (compression === void 0) { compression = null; }
  15874. var gl = this._gl;
  15875. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  15876. texture.isCube = true;
  15877. texture.generateMipMaps = generateMipMaps;
  15878. texture.format = format;
  15879. texture.type = type;
  15880. if (!this._doNotHandleContextLost) {
  15881. texture._bufferViewArray = data;
  15882. }
  15883. var textureType = this._getWebGLTextureType(type);
  15884. var internalFormat = this._getInternalFormat(format);
  15885. if (internalFormat === gl.RGB) {
  15886. internalFormat = gl.RGBA;
  15887. }
  15888. var width = size;
  15889. var height = width;
  15890. texture.width = width;
  15891. texture.height = height;
  15892. // Double check on POT to generate Mips.
  15893. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  15894. if (!isPot) {
  15895. generateMipMaps = false;
  15896. }
  15897. // Upload data if needed. The texture won't be ready until then.
  15898. if (data) {
  15899. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  15900. }
  15901. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15902. // Filters
  15903. if (data && generateMipMaps) {
  15904. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  15905. }
  15906. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  15907. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15908. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15909. }
  15910. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  15911. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15912. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15913. }
  15914. else {
  15915. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15916. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15917. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15918. }
  15919. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15920. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15921. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15922. return texture;
  15923. };
  15924. /**
  15925. * Creates a new raw cube texture from a specified url
  15926. * @param url defines the url where the data is located
  15927. * @param scene defines the current scene
  15928. * @param size defines the size of the textures
  15929. * @param format defines the format of the data
  15930. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  15931. * @param noMipmap defines if the engine should avoid generating the mip levels
  15932. * @param callback defines a callback used to extract texture data from loaded data
  15933. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  15934. * @param onLoad defines a callback called when texture is loaded
  15935. * @param onError defines a callback called if there is an error
  15936. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  15937. * @param invertY defines if data must be stored with Y axis inverted
  15938. * @returns the cube texture as an InternalTexture
  15939. */
  15940. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  15941. var _this = this;
  15942. if (onLoad === void 0) { onLoad = null; }
  15943. if (onError === void 0) { onError = null; }
  15944. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  15945. if (invertY === void 0) { invertY = false; }
  15946. var gl = this._gl;
  15947. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  15948. scene._addPendingData(texture);
  15949. texture.url = url;
  15950. this._internalTexturesCache.push(texture);
  15951. var onerror = function (request, exception) {
  15952. scene._removePendingData(texture);
  15953. if (onError && request) {
  15954. onError(request.status + " " + request.statusText, exception);
  15955. }
  15956. };
  15957. var internalCallback = function (data) {
  15958. var width = texture.width;
  15959. var faceDataArrays = callback(data);
  15960. if (!faceDataArrays) {
  15961. return;
  15962. }
  15963. if (mipmapGenerator) {
  15964. var textureType = _this._getWebGLTextureType(type);
  15965. var internalFormat = _this._getInternalFormat(format);
  15966. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  15967. var needConversion = false;
  15968. if (internalFormat === gl.RGB) {
  15969. internalFormat = gl.RGBA;
  15970. needConversion = true;
  15971. }
  15972. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15973. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  15974. var mipData = mipmapGenerator(faceDataArrays);
  15975. for (var level = 0; level < mipData.length; level++) {
  15976. var mipSize = width >> level;
  15977. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  15978. var mipFaceData = mipData[level][faceIndex];
  15979. if (needConversion) {
  15980. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  15981. }
  15982. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  15983. }
  15984. }
  15985. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15986. }
  15987. else {
  15988. texture.generateMipMaps = !noMipmap;
  15989. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  15990. }
  15991. texture.isReady = true;
  15992. // this.resetTextureCache();
  15993. scene._removePendingData(texture);
  15994. if (onLoad) {
  15995. onLoad();
  15996. }
  15997. };
  15998. this._loadFile(url, function (data) {
  15999. internalCallback(data);
  16000. }, undefined, scene.database, true, onerror);
  16001. return texture;
  16002. };
  16003. ;
  16004. /**
  16005. * Update a raw 3D texture
  16006. * @param texture defines the texture to update
  16007. * @param data defines the data to store
  16008. * @param format defines the data format
  16009. * @param invertY defines if data must be stored with Y axis inverted
  16010. * @param compression defines the used compression (can be null)
  16011. */
  16012. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression) {
  16013. if (compression === void 0) { compression = null; }
  16014. var internalFormat = this._getInternalFormat(format);
  16015. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16016. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16017. if (!this._doNotHandleContextLost) {
  16018. texture._bufferView = data;
  16019. texture.format = format;
  16020. texture.invertY = invertY;
  16021. texture._compression = compression;
  16022. }
  16023. if (texture.width % 4 !== 0) {
  16024. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16025. }
  16026. if (compression && data) {
  16027. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16028. }
  16029. else {
  16030. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalFormat, texture.width, texture.height, texture.depth, 0, internalFormat, this._gl.UNSIGNED_BYTE, data);
  16031. }
  16032. if (texture.generateMipMaps) {
  16033. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16034. }
  16035. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16036. // this.resetTextureCache();
  16037. texture.isReady = true;
  16038. };
  16039. /**
  16040. * Creates a new raw 3D texture
  16041. * @param data defines the data used to create the texture
  16042. * @param width defines the width of the texture
  16043. * @param height defines the height of the texture
  16044. * @param depth defines the depth of the texture
  16045. * @param format defines the format of the texture
  16046. * @param generateMipMaps defines if the engine must generate mip levels
  16047. * @param invertY defines if data must be stored with Y axis inverted
  16048. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16049. * @param compression defines the compressed used (can be null)
  16050. * @returns a new raw 3D texture (stored in an InternalTexture)
  16051. */
  16052. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression) {
  16053. if (compression === void 0) { compression = null; }
  16054. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16055. texture.baseWidth = width;
  16056. texture.baseHeight = height;
  16057. texture.baseDepth = depth;
  16058. texture.width = width;
  16059. texture.height = height;
  16060. texture.depth = depth;
  16061. texture.format = format;
  16062. texture.generateMipMaps = generateMipMaps;
  16063. texture.samplingMode = samplingMode;
  16064. texture.is3D = true;
  16065. if (!this._doNotHandleContextLost) {
  16066. texture._bufferView = data;
  16067. }
  16068. this.updateRawTexture3D(texture, data, format, invertY, compression);
  16069. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16070. // Filters
  16071. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16072. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16073. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16074. if (generateMipMaps) {
  16075. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16076. }
  16077. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16078. this._internalTexturesCache.push(texture);
  16079. return texture;
  16080. };
  16081. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16082. var gl = this._gl;
  16083. if (!gl) {
  16084. return;
  16085. }
  16086. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16087. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16088. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16089. if (!noMipmap && !isCompressed) {
  16090. gl.generateMipmap(gl.TEXTURE_2D);
  16091. }
  16092. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16093. // this.resetTextureCache();
  16094. if (scene) {
  16095. scene._removePendingData(texture);
  16096. }
  16097. texture.onLoadedObservable.notifyObservers(texture);
  16098. texture.onLoadedObservable.clear();
  16099. };
  16100. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16101. var _this = this;
  16102. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16103. var potWidth = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this.getCaps().maxTextureSize) : width;
  16104. var potHeight = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this.getCaps().maxTextureSize) : height;
  16105. var gl = this._gl;
  16106. if (!gl) {
  16107. return;
  16108. }
  16109. if (!texture._webGLTexture) {
  16110. // this.resetTextureCache();
  16111. if (scene) {
  16112. scene._removePendingData(texture);
  16113. }
  16114. return;
  16115. }
  16116. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16117. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, invertY === undefined ? 1 : (invertY ? 1 : 0));
  16118. texture.baseWidth = width;
  16119. texture.baseHeight = height;
  16120. texture.width = potWidth;
  16121. texture.height = potHeight;
  16122. texture.isReady = true;
  16123. if (processFunction(potWidth, potHeight, function () {
  16124. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16125. })) {
  16126. // Returning as texture needs extra async steps
  16127. return;
  16128. }
  16129. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16130. };
  16131. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16132. // Create new RGBA data container.
  16133. var rgbaData;
  16134. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16135. rgbaData = new Float32Array(width * height * 4);
  16136. }
  16137. else {
  16138. rgbaData = new Uint32Array(width * height * 4);
  16139. }
  16140. // Convert each pixel.
  16141. for (var x = 0; x < width; x++) {
  16142. for (var y = 0; y < height; y++) {
  16143. var index = (y * width + x) * 3;
  16144. var newIndex = (y * width + x) * 4;
  16145. // Map Old Value to new value.
  16146. rgbaData[newIndex + 0] = rgbData[index + 0];
  16147. rgbaData[newIndex + 1] = rgbData[index + 1];
  16148. rgbaData[newIndex + 2] = rgbData[index + 2];
  16149. // Add fully opaque alpha channel.
  16150. rgbaData[newIndex + 3] = 1;
  16151. }
  16152. }
  16153. return rgbaData;
  16154. };
  16155. /** @hidden */
  16156. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16157. var gl = this._gl;
  16158. if (texture._framebuffer) {
  16159. gl.deleteFramebuffer(texture._framebuffer);
  16160. texture._framebuffer = null;
  16161. }
  16162. if (texture._depthStencilBuffer) {
  16163. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16164. texture._depthStencilBuffer = null;
  16165. }
  16166. if (texture._MSAAFramebuffer) {
  16167. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16168. texture._MSAAFramebuffer = null;
  16169. }
  16170. if (texture._MSAARenderBuffer) {
  16171. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16172. texture._MSAARenderBuffer = null;
  16173. }
  16174. };
  16175. /** @hidden */
  16176. Engine.prototype._releaseTexture = function (texture) {
  16177. var gl = this._gl;
  16178. this._releaseFramebufferObjects(texture);
  16179. gl.deleteTexture(texture._webGLTexture);
  16180. // Unbind channels
  16181. this.unbindAllTextures();
  16182. var index = this._internalTexturesCache.indexOf(texture);
  16183. if (index !== -1) {
  16184. this._internalTexturesCache.splice(index, 1);
  16185. }
  16186. // Integrated fixed lod samplers.
  16187. if (texture._lodTextureHigh) {
  16188. texture._lodTextureHigh.dispose();
  16189. }
  16190. if (texture._lodTextureMid) {
  16191. texture._lodTextureMid.dispose();
  16192. }
  16193. if (texture._lodTextureLow) {
  16194. texture._lodTextureLow.dispose();
  16195. }
  16196. // Set output texture of post process to null if the texture has been released/disposed
  16197. this.scenes.forEach(function (scene) {
  16198. scene.postProcesses.forEach(function (postProcess) {
  16199. if (postProcess._outputTexture == texture) {
  16200. postProcess._outputTexture = null;
  16201. }
  16202. });
  16203. scene.cameras.forEach(function (camera) {
  16204. camera._postProcesses.forEach(function (postProcess) {
  16205. if (postProcess) {
  16206. if (postProcess._outputTexture == texture) {
  16207. postProcess._outputTexture = null;
  16208. }
  16209. }
  16210. });
  16211. });
  16212. });
  16213. };
  16214. Engine.prototype.setProgram = function (program) {
  16215. if (this._currentProgram !== program) {
  16216. this._gl.useProgram(program);
  16217. this._currentProgram = program;
  16218. }
  16219. };
  16220. /**
  16221. * Binds an effect to the webGL context
  16222. * @param effect defines the effect to bind
  16223. */
  16224. Engine.prototype.bindSamplers = function (effect) {
  16225. this.setProgram(effect.getProgram());
  16226. var samplers = effect.getSamplers();
  16227. for (var index = 0; index < samplers.length; index++) {
  16228. var uniform = effect.getUniform(samplers[index]);
  16229. if (uniform) {
  16230. this._boundUniforms[index] = uniform;
  16231. }
  16232. }
  16233. this._currentEffect = null;
  16234. };
  16235. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16236. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16237. return;
  16238. }
  16239. // Remove
  16240. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16241. // Bind last to it
  16242. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16243. // Bind to dummy
  16244. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16245. };
  16246. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16247. if (!internalTexture) {
  16248. return -1;
  16249. }
  16250. internalTexture._initialSlot = channel;
  16251. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16252. if (channel !== internalTexture._designatedSlot) {
  16253. this._textureCollisions.addCount(1, false);
  16254. }
  16255. }
  16256. else {
  16257. if (channel !== internalTexture._designatedSlot) {
  16258. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16259. return internalTexture._designatedSlot;
  16260. }
  16261. else {
  16262. // No slot for this texture, let's pick a new one (if we find a free slot)
  16263. if (this._nextFreeTextureSlots.length) {
  16264. return this._nextFreeTextureSlots[0];
  16265. }
  16266. // We need to recycle the oldest bound texture, sorry.
  16267. this._textureCollisions.addCount(1, false);
  16268. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16269. }
  16270. }
  16271. }
  16272. return channel;
  16273. };
  16274. Engine.prototype._linkTrackers = function (previous, next) {
  16275. previous.next = next;
  16276. next.previous = previous;
  16277. };
  16278. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16279. var currentSlot = internalTexture._designatedSlot;
  16280. if (currentSlot === -1) {
  16281. return -1;
  16282. }
  16283. internalTexture._designatedSlot = -1;
  16284. if (this.disableTextureBindingOptimization) {
  16285. return -1;
  16286. }
  16287. // Remove from bound list
  16288. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16289. // Free the slot
  16290. this._boundTexturesCache[currentSlot] = null;
  16291. this._nextFreeTextureSlots.push(currentSlot);
  16292. return currentSlot;
  16293. };
  16294. Engine.prototype._activateCurrentTexture = function () {
  16295. if (this._currentTextureChannel !== this._activeChannel) {
  16296. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16297. this._currentTextureChannel = this._activeChannel;
  16298. }
  16299. };
  16300. /** @hidden */
  16301. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16302. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16303. if (force === void 0) { force = false; }
  16304. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16305. this._activeChannel = texture._designatedSlot;
  16306. }
  16307. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16308. var isTextureForRendering = texture && texture._initialSlot > -1;
  16309. if (currentTextureBound !== texture || force) {
  16310. if (currentTextureBound) {
  16311. this._removeDesignatedSlot(currentTextureBound);
  16312. }
  16313. this._activateCurrentTexture();
  16314. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16315. this._boundTexturesCache[this._activeChannel] = texture;
  16316. if (texture) {
  16317. if (!this.disableTextureBindingOptimization) {
  16318. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16319. if (slotIndex > -1) {
  16320. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16321. }
  16322. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16323. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16324. }
  16325. texture._designatedSlot = this._activeChannel;
  16326. }
  16327. }
  16328. else if (forTextureDataUpdate) {
  16329. this._activateCurrentTexture();
  16330. }
  16331. if (isTextureForRendering && !forTextureDataUpdate) {
  16332. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16333. }
  16334. };
  16335. /** @hidden */
  16336. Engine.prototype._bindTexture = function (channel, texture) {
  16337. if (channel < 0) {
  16338. return;
  16339. }
  16340. if (texture) {
  16341. channel = this._getCorrectTextureChannel(channel, texture);
  16342. }
  16343. this._activeChannel = channel;
  16344. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16345. };
  16346. /**
  16347. * Sets a texture to the webGL context from a postprocess
  16348. * @param channel defines the channel to use
  16349. * @param postProcess defines the source postprocess
  16350. */
  16351. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16352. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16353. };
  16354. /**
  16355. * Binds the output of the passed in post process to the texture channel specified
  16356. * @param channel The channel the texture should be bound to
  16357. * @param postProcess The post process which's output should be bound
  16358. */
  16359. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16360. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16361. };
  16362. /**
  16363. * Unbind all textures from the webGL context
  16364. */
  16365. Engine.prototype.unbindAllTextures = function () {
  16366. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16367. this._activeChannel = channel;
  16368. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16369. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16370. if (this.webGLVersion > 1) {
  16371. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16372. }
  16373. }
  16374. };
  16375. /**
  16376. * Sets a texture to the according uniform.
  16377. * @param channel The texture channel
  16378. * @param uniform The uniform to set
  16379. * @param texture The texture to apply
  16380. */
  16381. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16382. if (channel < 0) {
  16383. return;
  16384. }
  16385. if (uniform) {
  16386. this._boundUniforms[channel] = uniform;
  16387. }
  16388. this._setTexture(channel, texture);
  16389. };
  16390. /**
  16391. * Sets a depth stencil texture from a render target to the according uniform.
  16392. * @param channel The texture channel
  16393. * @param uniform The uniform to set
  16394. * @param texture The render target texture containing the depth stencil texture to apply
  16395. */
  16396. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16397. if (channel < 0) {
  16398. return;
  16399. }
  16400. if (uniform) {
  16401. this._boundUniforms[channel] = uniform;
  16402. }
  16403. if (!texture || !texture.depthStencilTexture) {
  16404. this._setTexture(channel, null);
  16405. }
  16406. else {
  16407. this._setTexture(channel, texture, false, true);
  16408. }
  16409. };
  16410. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16411. var uniform = this._boundUniforms[sourceSlot];
  16412. if (uniform._currentState === destination) {
  16413. return;
  16414. }
  16415. this._gl.uniform1i(uniform, destination);
  16416. uniform._currentState = destination;
  16417. };
  16418. Engine.prototype._getTextureWrapMode = function (mode) {
  16419. switch (mode) {
  16420. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16421. return this._gl.REPEAT;
  16422. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16423. return this._gl.CLAMP_TO_EDGE;
  16424. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16425. return this._gl.MIRRORED_REPEAT;
  16426. }
  16427. return this._gl.REPEAT;
  16428. };
  16429. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16430. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16431. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16432. // Not ready?
  16433. if (!texture) {
  16434. if (this._boundTexturesCache[channel] != null) {
  16435. this._activeChannel = channel;
  16436. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16437. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16438. if (this.webGLVersion > 1) {
  16439. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16440. }
  16441. }
  16442. return false;
  16443. }
  16444. // Video
  16445. if (texture.video) {
  16446. this._activeChannel = channel;
  16447. texture.update();
  16448. }
  16449. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16450. texture.delayLoad();
  16451. return false;
  16452. }
  16453. var internalTexture;
  16454. if (depthStencilTexture) {
  16455. internalTexture = texture.depthStencilTexture;
  16456. }
  16457. else if (texture.isReady()) {
  16458. internalTexture = texture.getInternalTexture();
  16459. }
  16460. else if (texture.isCube) {
  16461. internalTexture = this.emptyCubeTexture;
  16462. }
  16463. else if (texture.is3D) {
  16464. internalTexture = this.emptyTexture3D;
  16465. }
  16466. else {
  16467. internalTexture = this.emptyTexture;
  16468. }
  16469. if (!isPartOfTextureArray) {
  16470. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16471. }
  16472. var needToBind = true;
  16473. if (this._boundTexturesCache[channel] === internalTexture) {
  16474. this._moveBoundTextureOnTop(internalTexture);
  16475. if (!isPartOfTextureArray) {
  16476. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16477. }
  16478. needToBind = false;
  16479. }
  16480. this._activeChannel = channel;
  16481. if (internalTexture && internalTexture.is3D) {
  16482. if (needToBind) {
  16483. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16484. }
  16485. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16486. internalTexture._cachedWrapU = texture.wrapU;
  16487. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16488. }
  16489. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16490. internalTexture._cachedWrapV = texture.wrapV;
  16491. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16492. }
  16493. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16494. internalTexture._cachedWrapR = texture.wrapR;
  16495. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16496. }
  16497. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16498. }
  16499. else if (internalTexture && internalTexture.isCube) {
  16500. if (needToBind) {
  16501. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16502. }
  16503. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16504. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16505. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16506. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16507. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16508. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16509. }
  16510. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16511. }
  16512. else {
  16513. if (needToBind) {
  16514. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16515. }
  16516. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16517. internalTexture._cachedWrapU = texture.wrapU;
  16518. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16519. }
  16520. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16521. internalTexture._cachedWrapV = texture.wrapV;
  16522. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16523. }
  16524. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16525. }
  16526. return true;
  16527. };
  16528. /**
  16529. * Sets an array of texture to the webGL context
  16530. * @param channel defines the channel where the texture array must be set
  16531. * @param uniform defines the associated uniform location
  16532. * @param textures defines the array of textures to bind
  16533. */
  16534. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16535. if (channel < 0 || !uniform) {
  16536. return;
  16537. }
  16538. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16539. this._textureUnits = new Int32Array(textures.length);
  16540. }
  16541. for (var i = 0; i < textures.length; i++) {
  16542. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16543. }
  16544. this._gl.uniform1iv(uniform, this._textureUnits);
  16545. for (var index = 0; index < textures.length; index++) {
  16546. this._setTexture(this._textureUnits[index], textures[index], true);
  16547. }
  16548. };
  16549. /** @hidden */
  16550. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16551. var internalTexture = texture.getInternalTexture();
  16552. if (!internalTexture) {
  16553. return;
  16554. }
  16555. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16556. var value = texture.anisotropicFilteringLevel;
  16557. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16558. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16559. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16560. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16561. }
  16562. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16563. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16564. internalTexture._cachedAnisotropicFilteringLevel = value;
  16565. }
  16566. };
  16567. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16568. this._bindTextureDirectly(target, texture, true, true);
  16569. this._gl.texParameterf(target, parameter, value);
  16570. };
  16571. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16572. if (texture) {
  16573. this._bindTextureDirectly(target, texture, true, true);
  16574. }
  16575. this._gl.texParameteri(target, parameter, value);
  16576. };
  16577. /**
  16578. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16579. * @param x defines the x coordinate of the rectangle where pixels must be read
  16580. * @param y defines the y coordinate of the rectangle where pixels must be read
  16581. * @param width defines the width of the rectangle where pixels must be read
  16582. * @param height defines the height of the rectangle where pixels must be read
  16583. * @returns a Uint8Array containing RGBA colors
  16584. */
  16585. Engine.prototype.readPixels = function (x, y, width, height) {
  16586. var data = new Uint8Array(height * width * 4);
  16587. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16588. return data;
  16589. };
  16590. /**
  16591. * Add an externaly attached data from its key.
  16592. * This method call will fail and return false, if such key already exists.
  16593. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16594. * @param key the unique key that identifies the data
  16595. * @param data the data object to associate to the key for this Engine instance
  16596. * @return true if no such key were already present and the data was added successfully, false otherwise
  16597. */
  16598. Engine.prototype.addExternalData = function (key, data) {
  16599. if (!this._externalData) {
  16600. this._externalData = new BABYLON.StringDictionary();
  16601. }
  16602. return this._externalData.add(key, data);
  16603. };
  16604. /**
  16605. * Get an externaly attached data from its key
  16606. * @param key the unique key that identifies the data
  16607. * @return the associated data, if present (can be null), or undefined if not present
  16608. */
  16609. Engine.prototype.getExternalData = function (key) {
  16610. if (!this._externalData) {
  16611. this._externalData = new BABYLON.StringDictionary();
  16612. }
  16613. return this._externalData.get(key);
  16614. };
  16615. /**
  16616. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16617. * @param key the unique key that identifies the data
  16618. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16619. * @return the associated data, can be null if the factory returned null.
  16620. */
  16621. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16622. if (!this._externalData) {
  16623. this._externalData = new BABYLON.StringDictionary();
  16624. }
  16625. return this._externalData.getOrAddWithFactory(key, factory);
  16626. };
  16627. /**
  16628. * Remove an externaly attached data from the Engine instance
  16629. * @param key the unique key that identifies the data
  16630. * @return true if the data was successfully removed, false if it doesn't exist
  16631. */
  16632. Engine.prototype.removeExternalData = function (key) {
  16633. if (!this._externalData) {
  16634. this._externalData = new BABYLON.StringDictionary();
  16635. }
  16636. return this._externalData.remove(key);
  16637. };
  16638. /**
  16639. * Unbind all vertex attributes from the webGL context
  16640. */
  16641. Engine.prototype.unbindAllAttributes = function () {
  16642. if (this._mustWipeVertexAttributes) {
  16643. this._mustWipeVertexAttributes = false;
  16644. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16645. this._gl.disableVertexAttribArray(i);
  16646. this._vertexAttribArraysEnabled[i] = false;
  16647. this._currentBufferPointers[i].active = false;
  16648. }
  16649. return;
  16650. }
  16651. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16652. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16653. continue;
  16654. }
  16655. this._gl.disableVertexAttribArray(i);
  16656. this._vertexAttribArraysEnabled[i] = false;
  16657. this._currentBufferPointers[i].active = false;
  16658. }
  16659. };
  16660. /**
  16661. * 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
  16662. */
  16663. Engine.prototype.releaseEffects = function () {
  16664. for (var name in this._compiledEffects) {
  16665. this._deleteProgram(this._compiledEffects[name]._program);
  16666. }
  16667. this._compiledEffects = {};
  16668. };
  16669. /**
  16670. * Dispose and release all associated resources
  16671. */
  16672. Engine.prototype.dispose = function () {
  16673. this.hideLoadingUI();
  16674. this.stopRenderLoop();
  16675. // Release postProcesses
  16676. while (this.postProcesses.length) {
  16677. this.postProcesses[0].dispose();
  16678. }
  16679. // Empty texture
  16680. if (this._emptyTexture) {
  16681. this._releaseTexture(this._emptyTexture);
  16682. this._emptyTexture = null;
  16683. }
  16684. if (this._emptyCubeTexture) {
  16685. this._releaseTexture(this._emptyCubeTexture);
  16686. this._emptyCubeTexture = null;
  16687. }
  16688. // Rescale PP
  16689. if (this._rescalePostProcess) {
  16690. this._rescalePostProcess.dispose();
  16691. }
  16692. // Release scenes
  16693. while (this.scenes.length) {
  16694. this.scenes[0].dispose();
  16695. }
  16696. // Release audio engine
  16697. if (Engine.audioEngine) {
  16698. Engine.audioEngine.dispose();
  16699. }
  16700. // Release effects
  16701. this.releaseEffects();
  16702. // Unbind
  16703. this.unbindAllAttributes();
  16704. this._boundUniforms = [];
  16705. if (this._dummyFramebuffer) {
  16706. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  16707. }
  16708. //WebVR
  16709. this.disableVR();
  16710. // Events
  16711. if (BABYLON.Tools.IsWindowObjectExist()) {
  16712. window.removeEventListener("blur", this._onBlur);
  16713. window.removeEventListener("focus", this._onFocus);
  16714. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  16715. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  16716. if (this._renderingCanvas) {
  16717. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  16718. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  16719. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  16720. if (!this._doNotHandleContextLost) {
  16721. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  16722. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  16723. }
  16724. }
  16725. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  16726. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  16727. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  16728. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  16729. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  16730. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  16731. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  16732. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  16733. if (this._onVrDisplayConnect) {
  16734. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  16735. if (this._onVrDisplayDisconnect) {
  16736. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  16737. }
  16738. if (this._onVrDisplayPresentChange) {
  16739. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  16740. }
  16741. this._onVrDisplayConnect = null;
  16742. this._onVrDisplayDisconnect = null;
  16743. }
  16744. }
  16745. // Remove from Instances
  16746. var index = Engine.Instances.indexOf(this);
  16747. if (index >= 0) {
  16748. Engine.Instances.splice(index, 1);
  16749. }
  16750. this._workingCanvas = null;
  16751. this._workingContext = null;
  16752. this._currentBufferPointers = [];
  16753. this._renderingCanvas = null;
  16754. this._currentProgram = null;
  16755. this._bindedRenderFunction = null;
  16756. this.onResizeObservable.clear();
  16757. this.onCanvasBlurObservable.clear();
  16758. this.onCanvasFocusObservable.clear();
  16759. this.onCanvasPointerOutObservable.clear();
  16760. this.onBeginFrameObservable.clear();
  16761. this.onEndFrameObservable.clear();
  16762. BABYLON.Effect.ResetCache();
  16763. // Abort active requests
  16764. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  16765. var request = _a[_i];
  16766. request.abort();
  16767. }
  16768. };
  16769. // Loading screen
  16770. /**
  16771. * Display the loading screen
  16772. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16773. */
  16774. Engine.prototype.displayLoadingUI = function () {
  16775. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16776. return;
  16777. }
  16778. var loadingScreen = this.loadingScreen;
  16779. if (loadingScreen) {
  16780. loadingScreen.displayLoadingUI();
  16781. }
  16782. };
  16783. /**
  16784. * Hide the loading screen
  16785. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16786. */
  16787. Engine.prototype.hideLoadingUI = function () {
  16788. if (!BABYLON.Tools.IsWindowObjectExist()) {
  16789. return;
  16790. }
  16791. var loadingScreen = this.loadingScreen;
  16792. if (loadingScreen) {
  16793. loadingScreen.hideLoadingUI();
  16794. }
  16795. };
  16796. Object.defineProperty(Engine.prototype, "loadingScreen", {
  16797. /**
  16798. * Gets the current loading screen object
  16799. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16800. */
  16801. get: function () {
  16802. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  16803. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  16804. return this._loadingScreen;
  16805. },
  16806. /**
  16807. * Sets the current loading screen object
  16808. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16809. */
  16810. set: function (loadingScreen) {
  16811. this._loadingScreen = loadingScreen;
  16812. },
  16813. enumerable: true,
  16814. configurable: true
  16815. });
  16816. Object.defineProperty(Engine.prototype, "loadingUIText", {
  16817. /**
  16818. * Sets the current loading screen text
  16819. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16820. */
  16821. set: function (text) {
  16822. this.loadingScreen.loadingUIText = text;
  16823. },
  16824. enumerable: true,
  16825. configurable: true
  16826. });
  16827. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  16828. /**
  16829. * Sets the current loading screen background color
  16830. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  16831. */
  16832. set: function (color) {
  16833. this.loadingScreen.loadingUIBackgroundColor = color;
  16834. },
  16835. enumerable: true,
  16836. configurable: true
  16837. });
  16838. /**
  16839. * Attach a new callback raised when context lost event is fired
  16840. * @param callback defines the callback to call
  16841. */
  16842. Engine.prototype.attachContextLostEvent = function (callback) {
  16843. if (this._renderingCanvas) {
  16844. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  16845. }
  16846. };
  16847. /**
  16848. * Attach a new callback raised when context restored event is fired
  16849. * @param callback defines the callback to call
  16850. */
  16851. Engine.prototype.attachContextRestoredEvent = function (callback) {
  16852. if (this._renderingCanvas) {
  16853. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  16854. }
  16855. };
  16856. /**
  16857. * Gets the source code of the vertex shader associated with a specific webGL program
  16858. * @param program defines the program to use
  16859. * @returns a string containing the source code of the vertex shader associated with the program
  16860. */
  16861. Engine.prototype.getVertexShaderSource = function (program) {
  16862. var shaders = this._gl.getAttachedShaders(program);
  16863. if (!shaders) {
  16864. return null;
  16865. }
  16866. return this._gl.getShaderSource(shaders[0]);
  16867. };
  16868. /**
  16869. * Gets the source code of the fragment shader associated with a specific webGL program
  16870. * @param program defines the program to use
  16871. * @returns a string containing the source code of the fragment shader associated with the program
  16872. */
  16873. Engine.prototype.getFragmentShaderSource = function (program) {
  16874. var shaders = this._gl.getAttachedShaders(program);
  16875. if (!shaders) {
  16876. return null;
  16877. }
  16878. return this._gl.getShaderSource(shaders[1]);
  16879. };
  16880. /**
  16881. * Get the current error code of the webGL context
  16882. * @returns the error code
  16883. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  16884. */
  16885. Engine.prototype.getError = function () {
  16886. return this._gl.getError();
  16887. };
  16888. // FPS
  16889. /**
  16890. * Gets the current framerate
  16891. * @returns a number representing the framerate
  16892. */
  16893. Engine.prototype.getFps = function () {
  16894. return this._fps;
  16895. };
  16896. /**
  16897. * Gets the time spent between current and previous frame
  16898. * @returns a number representing the delta time in ms
  16899. */
  16900. Engine.prototype.getDeltaTime = function () {
  16901. return this._deltaTime;
  16902. };
  16903. Engine.prototype._measureFps = function () {
  16904. this._performanceMonitor.sampleFrame();
  16905. this._fps = this._performanceMonitor.averageFPS;
  16906. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  16907. };
  16908. /** @hidden */
  16909. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex) {
  16910. if (faceIndex === void 0) { faceIndex = -1; }
  16911. var gl = this._gl;
  16912. if (!this._dummyFramebuffer) {
  16913. var dummy = gl.createFramebuffer();
  16914. if (!dummy) {
  16915. throw new Error("Unable to create dummy framebuffer");
  16916. }
  16917. this._dummyFramebuffer = dummy;
  16918. }
  16919. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  16920. if (faceIndex > -1) {
  16921. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, 0);
  16922. }
  16923. else {
  16924. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  16925. }
  16926. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  16927. var buffer;
  16928. switch (readType) {
  16929. case gl.UNSIGNED_BYTE:
  16930. buffer = new Uint8Array(4 * width * height);
  16931. readType = gl.UNSIGNED_BYTE;
  16932. break;
  16933. default:
  16934. buffer = new Float32Array(4 * width * height);
  16935. readType = gl.FLOAT;
  16936. break;
  16937. }
  16938. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  16939. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  16940. return buffer;
  16941. };
  16942. Engine.prototype._canRenderToFloatFramebuffer = function () {
  16943. if (this._webGLVersion > 1) {
  16944. return this._caps.colorBufferFloat;
  16945. }
  16946. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  16947. };
  16948. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  16949. if (this._webGLVersion > 1) {
  16950. return this._caps.colorBufferFloat;
  16951. }
  16952. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  16953. };
  16954. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  16955. Engine.prototype._canRenderToFramebuffer = function (type) {
  16956. var gl = this._gl;
  16957. //clear existing errors
  16958. while (gl.getError() !== gl.NO_ERROR) { }
  16959. var successful = true;
  16960. var texture = gl.createTexture();
  16961. gl.bindTexture(gl.TEXTURE_2D, texture);
  16962. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  16963. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16964. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16965. var fb = gl.createFramebuffer();
  16966. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  16967. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  16968. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  16969. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  16970. successful = successful && (gl.getError() === gl.NO_ERROR);
  16971. //try render by clearing frame buffer's color buffer
  16972. if (successful) {
  16973. gl.clear(gl.COLOR_BUFFER_BIT);
  16974. successful = successful && (gl.getError() === gl.NO_ERROR);
  16975. }
  16976. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  16977. if (successful) {
  16978. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  16979. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16980. var readFormat = gl.RGBA;
  16981. var readType = gl.UNSIGNED_BYTE;
  16982. var buffer = new Uint8Array(4);
  16983. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  16984. successful = successful && (gl.getError() === gl.NO_ERROR);
  16985. }
  16986. //clean up
  16987. gl.deleteTexture(texture);
  16988. gl.deleteFramebuffer(fb);
  16989. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  16990. //clear accumulated errors
  16991. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  16992. return successful;
  16993. };
  16994. /** @hidden */
  16995. Engine.prototype._getWebGLTextureType = function (type) {
  16996. if (type === Engine.TEXTURETYPE_FLOAT) {
  16997. return this._gl.FLOAT;
  16998. }
  16999. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17000. // Add Half Float Constant.
  17001. return this._gl.HALF_FLOAT_OES;
  17002. }
  17003. return this._gl.UNSIGNED_BYTE;
  17004. };
  17005. ;
  17006. Engine.prototype._getInternalFormat = function (format) {
  17007. var internalFormat = this._gl.RGBA;
  17008. switch (format) {
  17009. case Engine.TEXTUREFORMAT_ALPHA:
  17010. internalFormat = this._gl.ALPHA;
  17011. break;
  17012. case Engine.TEXTUREFORMAT_LUMINANCE:
  17013. internalFormat = this._gl.LUMINANCE;
  17014. break;
  17015. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17016. internalFormat = this._gl.LUMINANCE_ALPHA;
  17017. break;
  17018. case Engine.TEXTUREFORMAT_RGB:
  17019. case Engine.TEXTUREFORMAT_RGB32F:
  17020. internalFormat = this._gl.RGB;
  17021. break;
  17022. case Engine.TEXTUREFORMAT_RGBA:
  17023. case Engine.TEXTUREFORMAT_RGBA32F:
  17024. internalFormat = this._gl.RGBA;
  17025. break;
  17026. case Engine.TEXTUREFORMAT_R32F:
  17027. internalFormat = this._gl.RED;
  17028. break;
  17029. case Engine.TEXTUREFORMAT_RG32F:
  17030. internalFormat = this._gl.RG;
  17031. break;
  17032. }
  17033. return internalFormat;
  17034. };
  17035. /** @hidden */
  17036. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17037. if (this._webGLVersion === 1) {
  17038. if (format) {
  17039. switch (format) {
  17040. case Engine.TEXTUREFORMAT_LUMINANCE:
  17041. return this._gl.LUMINANCE;
  17042. }
  17043. }
  17044. return this._gl.RGBA;
  17045. }
  17046. if (type === Engine.TEXTURETYPE_FLOAT) {
  17047. if (format) {
  17048. switch (format) {
  17049. case Engine.TEXTUREFORMAT_R32F:
  17050. return this._gl.R32F;
  17051. case Engine.TEXTUREFORMAT_RG32F:
  17052. return this._gl.RG32F;
  17053. case Engine.TEXTUREFORMAT_RGB32F:
  17054. return this._gl.RGB32F;
  17055. }
  17056. }
  17057. return this._gl.RGBA32F;
  17058. }
  17059. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17060. return this._gl.RGBA16F;
  17061. }
  17062. if (format) {
  17063. switch (format) {
  17064. case Engine.TEXTUREFORMAT_LUMINANCE:
  17065. return this._gl.LUMINANCE;
  17066. case Engine.TEXTUREFORMAT_RGB:
  17067. return this._gl.RGB;
  17068. }
  17069. }
  17070. return this._gl.RGBA;
  17071. };
  17072. ;
  17073. /** @hidden */
  17074. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17075. if (type === Engine.TEXTURETYPE_FLOAT) {
  17076. return this._gl.RGBA32F;
  17077. }
  17078. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17079. return this._gl.RGBA16F;
  17080. }
  17081. return this._gl.RGBA8;
  17082. };
  17083. ;
  17084. /**
  17085. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17086. * @return the new query
  17087. */
  17088. Engine.prototype.createQuery = function () {
  17089. return this._gl.createQuery();
  17090. };
  17091. /**
  17092. * Delete and release a webGL query
  17093. * @param query defines the query to delete
  17094. * @return the current engine
  17095. */
  17096. Engine.prototype.deleteQuery = function (query) {
  17097. this._gl.deleteQuery(query);
  17098. return this;
  17099. };
  17100. /**
  17101. * Check if a given query has resolved and got its value
  17102. * @param query defines the query to check
  17103. * @returns true if the query got its value
  17104. */
  17105. Engine.prototype.isQueryResultAvailable = function (query) {
  17106. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17107. };
  17108. /**
  17109. * Gets the value of a given query
  17110. * @param query defines the query to check
  17111. * @returns the value of the query
  17112. */
  17113. Engine.prototype.getQueryResult = function (query) {
  17114. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17115. };
  17116. /**
  17117. * Initiates an occlusion query
  17118. * @param algorithmType defines the algorithm to use
  17119. * @param query defines the query to use
  17120. * @returns the current engine
  17121. * @see http://doc.babylonjs.com/features/occlusionquery
  17122. */
  17123. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17124. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17125. this._gl.beginQuery(glAlgorithm, query);
  17126. return this;
  17127. };
  17128. /**
  17129. * Ends an occlusion query
  17130. * @see http://doc.babylonjs.com/features/occlusionquery
  17131. * @param algorithmType defines the algorithm to use
  17132. * @returns the current engine
  17133. */
  17134. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17135. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17136. this._gl.endQuery(glAlgorithm);
  17137. return this;
  17138. };
  17139. /* Time queries */
  17140. Engine.prototype._createTimeQuery = function () {
  17141. var timerQuery = this._caps.timerQuery;
  17142. if (timerQuery.createQueryEXT) {
  17143. return timerQuery.createQueryEXT();
  17144. }
  17145. return this.createQuery();
  17146. };
  17147. Engine.prototype._deleteTimeQuery = function (query) {
  17148. var timerQuery = this._caps.timerQuery;
  17149. if (timerQuery.deleteQueryEXT) {
  17150. timerQuery.deleteQueryEXT(query);
  17151. return;
  17152. }
  17153. this.deleteQuery(query);
  17154. };
  17155. Engine.prototype._getTimeQueryResult = function (query) {
  17156. var timerQuery = this._caps.timerQuery;
  17157. if (timerQuery.getQueryObjectEXT) {
  17158. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17159. }
  17160. return this.getQueryResult(query);
  17161. };
  17162. Engine.prototype._getTimeQueryAvailability = function (query) {
  17163. var timerQuery = this._caps.timerQuery;
  17164. if (timerQuery.getQueryObjectEXT) {
  17165. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17166. }
  17167. return this.isQueryResultAvailable(query);
  17168. };
  17169. /**
  17170. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17171. * Please note that only one query can be issued at a time
  17172. * @returns a time token used to track the time span
  17173. */
  17174. Engine.prototype.startTimeQuery = function () {
  17175. var timerQuery = this._caps.timerQuery;
  17176. if (!timerQuery) {
  17177. return null;
  17178. }
  17179. var token = new BABYLON._TimeToken();
  17180. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17181. if (this._caps.canUseTimestampForTimerQuery) {
  17182. token._startTimeQuery = this._createTimeQuery();
  17183. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17184. }
  17185. else {
  17186. if (this._currentNonTimestampToken) {
  17187. return this._currentNonTimestampToken;
  17188. }
  17189. token._timeElapsedQuery = this._createTimeQuery();
  17190. if (timerQuery.beginQueryEXT) {
  17191. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17192. }
  17193. else {
  17194. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17195. }
  17196. this._currentNonTimestampToken = token;
  17197. }
  17198. return token;
  17199. };
  17200. /**
  17201. * Ends a time query
  17202. * @param token defines the token used to measure the time span
  17203. * @returns the time spent (in ns)
  17204. */
  17205. Engine.prototype.endTimeQuery = function (token) {
  17206. var timerQuery = this._caps.timerQuery;
  17207. if (!timerQuery || !token) {
  17208. return -1;
  17209. }
  17210. if (this._caps.canUseTimestampForTimerQuery) {
  17211. if (!token._startTimeQuery) {
  17212. return -1;
  17213. }
  17214. if (!token._endTimeQuery) {
  17215. token._endTimeQuery = this._createTimeQuery();
  17216. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17217. }
  17218. }
  17219. else if (!token._timeElapsedQueryEnded) {
  17220. if (!token._timeElapsedQuery) {
  17221. return -1;
  17222. }
  17223. if (timerQuery.endQueryEXT) {
  17224. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17225. }
  17226. else {
  17227. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17228. }
  17229. token._timeElapsedQueryEnded = true;
  17230. }
  17231. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17232. var available = false;
  17233. if (token._endTimeQuery) {
  17234. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17235. }
  17236. else if (token._timeElapsedQuery) {
  17237. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17238. }
  17239. if (available && !disjoint) {
  17240. var result = 0;
  17241. if (this._caps.canUseTimestampForTimerQuery) {
  17242. if (!token._startTimeQuery || !token._endTimeQuery) {
  17243. return -1;
  17244. }
  17245. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17246. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17247. result = timeEnd - timeStart;
  17248. this._deleteTimeQuery(token._startTimeQuery);
  17249. this._deleteTimeQuery(token._endTimeQuery);
  17250. token._startTimeQuery = null;
  17251. token._endTimeQuery = null;
  17252. }
  17253. else {
  17254. if (!token._timeElapsedQuery) {
  17255. return -1;
  17256. }
  17257. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17258. this._deleteTimeQuery(token._timeElapsedQuery);
  17259. token._timeElapsedQuery = null;
  17260. token._timeElapsedQueryEnded = false;
  17261. this._currentNonTimestampToken = null;
  17262. }
  17263. return result;
  17264. }
  17265. return -1;
  17266. };
  17267. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17268. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17269. };
  17270. // Transform feedback
  17271. /**
  17272. * Creates a webGL transform feedback object
  17273. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17274. * @returns the webGL transform feedback object
  17275. */
  17276. Engine.prototype.createTransformFeedback = function () {
  17277. return this._gl.createTransformFeedback();
  17278. };
  17279. /**
  17280. * Delete a webGL transform feedback object
  17281. * @param value defines the webGL transform feedback object to delete
  17282. */
  17283. Engine.prototype.deleteTransformFeedback = function (value) {
  17284. this._gl.deleteTransformFeedback(value);
  17285. };
  17286. /**
  17287. * Bind a webGL transform feedback object to the webgl context
  17288. * @param value defines the webGL transform feedback object to bind
  17289. */
  17290. Engine.prototype.bindTransformFeedback = function (value) {
  17291. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17292. };
  17293. /**
  17294. * Begins a transform feedback operation
  17295. * @param usePoints defines if points or triangles must be used
  17296. */
  17297. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17298. if (usePoints === void 0) { usePoints = true; }
  17299. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17300. };
  17301. /**
  17302. * Ends a transform feedback operation
  17303. */
  17304. Engine.prototype.endTransformFeedback = function () {
  17305. this._gl.endTransformFeedback();
  17306. };
  17307. /**
  17308. * Specify the varyings to use with transform feedback
  17309. * @param program defines the associated webGL program
  17310. * @param value defines the list of strings representing the varying names
  17311. */
  17312. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17313. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17314. };
  17315. /**
  17316. * Bind a webGL buffer for a transform feedback operation
  17317. * @param value defines the webGL buffer to bind
  17318. */
  17319. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17320. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17321. };
  17322. /** @hidden */
  17323. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17324. var _this = this;
  17325. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17326. this._activeRequests.push(request);
  17327. request.onCompleteObservable.add(function (request) {
  17328. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17329. });
  17330. return request;
  17331. };
  17332. /** @hidden */
  17333. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17334. var _this = this;
  17335. return new Promise(function (resolve, reject) {
  17336. _this._loadFile(url, function (data) {
  17337. resolve(data);
  17338. }, undefined, database, useArrayBuffer, function (request, exception) {
  17339. reject(exception);
  17340. });
  17341. });
  17342. };
  17343. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17344. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17345. var onload = function (data) {
  17346. loadedFiles[index] = data;
  17347. loadedFiles._internalCount++;
  17348. if (loadedFiles._internalCount === 6) {
  17349. onfinish(loadedFiles);
  17350. }
  17351. };
  17352. var onerror = function (request, exception) {
  17353. if (onErrorCallBack && request) {
  17354. onErrorCallBack(request.status + " " + request.statusText, exception);
  17355. }
  17356. };
  17357. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17358. };
  17359. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17360. if (onError === void 0) { onError = null; }
  17361. var loadedFiles = [];
  17362. loadedFiles._internalCount = 0;
  17363. for (var index = 0; index < 6; index++) {
  17364. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17365. }
  17366. };
  17367. // Statics
  17368. /**
  17369. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17370. * @returns true if the engine can be created
  17371. * @ignorenaming
  17372. */
  17373. Engine.isSupported = function () {
  17374. try {
  17375. var tempcanvas = document.createElement("canvas");
  17376. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17377. return gl != null && !!window.WebGLRenderingContext;
  17378. }
  17379. catch (e) {
  17380. return false;
  17381. }
  17382. };
  17383. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17384. Engine.ExceptionList = [
  17385. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17386. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17387. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17388. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17389. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17390. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17391. ];
  17392. /** Gets the list of created engines */
  17393. Engine.Instances = new Array();
  17394. // Const statics
  17395. Engine._ALPHA_DISABLE = 0;
  17396. Engine._ALPHA_ADD = 1;
  17397. Engine._ALPHA_COMBINE = 2;
  17398. Engine._ALPHA_SUBTRACT = 3;
  17399. Engine._ALPHA_MULTIPLY = 4;
  17400. Engine._ALPHA_MAXIMIZED = 5;
  17401. Engine._ALPHA_ONEONE = 6;
  17402. Engine._ALPHA_PREMULTIPLIED = 7;
  17403. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17404. Engine._ALPHA_INTERPOLATE = 9;
  17405. Engine._ALPHA_SCREENMODE = 10;
  17406. Engine._DELAYLOADSTATE_NONE = 0;
  17407. Engine._DELAYLOADSTATE_LOADED = 1;
  17408. Engine._DELAYLOADSTATE_LOADING = 2;
  17409. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17410. Engine._TEXTUREFORMAT_ALPHA = 0;
  17411. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17412. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17413. Engine._TEXTUREFORMAT_RGB = 4;
  17414. Engine._TEXTUREFORMAT_RGBA = 5;
  17415. Engine._TEXTUREFORMAT_R32F = 6;
  17416. Engine._TEXTUREFORMAT_RG32F = 7;
  17417. Engine._TEXTUREFORMAT_RGB32F = 8;
  17418. Engine._TEXTUREFORMAT_RGBA32F = 9;
  17419. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17420. Engine._TEXTURETYPE_FLOAT = 1;
  17421. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17422. // Depht or Stencil test Constants.
  17423. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17424. 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.
  17425. 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.
  17426. 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.
  17427. 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.
  17428. 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.
  17429. 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.
  17430. 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.
  17431. // Stencil Actions Constants.
  17432. Engine._KEEP = 0x1E00;
  17433. Engine._REPLACE = 0x1E01;
  17434. Engine._INCR = 0x1E02;
  17435. Engine._DECR = 0x1E03;
  17436. Engine._INVERT = 0x150A;
  17437. Engine._INCR_WRAP = 0x8507;
  17438. Engine._DECR_WRAP = 0x8508;
  17439. // Texture rescaling mode
  17440. Engine._SCALEMODE_FLOOR = 1;
  17441. Engine._SCALEMODE_NEAREST = 2;
  17442. Engine._SCALEMODE_CEILING = 3;
  17443. // Updatable statics so stick with vars here
  17444. /**
  17445. * Gets or sets the epsilon value used by collision engine
  17446. */
  17447. Engine.CollisionsEpsilon = 0.001;
  17448. /**
  17449. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17450. */
  17451. Engine.CodeRepository = "src/";
  17452. /**
  17453. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17454. */
  17455. Engine.ShadersRepository = "src/Shaders/";
  17456. return Engine;
  17457. }());
  17458. BABYLON.Engine = Engine;
  17459. })(BABYLON || (BABYLON = {}));
  17460. //# sourceMappingURL=babylon.engine.js.map
  17461. var BABYLON;
  17462. (function (BABYLON) {
  17463. /**
  17464. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17465. */
  17466. var Node = /** @class */ (function () {
  17467. /**
  17468. * Creates a new Node
  17469. * @param {string} name - the name and id to be given to this node
  17470. * @param {BABYLON.Scene} the scene this node will be added to
  17471. */
  17472. function Node(name, scene) {
  17473. if (scene === void 0) { scene = null; }
  17474. /**
  17475. * Gets or sets a string used to store user defined state for the node
  17476. */
  17477. this.state = "";
  17478. /**
  17479. * Gets or sets an object used to store user defined information for the node
  17480. */
  17481. this.metadata = null;
  17482. /**
  17483. * Gets or sets a boolean used to define if the node must be serialized
  17484. */
  17485. this.doNotSerialize = false;
  17486. /** @hidden */
  17487. this._isDisposed = false;
  17488. /**
  17489. * Gets a list of Animations associated with the node
  17490. */
  17491. this.animations = new Array();
  17492. this._ranges = {};
  17493. this._isEnabled = true;
  17494. this._isReady = true;
  17495. /** @hidden */
  17496. this._currentRenderId = -1;
  17497. this._parentRenderId = -1;
  17498. this._childRenderId = -1;
  17499. this._animationPropertiesOverride = null;
  17500. /**
  17501. * An event triggered when the mesh is disposed
  17502. */
  17503. this.onDisposeObservable = new BABYLON.Observable();
  17504. // Behaviors
  17505. this._behaviors = new Array();
  17506. this.name = name;
  17507. this.id = name;
  17508. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17509. this.uniqueId = this._scene.getUniqueId();
  17510. this._initCache();
  17511. }
  17512. /**
  17513. * Gets a boolean indicating if the node has been disposed
  17514. * @returns true if the node was disposed
  17515. */
  17516. Node.prototype.isDisposed = function () {
  17517. return this._isDisposed;
  17518. };
  17519. Object.defineProperty(Node.prototype, "parent", {
  17520. get: function () {
  17521. return this._parentNode;
  17522. },
  17523. /**
  17524. * Gets or sets the parent of the node
  17525. */
  17526. set: function (parent) {
  17527. if (this._parentNode === parent) {
  17528. return;
  17529. }
  17530. // Remove self from list of children of parent
  17531. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17532. var index = this._parentNode._children.indexOf(this);
  17533. if (index !== -1) {
  17534. this._parentNode._children.splice(index, 1);
  17535. }
  17536. }
  17537. // Store new parent
  17538. this._parentNode = parent;
  17539. // Add as child to new parent
  17540. if (this._parentNode) {
  17541. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17542. this._parentNode._children = new Array();
  17543. }
  17544. this._parentNode._children.push(this);
  17545. }
  17546. },
  17547. enumerable: true,
  17548. configurable: true
  17549. });
  17550. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17551. /**
  17552. * Gets or sets the animation properties override
  17553. */
  17554. get: function () {
  17555. if (!this._animationPropertiesOverride) {
  17556. return this._scene.animationPropertiesOverride;
  17557. }
  17558. return this._animationPropertiesOverride;
  17559. },
  17560. set: function (value) {
  17561. this._animationPropertiesOverride = value;
  17562. },
  17563. enumerable: true,
  17564. configurable: true
  17565. });
  17566. /**
  17567. * Gets a string idenfifying the name of the class
  17568. * @returns "Node" string
  17569. */
  17570. Node.prototype.getClassName = function () {
  17571. return "Node";
  17572. };
  17573. Object.defineProperty(Node.prototype, "onDispose", {
  17574. /**
  17575. * Sets a callback that will be raised when the node will be disposed
  17576. */
  17577. set: function (callback) {
  17578. if (this._onDisposeObserver) {
  17579. this.onDisposeObservable.remove(this._onDisposeObserver);
  17580. }
  17581. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17582. },
  17583. enumerable: true,
  17584. configurable: true
  17585. });
  17586. /**
  17587. * Gets the scene of the node
  17588. * @returns a {BABYLON.Scene}
  17589. */
  17590. Node.prototype.getScene = function () {
  17591. return this._scene;
  17592. };
  17593. /**
  17594. * Gets the engine of the node
  17595. * @returns a {BABYLON.Engine}
  17596. */
  17597. Node.prototype.getEngine = function () {
  17598. return this._scene.getEngine();
  17599. };
  17600. /**
  17601. * Attach a behavior to the node
  17602. * @see http://doc.babylonjs.com/features/behaviour
  17603. * @param behavior defines the behavior to attach
  17604. * @returns the current Node
  17605. */
  17606. Node.prototype.addBehavior = function (behavior) {
  17607. var _this = this;
  17608. var index = this._behaviors.indexOf(behavior);
  17609. if (index !== -1) {
  17610. return this;
  17611. }
  17612. behavior.init();
  17613. if (this._scene.isLoading) {
  17614. // We defer the attach when the scene will be loaded
  17615. var observer = this._scene.onDataLoadedObservable.add(function () {
  17616. behavior.attach(_this);
  17617. setTimeout(function () {
  17618. // Need to use a timeout to avoid removing an observer while iterating the list of observers
  17619. _this._scene.onDataLoadedObservable.remove(observer);
  17620. }, 0);
  17621. });
  17622. }
  17623. else {
  17624. behavior.attach(this);
  17625. }
  17626. this._behaviors.push(behavior);
  17627. return this;
  17628. };
  17629. /**
  17630. * Remove an attached behavior
  17631. * @see http://doc.babylonjs.com/features/behaviour
  17632. * @param behavior defines the behavior to attach
  17633. * @returns the current Node
  17634. */
  17635. Node.prototype.removeBehavior = function (behavior) {
  17636. var index = this._behaviors.indexOf(behavior);
  17637. if (index === -1) {
  17638. return this;
  17639. }
  17640. this._behaviors[index].detach();
  17641. this._behaviors.splice(index, 1);
  17642. return this;
  17643. };
  17644. Object.defineProperty(Node.prototype, "behaviors", {
  17645. /**
  17646. * Gets the list of attached behaviors
  17647. * @see http://doc.babylonjs.com/features/behaviour
  17648. */
  17649. get: function () {
  17650. return this._behaviors;
  17651. },
  17652. enumerable: true,
  17653. configurable: true
  17654. });
  17655. /**
  17656. * Gets an attached behavior by name
  17657. * @param name defines the name of the behavior to look for
  17658. * @see http://doc.babylonjs.com/features/behaviour
  17659. * @returns null if behavior was not found else the requested behavior
  17660. */
  17661. Node.prototype.getBehaviorByName = function (name) {
  17662. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17663. var behavior = _a[_i];
  17664. if (behavior.name === name) {
  17665. return behavior;
  17666. }
  17667. }
  17668. return null;
  17669. };
  17670. /**
  17671. * Returns the world matrix of the node
  17672. * @returns a matrix containing the node's world matrix
  17673. */
  17674. Node.prototype.getWorldMatrix = function () {
  17675. return BABYLON.Matrix.Identity();
  17676. };
  17677. /** @hidden */
  17678. Node.prototype._getWorldMatrixDeterminant = function () {
  17679. return 1;
  17680. };
  17681. // override it in derived class if you add new variables to the cache
  17682. // and call the parent class method
  17683. /** @hidden */
  17684. Node.prototype._initCache = function () {
  17685. this._cache = {};
  17686. this._cache.parent = undefined;
  17687. };
  17688. /** @hidden */
  17689. Node.prototype.updateCache = function (force) {
  17690. if (!force && this.isSynchronized())
  17691. return;
  17692. this._cache.parent = this.parent;
  17693. this._updateCache();
  17694. };
  17695. // override it in derived class if you add new variables to the cache
  17696. // and call the parent class method if !ignoreParentClass
  17697. /** @hidden */
  17698. Node.prototype._updateCache = function (ignoreParentClass) {
  17699. };
  17700. // override it in derived class if you add new variables to the cache
  17701. /** @hidden */
  17702. Node.prototype._isSynchronized = function () {
  17703. return true;
  17704. };
  17705. /** @hidden */
  17706. Node.prototype._markSyncedWithParent = function () {
  17707. if (this.parent) {
  17708. this._parentRenderId = this.parent._childRenderId;
  17709. }
  17710. };
  17711. /** @hidden */
  17712. Node.prototype.isSynchronizedWithParent = function () {
  17713. if (!this.parent) {
  17714. return true;
  17715. }
  17716. if (this._parentRenderId !== this.parent._childRenderId) {
  17717. return false;
  17718. }
  17719. return this.parent.isSynchronized();
  17720. };
  17721. /** @hidden */
  17722. Node.prototype.isSynchronized = function (updateCache) {
  17723. var check = this.hasNewParent();
  17724. check = check || !this.isSynchronizedWithParent();
  17725. check = check || !this._isSynchronized();
  17726. if (updateCache)
  17727. this.updateCache(true);
  17728. return !check;
  17729. };
  17730. /** @hidden */
  17731. Node.prototype.hasNewParent = function (update) {
  17732. if (this._cache.parent === this.parent)
  17733. return false;
  17734. if (update)
  17735. this._cache.parent = this.parent;
  17736. return true;
  17737. };
  17738. /**
  17739. * Is this node ready to be used/rendered
  17740. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  17741. * @return true if the node is ready
  17742. */
  17743. Node.prototype.isReady = function (completeCheck) {
  17744. if (completeCheck === void 0) { completeCheck = false; }
  17745. return this._isReady;
  17746. };
  17747. /**
  17748. * Is this node enabled?
  17749. * 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
  17750. * @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
  17751. * @return whether this node (and its parent) is enabled
  17752. */
  17753. Node.prototype.isEnabled = function (checkAncestors) {
  17754. if (checkAncestors === void 0) { checkAncestors = true; }
  17755. if (checkAncestors === false) {
  17756. return this._isEnabled;
  17757. }
  17758. if (this._isEnabled === false) {
  17759. return false;
  17760. }
  17761. if (this.parent !== undefined && this.parent !== null) {
  17762. return this.parent.isEnabled(checkAncestors);
  17763. }
  17764. return true;
  17765. };
  17766. /**
  17767. * Set the enabled state of this node
  17768. * @param value defines the new enabled state
  17769. */
  17770. Node.prototype.setEnabled = function (value) {
  17771. this._isEnabled = value;
  17772. };
  17773. /**
  17774. * Is this node a descendant of the given node?
  17775. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  17776. * @param ancestor defines the parent node to inspect
  17777. * @returns a boolean indicating if this node is a descendant of the given node
  17778. */
  17779. Node.prototype.isDescendantOf = function (ancestor) {
  17780. if (this.parent) {
  17781. if (this.parent === ancestor) {
  17782. return true;
  17783. }
  17784. return this.parent.isDescendantOf(ancestor);
  17785. }
  17786. return false;
  17787. };
  17788. /** @hidden */
  17789. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  17790. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  17791. if (!this._children) {
  17792. return;
  17793. }
  17794. for (var index = 0; index < this._children.length; index++) {
  17795. var item = this._children[index];
  17796. if (!predicate || predicate(item)) {
  17797. results.push(item);
  17798. }
  17799. if (!directDescendantsOnly) {
  17800. item._getDescendants(results, false, predicate);
  17801. }
  17802. }
  17803. };
  17804. /**
  17805. * Will return all nodes that have this node as ascendant
  17806. * @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
  17807. * @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
  17808. * @return all children nodes of all types
  17809. */
  17810. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  17811. var results = new Array();
  17812. this._getDescendants(results, directDescendantsOnly, predicate);
  17813. return results;
  17814. };
  17815. /**
  17816. * Get all child-meshes of this node
  17817. * @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
  17818. * @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
  17819. * @returns an array of {BABYLON.AbstractMesh}
  17820. */
  17821. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  17822. var results = [];
  17823. this._getDescendants(results, directDescendantsOnly, function (node) {
  17824. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  17825. });
  17826. return results;
  17827. };
  17828. /**
  17829. * Get all child-transformNodes of this node
  17830. * @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
  17831. * @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
  17832. * @returns an array of {BABYLON.TransformNode}
  17833. */
  17834. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  17835. var results = [];
  17836. this._getDescendants(results, directDescendantsOnly, function (node) {
  17837. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  17838. });
  17839. return results;
  17840. };
  17841. /**
  17842. * Get all direct children of this node
  17843. * @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
  17844. * @returns an array of {BABYLON.Node}
  17845. */
  17846. Node.prototype.getChildren = function (predicate) {
  17847. return this.getDescendants(true, predicate);
  17848. };
  17849. /** @hidden */
  17850. Node.prototype._setReady = function (state) {
  17851. if (state === this._isReady) {
  17852. return;
  17853. }
  17854. if (!state) {
  17855. this._isReady = false;
  17856. return;
  17857. }
  17858. if (this.onReady) {
  17859. this.onReady(this);
  17860. }
  17861. this._isReady = true;
  17862. };
  17863. /**
  17864. * Get an animation by name
  17865. * @param name defines the name of the animation to look for
  17866. * @returns null if not found else the requested animation
  17867. */
  17868. Node.prototype.getAnimationByName = function (name) {
  17869. for (var i = 0; i < this.animations.length; i++) {
  17870. var animation = this.animations[i];
  17871. if (animation.name === name) {
  17872. return animation;
  17873. }
  17874. }
  17875. return null;
  17876. };
  17877. /**
  17878. * Creates an animation range for this node
  17879. * @param name defines the name of the range
  17880. * @param from defines the starting key
  17881. * @param to defines the end key
  17882. */
  17883. Node.prototype.createAnimationRange = function (name, from, to) {
  17884. // check name not already in use
  17885. if (!this._ranges[name]) {
  17886. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  17887. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17888. if (this.animations[i]) {
  17889. this.animations[i].createRange(name, from, to);
  17890. }
  17891. }
  17892. }
  17893. };
  17894. /**
  17895. * Delete a specific animation range
  17896. * @param name defines the name of the range to delete
  17897. * @param deleteFrames defines if animation frames from the range must be deleted as well
  17898. */
  17899. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  17900. if (deleteFrames === void 0) { deleteFrames = true; }
  17901. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  17902. if (this.animations[i]) {
  17903. this.animations[i].deleteRange(name, deleteFrames);
  17904. }
  17905. }
  17906. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  17907. };
  17908. /**
  17909. * Get an animation range by name
  17910. * @param name defines the name of the animation range to look for
  17911. * @returns null if not found else the requested animation range
  17912. */
  17913. Node.prototype.getAnimationRange = function (name) {
  17914. return this._ranges[name];
  17915. };
  17916. /**
  17917. * Will start the animation sequence
  17918. * @param name defines the range frames for animation sequence
  17919. * @param loop defines if the animation should loop (false by default)
  17920. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  17921. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  17922. * @returns the object created for this animation. If range does not exist, it will return null
  17923. */
  17924. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  17925. var range = this.getAnimationRange(name);
  17926. if (!range) {
  17927. return null;
  17928. }
  17929. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  17930. };
  17931. /**
  17932. * Serialize animation ranges into a JSON compatible object
  17933. * @returns serialization object
  17934. */
  17935. Node.prototype.serializeAnimationRanges = function () {
  17936. var serializationRanges = [];
  17937. for (var name in this._ranges) {
  17938. var localRange = this._ranges[name];
  17939. if (!localRange) {
  17940. continue;
  17941. }
  17942. var range = {};
  17943. range.name = name;
  17944. range.from = localRange.from;
  17945. range.to = localRange.to;
  17946. serializationRanges.push(range);
  17947. }
  17948. return serializationRanges;
  17949. };
  17950. /**
  17951. * Computes the world matrix of the node
  17952. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  17953. * @returns the world matrix
  17954. */
  17955. Node.prototype.computeWorldMatrix = function (force) {
  17956. return BABYLON.Matrix.Identity();
  17957. };
  17958. /**
  17959. * Releases resources associated with this node.
  17960. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  17961. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  17962. */
  17963. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  17964. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  17965. if (!doNotRecurse) {
  17966. var nodes = this.getDescendants(true);
  17967. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  17968. var node = nodes_1[_i];
  17969. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  17970. }
  17971. }
  17972. else {
  17973. var transformNodes = this.getChildTransformNodes(true);
  17974. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  17975. var transformNode = transformNodes_1[_a];
  17976. transformNode.parent = null;
  17977. transformNode.computeWorldMatrix(true);
  17978. }
  17979. }
  17980. this.parent = null;
  17981. // Callback
  17982. this.onDisposeObservable.notifyObservers(this);
  17983. this.onDisposeObservable.clear();
  17984. // Behaviors
  17985. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  17986. var behavior = _c[_b];
  17987. behavior.detach();
  17988. }
  17989. this._behaviors = [];
  17990. this._isDisposed = true;
  17991. };
  17992. /**
  17993. * Parse animation range data from a serialization object and store them into a given node
  17994. * @param node defines where to store the animation ranges
  17995. * @param parsedNode defines the serialization object to read data from
  17996. * @param scene defines the hosting scene
  17997. */
  17998. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  17999. if (parsedNode.ranges) {
  18000. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18001. var data = parsedNode.ranges[index];
  18002. node.createAnimationRange(data.name, data.from, data.to);
  18003. }
  18004. }
  18005. };
  18006. __decorate([
  18007. BABYLON.serialize()
  18008. ], Node.prototype, "name", void 0);
  18009. __decorate([
  18010. BABYLON.serialize()
  18011. ], Node.prototype, "id", void 0);
  18012. __decorate([
  18013. BABYLON.serialize()
  18014. ], Node.prototype, "uniqueId", void 0);
  18015. __decorate([
  18016. BABYLON.serialize()
  18017. ], Node.prototype, "state", void 0);
  18018. __decorate([
  18019. BABYLON.serialize()
  18020. ], Node.prototype, "metadata", void 0);
  18021. return Node;
  18022. }());
  18023. BABYLON.Node = Node;
  18024. })(BABYLON || (BABYLON = {}));
  18025. //# sourceMappingURL=babylon.node.js.map
  18026. var BABYLON;
  18027. (function (BABYLON) {
  18028. var BoundingSphere = /** @class */ (function () {
  18029. /**
  18030. * Creates a new bounding sphere
  18031. * @param min defines the minimum vector (in local space)
  18032. * @param max defines the maximum vector (in local space)
  18033. */
  18034. function BoundingSphere(min, max) {
  18035. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18036. this.reConstruct(min, max);
  18037. }
  18038. /**
  18039. * Recreates the entire bounding sphere from scratch
  18040. * @param min defines the new minimum vector (in local space)
  18041. * @param max defines the new maximum vector (in local space)
  18042. */
  18043. BoundingSphere.prototype.reConstruct = function (min, max) {
  18044. this.minimum = min.clone();
  18045. this.maximum = max.clone();
  18046. var distance = BABYLON.Vector3.Distance(min, max);
  18047. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18048. this.radius = distance * 0.5;
  18049. this.centerWorld = BABYLON.Vector3.Zero();
  18050. this._update(BABYLON.Matrix.Identity());
  18051. };
  18052. // Methods
  18053. BoundingSphere.prototype._update = function (world) {
  18054. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18055. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18056. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18057. };
  18058. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18059. for (var i = 0; i < 6; i++) {
  18060. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18061. return false;
  18062. }
  18063. return true;
  18064. };
  18065. BoundingSphere.prototype.intersectsPoint = function (point) {
  18066. var x = this.centerWorld.x - point.x;
  18067. var y = this.centerWorld.y - point.y;
  18068. var z = this.centerWorld.z - point.z;
  18069. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18070. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18071. return false;
  18072. return true;
  18073. };
  18074. // Statics
  18075. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18076. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18077. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18078. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18079. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18080. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18081. return false;
  18082. return true;
  18083. };
  18084. return BoundingSphere;
  18085. }());
  18086. BABYLON.BoundingSphere = BoundingSphere;
  18087. })(BABYLON || (BABYLON = {}));
  18088. //# sourceMappingURL=babylon.boundingSphere.js.map
  18089. var BABYLON;
  18090. (function (BABYLON) {
  18091. var BoundingBox = /** @class */ (function () {
  18092. /**
  18093. * Creates a new bounding box
  18094. * @param min defines the minimum vector (in local space)
  18095. * @param max defines the maximum vector (in local space)
  18096. */
  18097. function BoundingBox(min, max) {
  18098. this.vectorsWorld = new Array();
  18099. this.reConstruct(min, max);
  18100. }
  18101. // Methods
  18102. /**
  18103. * Recreates the entire bounding box from scratch
  18104. * @param min defines the new minimum vector (in local space)
  18105. * @param max defines the new maximum vector (in local space)
  18106. */
  18107. BoundingBox.prototype.reConstruct = function (min, max) {
  18108. this.minimum = min.clone();
  18109. this.maximum = max.clone();
  18110. // Bounding vectors
  18111. this.vectors = new Array();
  18112. this.vectors.push(this.minimum.clone());
  18113. this.vectors.push(this.maximum.clone());
  18114. this.vectors.push(this.minimum.clone());
  18115. this.vectors[2].x = this.maximum.x;
  18116. this.vectors.push(this.minimum.clone());
  18117. this.vectors[3].y = this.maximum.y;
  18118. this.vectors.push(this.minimum.clone());
  18119. this.vectors[4].z = this.maximum.z;
  18120. this.vectors.push(this.maximum.clone());
  18121. this.vectors[5].z = this.minimum.z;
  18122. this.vectors.push(this.maximum.clone());
  18123. this.vectors[6].x = this.minimum.x;
  18124. this.vectors.push(this.maximum.clone());
  18125. this.vectors[7].y = this.minimum.y;
  18126. // OBB
  18127. this.center = this.maximum.add(this.minimum).scale(0.5);
  18128. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18129. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18130. // World
  18131. for (var index = 0; index < this.vectors.length; index++) {
  18132. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18133. }
  18134. this.minimumWorld = BABYLON.Vector3.Zero();
  18135. this.maximumWorld = BABYLON.Vector3.Zero();
  18136. this.centerWorld = BABYLON.Vector3.Zero();
  18137. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18138. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18139. };
  18140. BoundingBox.prototype.getWorldMatrix = function () {
  18141. return this._worldMatrix;
  18142. };
  18143. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18144. this._worldMatrix.copyFrom(matrix);
  18145. return this;
  18146. };
  18147. BoundingBox.prototype._update = function (world) {
  18148. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18149. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18150. for (var index = 0; index < this.vectors.length; index++) {
  18151. var v = this.vectorsWorld[index];
  18152. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18153. if (v.x < this.minimumWorld.x)
  18154. this.minimumWorld.x = v.x;
  18155. if (v.y < this.minimumWorld.y)
  18156. this.minimumWorld.y = v.y;
  18157. if (v.z < this.minimumWorld.z)
  18158. this.minimumWorld.z = v.z;
  18159. if (v.x > this.maximumWorld.x)
  18160. this.maximumWorld.x = v.x;
  18161. if (v.y > this.maximumWorld.y)
  18162. this.maximumWorld.y = v.y;
  18163. if (v.z > this.maximumWorld.z)
  18164. this.maximumWorld.z = v.z;
  18165. }
  18166. // Extend
  18167. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18168. this.extendSizeWorld.scaleInPlace(0.5);
  18169. // OBB
  18170. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18171. this.centerWorld.scaleInPlace(0.5);
  18172. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18173. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18174. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18175. this._worldMatrix = world;
  18176. };
  18177. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18178. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18179. };
  18180. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18181. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18182. };
  18183. BoundingBox.prototype.intersectsPoint = function (point) {
  18184. var delta = -BABYLON.Epsilon;
  18185. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18186. return false;
  18187. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18188. return false;
  18189. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18190. return false;
  18191. return true;
  18192. };
  18193. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18194. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18195. };
  18196. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18197. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18198. return false;
  18199. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18200. return false;
  18201. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18202. return false;
  18203. return true;
  18204. };
  18205. // Statics
  18206. BoundingBox.Intersects = function (box0, box1) {
  18207. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18208. return false;
  18209. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18210. return false;
  18211. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18212. return false;
  18213. return true;
  18214. };
  18215. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18216. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18217. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18218. return (num <= (sphereRadius * sphereRadius));
  18219. };
  18220. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18221. for (var p = 0; p < 6; p++) {
  18222. for (var i = 0; i < 8; i++) {
  18223. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18224. return false;
  18225. }
  18226. }
  18227. }
  18228. return true;
  18229. };
  18230. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18231. for (var p = 0; p < 6; p++) {
  18232. var inCount = 8;
  18233. for (var i = 0; i < 8; i++) {
  18234. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18235. --inCount;
  18236. }
  18237. else {
  18238. break;
  18239. }
  18240. }
  18241. if (inCount === 0)
  18242. return false;
  18243. }
  18244. return true;
  18245. };
  18246. return BoundingBox;
  18247. }());
  18248. BABYLON.BoundingBox = BoundingBox;
  18249. })(BABYLON || (BABYLON = {}));
  18250. //# sourceMappingURL=babylon.boundingBox.js.map
  18251. var BABYLON;
  18252. (function (BABYLON) {
  18253. var computeBoxExtents = function (axis, box) {
  18254. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18255. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18256. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18257. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18258. var r = r0 + r1 + r2;
  18259. return {
  18260. min: p - r,
  18261. max: p + r
  18262. };
  18263. };
  18264. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18265. var axisOverlap = function (axis, box0, box1) {
  18266. var result0 = computeBoxExtents(axis, box0);
  18267. var result1 = computeBoxExtents(axis, box1);
  18268. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18269. };
  18270. var BoundingInfo = /** @class */ (function () {
  18271. function BoundingInfo(minimum, maximum) {
  18272. this.minimum = minimum;
  18273. this.maximum = maximum;
  18274. this._isLocked = false;
  18275. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18276. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18277. }
  18278. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18279. get: function () {
  18280. return this._isLocked;
  18281. },
  18282. set: function (value) {
  18283. this._isLocked = value;
  18284. },
  18285. enumerable: true,
  18286. configurable: true
  18287. });
  18288. // Methods
  18289. BoundingInfo.prototype.update = function (world) {
  18290. if (this._isLocked) {
  18291. return;
  18292. }
  18293. this.boundingBox._update(world);
  18294. this.boundingSphere._update(world);
  18295. };
  18296. /**
  18297. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18298. * @param center New center of the bounding info
  18299. * @param extend New extend of the bounding info
  18300. */
  18301. BoundingInfo.prototype.centerOn = function (center, extend) {
  18302. this.minimum = center.subtract(extend);
  18303. this.maximum = center.add(extend);
  18304. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18305. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18306. return this;
  18307. };
  18308. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18309. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18310. return false;
  18311. return this.boundingBox.isInFrustum(frustumPlanes);
  18312. };
  18313. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18314. /**
  18315. * Gets the world distance between the min and max points of the bounding box
  18316. */
  18317. get: function () {
  18318. var boundingBox = this.boundingBox;
  18319. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18320. return size.length();
  18321. },
  18322. enumerable: true,
  18323. configurable: true
  18324. });
  18325. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18326. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18327. };
  18328. BoundingInfo.prototype._checkCollision = function (collider) {
  18329. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18330. };
  18331. BoundingInfo.prototype.intersectsPoint = function (point) {
  18332. if (!this.boundingSphere.centerWorld) {
  18333. return false;
  18334. }
  18335. if (!this.boundingSphere.intersectsPoint(point)) {
  18336. return false;
  18337. }
  18338. if (!this.boundingBox.intersectsPoint(point)) {
  18339. return false;
  18340. }
  18341. return true;
  18342. };
  18343. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18344. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18345. return false;
  18346. }
  18347. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18348. return false;
  18349. }
  18350. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18351. return false;
  18352. }
  18353. if (!precise) {
  18354. return true;
  18355. }
  18356. var box0 = this.boundingBox;
  18357. var box1 = boundingInfo.boundingBox;
  18358. if (!axisOverlap(box0.directions[0], box0, box1))
  18359. return false;
  18360. if (!axisOverlap(box0.directions[1], box0, box1))
  18361. return false;
  18362. if (!axisOverlap(box0.directions[2], box0, box1))
  18363. return false;
  18364. if (!axisOverlap(box1.directions[0], box0, box1))
  18365. return false;
  18366. if (!axisOverlap(box1.directions[1], box0, box1))
  18367. return false;
  18368. if (!axisOverlap(box1.directions[2], box0, box1))
  18369. return false;
  18370. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18371. return false;
  18372. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18373. return false;
  18374. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18375. return false;
  18376. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18377. return false;
  18378. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18379. return false;
  18380. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18381. return false;
  18382. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18383. return false;
  18384. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18385. return false;
  18386. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18387. return false;
  18388. return true;
  18389. };
  18390. return BoundingInfo;
  18391. }());
  18392. BABYLON.BoundingInfo = BoundingInfo;
  18393. })(BABYLON || (BABYLON = {}));
  18394. //# sourceMappingURL=babylon.boundingInfo.js.map
  18395. var BABYLON;
  18396. (function (BABYLON) {
  18397. var TransformNode = /** @class */ (function (_super) {
  18398. __extends(TransformNode, _super);
  18399. function TransformNode(name, scene, isPure) {
  18400. if (scene === void 0) { scene = null; }
  18401. if (isPure === void 0) { isPure = true; }
  18402. var _this = _super.call(this, name, scene) || this;
  18403. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18404. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18405. _this._up = new BABYLON.Vector3(0, 1, 0);
  18406. _this._right = new BABYLON.Vector3(1, 0, 0);
  18407. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18408. // Properties
  18409. _this._rotation = BABYLON.Vector3.Zero();
  18410. _this._scaling = BABYLON.Vector3.One();
  18411. _this._isDirty = false;
  18412. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18413. _this.scalingDeterminant = 1;
  18414. _this.infiniteDistance = false;
  18415. _this.position = BABYLON.Vector3.Zero();
  18416. _this._localWorld = BABYLON.Matrix.Zero();
  18417. _this._worldMatrix = BABYLON.Matrix.Zero();
  18418. _this._worldMatrixDeterminant = 0;
  18419. _this._absolutePosition = BABYLON.Vector3.Zero();
  18420. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18421. _this._postMultiplyPivotMatrix = false;
  18422. _this._isWorldMatrixFrozen = false;
  18423. /**
  18424. * An event triggered after the world matrix is updated
  18425. */
  18426. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18427. _this._nonUniformScaling = false;
  18428. if (isPure) {
  18429. _this.getScene().addTransformNode(_this);
  18430. }
  18431. return _this;
  18432. }
  18433. /**
  18434. * Gets a string idenfifying the name of the class
  18435. * @returns "TransformNode" string
  18436. */
  18437. TransformNode.prototype.getClassName = function () {
  18438. return "TransformNode";
  18439. };
  18440. Object.defineProperty(TransformNode.prototype, "rotation", {
  18441. /**
  18442. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18443. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18444. * Default : (0.0, 0.0, 0.0)
  18445. */
  18446. get: function () {
  18447. return this._rotation;
  18448. },
  18449. set: function (newRotation) {
  18450. this._rotation = newRotation;
  18451. },
  18452. enumerable: true,
  18453. configurable: true
  18454. });
  18455. Object.defineProperty(TransformNode.prototype, "scaling", {
  18456. /**
  18457. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18458. * Default : (1.0, 1.0, 1.0)
  18459. */
  18460. get: function () {
  18461. return this._scaling;
  18462. },
  18463. /**
  18464. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18465. * Default : (1.0, 1.0, 1.0)
  18466. */
  18467. set: function (newScaling) {
  18468. this._scaling = newScaling;
  18469. },
  18470. enumerable: true,
  18471. configurable: true
  18472. });
  18473. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18474. /**
  18475. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18476. * It's null by default.
  18477. * 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)
  18478. */
  18479. get: function () {
  18480. return this._rotationQuaternion;
  18481. },
  18482. set: function (quaternion) {
  18483. this._rotationQuaternion = quaternion;
  18484. //reset the rotation vector.
  18485. if (quaternion && this.rotation.length()) {
  18486. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18487. }
  18488. },
  18489. enumerable: true,
  18490. configurable: true
  18491. });
  18492. Object.defineProperty(TransformNode.prototype, "forward", {
  18493. /**
  18494. * The forward direction of that transform in world space.
  18495. */
  18496. get: function () {
  18497. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18498. },
  18499. enumerable: true,
  18500. configurable: true
  18501. });
  18502. Object.defineProperty(TransformNode.prototype, "up", {
  18503. /**
  18504. * The up direction of that transform in world space.
  18505. */
  18506. get: function () {
  18507. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18508. },
  18509. enumerable: true,
  18510. configurable: true
  18511. });
  18512. Object.defineProperty(TransformNode.prototype, "right", {
  18513. /**
  18514. * The right direction of that transform in world space.
  18515. */
  18516. get: function () {
  18517. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18518. },
  18519. enumerable: true,
  18520. configurable: true
  18521. });
  18522. /**
  18523. * Returns the latest update of the World matrix
  18524. * Returns a Matrix.
  18525. */
  18526. TransformNode.prototype.getWorldMatrix = function () {
  18527. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18528. this.computeWorldMatrix();
  18529. }
  18530. return this._worldMatrix;
  18531. };
  18532. /** @hidden */
  18533. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18534. return this._worldMatrixDeterminant;
  18535. };
  18536. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18537. /**
  18538. * Returns directly the latest state of the mesh World matrix.
  18539. * A Matrix is returned.
  18540. */
  18541. get: function () {
  18542. return this._worldMatrix;
  18543. },
  18544. enumerable: true,
  18545. configurable: true
  18546. });
  18547. /**
  18548. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18549. * Returns the TransformNode.
  18550. */
  18551. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18552. this._poseMatrix.copyFrom(matrix);
  18553. return this;
  18554. };
  18555. /**
  18556. * Returns the mesh Pose matrix.
  18557. * Returned object : Matrix
  18558. */
  18559. TransformNode.prototype.getPoseMatrix = function () {
  18560. return this._poseMatrix;
  18561. };
  18562. TransformNode.prototype._isSynchronized = function () {
  18563. if (this._isDirty) {
  18564. return false;
  18565. }
  18566. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18567. return false;
  18568. if (this._cache.pivotMatrixUpdated) {
  18569. return false;
  18570. }
  18571. if (this.infiniteDistance) {
  18572. return false;
  18573. }
  18574. if (!this._cache.position.equals(this.position))
  18575. return false;
  18576. if (this.rotationQuaternion) {
  18577. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18578. return false;
  18579. }
  18580. if (!this._cache.rotation.equals(this.rotation))
  18581. return false;
  18582. if (!this._cache.scaling.equals(this.scaling))
  18583. return false;
  18584. return true;
  18585. };
  18586. TransformNode.prototype._initCache = function () {
  18587. _super.prototype._initCache.call(this);
  18588. this._cache.localMatrixUpdated = false;
  18589. this._cache.position = BABYLON.Vector3.Zero();
  18590. this._cache.scaling = BABYLON.Vector3.Zero();
  18591. this._cache.rotation = BABYLON.Vector3.Zero();
  18592. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18593. this._cache.billboardMode = -1;
  18594. };
  18595. TransformNode.prototype.markAsDirty = function (property) {
  18596. if (property === "rotation") {
  18597. this.rotationQuaternion = null;
  18598. }
  18599. this._currentRenderId = Number.MAX_VALUE;
  18600. this._isDirty = true;
  18601. return this;
  18602. };
  18603. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18604. /**
  18605. * Returns the current mesh absolute position.
  18606. * Retuns a Vector3.
  18607. */
  18608. get: function () {
  18609. return this._absolutePosition;
  18610. },
  18611. enumerable: true,
  18612. configurable: true
  18613. });
  18614. /**
  18615. * Sets a new matrix to apply before all other transformation
  18616. * @param matrix defines the transform matrix
  18617. * @returns the current TransformNode
  18618. */
  18619. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18620. return this.setPivotMatrix(matrix, false);
  18621. };
  18622. /**
  18623. * Sets a new pivot matrix to the current node
  18624. * @param matrix defines the new pivot matrix to use
  18625. * @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
  18626. * @returns the current TransformNode
  18627. */
  18628. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18629. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18630. this._pivotMatrix = matrix.clone();
  18631. this._cache.pivotMatrixUpdated = true;
  18632. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18633. if (this._postMultiplyPivotMatrix) {
  18634. if (!this._pivotMatrixInverse) {
  18635. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18636. }
  18637. else {
  18638. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18639. }
  18640. }
  18641. return this;
  18642. };
  18643. /**
  18644. * Returns the mesh pivot matrix.
  18645. * Default : Identity.
  18646. * A Matrix is returned.
  18647. */
  18648. TransformNode.prototype.getPivotMatrix = function () {
  18649. return this._pivotMatrix;
  18650. };
  18651. /**
  18652. * Prevents the World matrix to be computed any longer.
  18653. * Returns the TransformNode.
  18654. */
  18655. TransformNode.prototype.freezeWorldMatrix = function () {
  18656. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18657. this.computeWorldMatrix(true);
  18658. this._isWorldMatrixFrozen = true;
  18659. return this;
  18660. };
  18661. /**
  18662. * Allows back the World matrix computation.
  18663. * Returns the TransformNode.
  18664. */
  18665. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18666. this._isWorldMatrixFrozen = false;
  18667. this.computeWorldMatrix(true);
  18668. return this;
  18669. };
  18670. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  18671. /**
  18672. * True if the World matrix has been frozen.
  18673. * Returns a boolean.
  18674. */
  18675. get: function () {
  18676. return this._isWorldMatrixFrozen;
  18677. },
  18678. enumerable: true,
  18679. configurable: true
  18680. });
  18681. /**
  18682. * Retuns the mesh absolute position in the World.
  18683. * Returns a Vector3.
  18684. */
  18685. TransformNode.prototype.getAbsolutePosition = function () {
  18686. this.computeWorldMatrix();
  18687. return this._absolutePosition;
  18688. };
  18689. /**
  18690. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  18691. * Returns the TransformNode.
  18692. */
  18693. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  18694. if (!absolutePosition) {
  18695. return this;
  18696. }
  18697. var absolutePositionX;
  18698. var absolutePositionY;
  18699. var absolutePositionZ;
  18700. if (absolutePosition.x === undefined) {
  18701. if (arguments.length < 3) {
  18702. return this;
  18703. }
  18704. absolutePositionX = arguments[0];
  18705. absolutePositionY = arguments[1];
  18706. absolutePositionZ = arguments[2];
  18707. }
  18708. else {
  18709. absolutePositionX = absolutePosition.x;
  18710. absolutePositionY = absolutePosition.y;
  18711. absolutePositionZ = absolutePosition.z;
  18712. }
  18713. if (this.parent) {
  18714. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18715. invertParentWorldMatrix.invert();
  18716. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  18717. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  18718. }
  18719. else {
  18720. this.position.x = absolutePositionX;
  18721. this.position.y = absolutePositionY;
  18722. this.position.z = absolutePositionZ;
  18723. }
  18724. return this;
  18725. };
  18726. /**
  18727. * Sets the mesh position in its local space.
  18728. * Returns the TransformNode.
  18729. */
  18730. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  18731. this.computeWorldMatrix();
  18732. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  18733. return this;
  18734. };
  18735. /**
  18736. * Returns the mesh position in the local space from the current World matrix values.
  18737. * Returns a new Vector3.
  18738. */
  18739. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  18740. this.computeWorldMatrix();
  18741. var invLocalWorldMatrix = this._localWorld.clone();
  18742. invLocalWorldMatrix.invert();
  18743. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  18744. };
  18745. /**
  18746. * Translates the mesh along the passed Vector3 in its local space.
  18747. * Returns the TransformNode.
  18748. */
  18749. TransformNode.prototype.locallyTranslate = function (vector3) {
  18750. this.computeWorldMatrix(true);
  18751. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  18752. return this;
  18753. };
  18754. /**
  18755. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  18756. * @param targetPoint the position (must be in same space as current mesh) to look at
  18757. * @param yawCor optional yaw (y-axis) correction in radians
  18758. * @param pitchCor optional pitch (x-axis) correction in radians
  18759. * @param rollCor optional roll (z-axis) correction in radians
  18760. * @param space the choosen space of the target
  18761. * @returns the TransformNode.
  18762. */
  18763. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  18764. if (yawCor === void 0) { yawCor = 0; }
  18765. if (pitchCor === void 0) { pitchCor = 0; }
  18766. if (rollCor === void 0) { rollCor = 0; }
  18767. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18768. var dv = TransformNode._lookAtVectorCache;
  18769. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  18770. targetPoint.subtractToRef(pos, dv);
  18771. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  18772. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  18773. var pitch = Math.atan2(dv.y, len);
  18774. if (this.rotationQuaternion) {
  18775. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  18776. }
  18777. else {
  18778. this.rotation.x = pitch + pitchCor;
  18779. this.rotation.y = yaw + yawCor;
  18780. this.rotation.z = rollCor;
  18781. }
  18782. return this;
  18783. };
  18784. /**
  18785. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  18786. * This Vector3 is expressed in the World space.
  18787. */
  18788. TransformNode.prototype.getDirection = function (localAxis) {
  18789. var result = BABYLON.Vector3.Zero();
  18790. this.getDirectionToRef(localAxis, result);
  18791. return result;
  18792. };
  18793. /**
  18794. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  18795. * localAxis is expressed in the mesh local space.
  18796. * result is computed in the Wordl space from the mesh World matrix.
  18797. * Returns the TransformNode.
  18798. */
  18799. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  18800. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  18801. return this;
  18802. };
  18803. /**
  18804. * Sets a new pivot point to the current node
  18805. * @param point defines the new pivot point to use
  18806. * @param space defines if the point is in world or local space (local by default)
  18807. * @returns the current TransformNode
  18808. */
  18809. TransformNode.prototype.setPivotPoint = function (point, space) {
  18810. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  18811. if (this.getScene().getRenderId() == 0) {
  18812. this.computeWorldMatrix(true);
  18813. }
  18814. var wm = this.getWorldMatrix();
  18815. if (space == BABYLON.Space.WORLD) {
  18816. var tmat = BABYLON.Tmp.Matrix[0];
  18817. wm.invertToRef(tmat);
  18818. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  18819. }
  18820. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  18821. };
  18822. /**
  18823. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  18824. */
  18825. TransformNode.prototype.getPivotPoint = function () {
  18826. var point = BABYLON.Vector3.Zero();
  18827. this.getPivotPointToRef(point);
  18828. return point;
  18829. };
  18830. /**
  18831. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  18832. * Returns the TransformNode.
  18833. */
  18834. TransformNode.prototype.getPivotPointToRef = function (result) {
  18835. result.x = -this._pivotMatrix.m[12];
  18836. result.y = -this._pivotMatrix.m[13];
  18837. result.z = -this._pivotMatrix.m[14];
  18838. return this;
  18839. };
  18840. /**
  18841. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  18842. */
  18843. TransformNode.prototype.getAbsolutePivotPoint = function () {
  18844. var point = BABYLON.Vector3.Zero();
  18845. this.getAbsolutePivotPointToRef(point);
  18846. return point;
  18847. };
  18848. /**
  18849. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  18850. * Returns the TransformNode.
  18851. */
  18852. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  18853. result.x = this._pivotMatrix.m[12];
  18854. result.y = this._pivotMatrix.m[13];
  18855. result.z = this._pivotMatrix.m[14];
  18856. this.getPivotPointToRef(result);
  18857. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  18858. return this;
  18859. };
  18860. /**
  18861. * Defines the passed node as the parent of the current node.
  18862. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  18863. * Returns the TransformNode.
  18864. */
  18865. TransformNode.prototype.setParent = function (node) {
  18866. if (node === null) {
  18867. var rotation = BABYLON.Tmp.Quaternion[0];
  18868. var position = BABYLON.Tmp.Vector3[0];
  18869. var scale = BABYLON.Tmp.Vector3[1];
  18870. if (this.parent && this.parent.computeWorldMatrix) {
  18871. this.parent.computeWorldMatrix(true);
  18872. }
  18873. this.computeWorldMatrix(true);
  18874. this.getWorldMatrix().decompose(scale, rotation, position);
  18875. if (this.rotationQuaternion) {
  18876. this.rotationQuaternion.copyFrom(rotation);
  18877. }
  18878. else {
  18879. rotation.toEulerAnglesToRef(this.rotation);
  18880. }
  18881. this.scaling.x = scale.x;
  18882. this.scaling.y = scale.y;
  18883. this.scaling.z = scale.z;
  18884. this.position.x = position.x;
  18885. this.position.y = position.y;
  18886. this.position.z = position.z;
  18887. }
  18888. else {
  18889. var rotation = BABYLON.Tmp.Quaternion[0];
  18890. var position = BABYLON.Tmp.Vector3[0];
  18891. var scale = BABYLON.Tmp.Vector3[1];
  18892. var diffMatrix = BABYLON.Tmp.Matrix[0];
  18893. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  18894. this.computeWorldMatrix(true);
  18895. node.computeWorldMatrix(true);
  18896. node.getWorldMatrix().invertToRef(invParentMatrix);
  18897. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  18898. diffMatrix.decompose(scale, rotation, position);
  18899. if (this.rotationQuaternion) {
  18900. this.rotationQuaternion.copyFrom(rotation);
  18901. }
  18902. else {
  18903. rotation.toEulerAnglesToRef(this.rotation);
  18904. }
  18905. this.position.x = position.x;
  18906. this.position.y = position.y;
  18907. this.position.z = position.z;
  18908. this.scaling.x = scale.x;
  18909. this.scaling.y = scale.y;
  18910. this.scaling.z = scale.z;
  18911. }
  18912. this.parent = node;
  18913. return this;
  18914. };
  18915. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  18916. get: function () {
  18917. return this._nonUniformScaling;
  18918. },
  18919. enumerable: true,
  18920. configurable: true
  18921. });
  18922. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  18923. if (this._nonUniformScaling === value) {
  18924. return false;
  18925. }
  18926. this._nonUniformScaling = true;
  18927. return true;
  18928. };
  18929. /**
  18930. * Attach the current TransformNode to another TransformNode associated with a bone
  18931. * @param bone Bone affecting the TransformNode
  18932. * @param affectedTransformNode TransformNode associated with the bone
  18933. */
  18934. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  18935. this._transformToBoneReferal = affectedTransformNode;
  18936. this.parent = bone;
  18937. if (bone.getWorldMatrix().determinant() < 0) {
  18938. this.scalingDeterminant *= -1;
  18939. }
  18940. return this;
  18941. };
  18942. TransformNode.prototype.detachFromBone = function () {
  18943. if (!this.parent) {
  18944. return this;
  18945. }
  18946. if (this.parent.getWorldMatrix().determinant() < 0) {
  18947. this.scalingDeterminant *= -1;
  18948. }
  18949. this._transformToBoneReferal = null;
  18950. this.parent = null;
  18951. return this;
  18952. };
  18953. /**
  18954. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  18955. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  18956. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18957. * The passed axis is also normalized.
  18958. * Returns the TransformNode.
  18959. */
  18960. TransformNode.prototype.rotate = function (axis, amount, space) {
  18961. axis.normalize();
  18962. if (!this.rotationQuaternion) {
  18963. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18964. this.rotation = BABYLON.Vector3.Zero();
  18965. }
  18966. var rotationQuaternion;
  18967. if (!space || space === BABYLON.Space.LOCAL) {
  18968. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18969. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  18970. }
  18971. else {
  18972. if (this.parent) {
  18973. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  18974. invertParentWorldMatrix.invert();
  18975. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  18976. }
  18977. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  18978. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  18979. }
  18980. return this;
  18981. };
  18982. /**
  18983. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  18984. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  18985. * The passed axis is also normalized.
  18986. * Returns the TransformNode.
  18987. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  18988. */
  18989. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  18990. axis.normalize();
  18991. if (!this.rotationQuaternion) {
  18992. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  18993. this.rotation.copyFromFloats(0, 0, 0);
  18994. }
  18995. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  18996. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  18997. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  18998. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  18999. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19000. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19001. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19002. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19003. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19004. return this;
  19005. };
  19006. /**
  19007. * Translates the mesh along the axis vector for the passed distance in the given space.
  19008. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19009. * Returns the TransformNode.
  19010. */
  19011. TransformNode.prototype.translate = function (axis, distance, space) {
  19012. var displacementVector = axis.scale(distance);
  19013. if (!space || space === BABYLON.Space.LOCAL) {
  19014. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19015. this.setPositionWithLocalVector(tempV3);
  19016. }
  19017. else {
  19018. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19019. }
  19020. return this;
  19021. };
  19022. /**
  19023. * Adds a rotation step to the mesh current rotation.
  19024. * x, y, z are Euler angles expressed in radians.
  19025. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19026. * This means this rotation is made in the mesh local space only.
  19027. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19028. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19029. * ```javascript
  19030. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19031. * ```
  19032. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19033. * 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.
  19034. * Returns the TransformNode.
  19035. */
  19036. TransformNode.prototype.addRotation = function (x, y, z) {
  19037. var rotationQuaternion;
  19038. if (this.rotationQuaternion) {
  19039. rotationQuaternion = this.rotationQuaternion;
  19040. }
  19041. else {
  19042. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19043. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19044. }
  19045. var accumulation = BABYLON.Tmp.Quaternion[0];
  19046. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19047. rotationQuaternion.multiplyInPlace(accumulation);
  19048. if (!this.rotationQuaternion) {
  19049. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19050. }
  19051. return this;
  19052. };
  19053. /**
  19054. * Computes the mesh World matrix and returns it.
  19055. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19056. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19057. * If the parameter `force`is set to `true`, the actual computation is done.
  19058. * Returns the mesh World Matrix.
  19059. */
  19060. TransformNode.prototype.computeWorldMatrix = function (force) {
  19061. if (this._isWorldMatrixFrozen) {
  19062. return this._worldMatrix;
  19063. }
  19064. if (!force && this.isSynchronized(true)) {
  19065. this._currentRenderId = this.getScene().getRenderId();
  19066. return this._worldMatrix;
  19067. }
  19068. this._cache.position.copyFrom(this.position);
  19069. this._cache.scaling.copyFrom(this.scaling);
  19070. this._cache.pivotMatrixUpdated = false;
  19071. this._cache.billboardMode = this.billboardMode;
  19072. this._currentRenderId = this.getScene().getRenderId();
  19073. this._childRenderId = this.getScene().getRenderId();
  19074. this._isDirty = false;
  19075. // Scaling
  19076. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19077. // Rotation
  19078. //rotate, if quaternion is set and rotation was used
  19079. if (this.rotationQuaternion) {
  19080. var len = this.rotation.length();
  19081. if (len) {
  19082. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19083. this.rotation.copyFromFloats(0, 0, 0);
  19084. }
  19085. }
  19086. if (this.rotationQuaternion) {
  19087. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19088. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19089. }
  19090. else {
  19091. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19092. this._cache.rotation.copyFrom(this.rotation);
  19093. }
  19094. // Translation
  19095. var camera = this.getScene().activeCamera;
  19096. if (this.infiniteDistance && !this.parent && camera) {
  19097. var cameraWorldMatrix = camera.getWorldMatrix();
  19098. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19099. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19100. }
  19101. else {
  19102. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19103. }
  19104. // Composing transformations
  19105. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19106. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19107. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19108. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19109. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19110. // Need to decompose each rotation here
  19111. var currentPosition = BABYLON.Tmp.Vector3[3];
  19112. if (this.parent && this.parent.getWorldMatrix) {
  19113. if (this._transformToBoneReferal) {
  19114. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19115. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19116. }
  19117. else {
  19118. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19119. }
  19120. }
  19121. else {
  19122. currentPosition.copyFrom(this.position);
  19123. }
  19124. currentPosition.subtractInPlace(camera.globalPosition);
  19125. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19126. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19127. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19128. }
  19129. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19130. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19131. }
  19132. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19133. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19134. }
  19135. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19136. }
  19137. else {
  19138. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19139. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19140. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19141. }
  19142. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19143. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19144. }
  19145. // Local world
  19146. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19147. // Parent
  19148. if (this.parent && this.parent.getWorldMatrix) {
  19149. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19150. if (this._transformToBoneReferal) {
  19151. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19152. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19153. }
  19154. else {
  19155. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19156. }
  19157. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19158. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19159. this._worldMatrix.copyFrom(this._localWorld);
  19160. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19161. }
  19162. else {
  19163. if (this._transformToBoneReferal) {
  19164. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19165. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19166. }
  19167. else {
  19168. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19169. }
  19170. }
  19171. this._markSyncedWithParent();
  19172. }
  19173. else {
  19174. this._worldMatrix.copyFrom(this._localWorld);
  19175. }
  19176. // Post multiply inverse of pivotMatrix
  19177. if (this._postMultiplyPivotMatrix) {
  19178. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19179. }
  19180. // Normal matrix
  19181. if (this.scaling.isNonUniform) {
  19182. this._updateNonUniformScalingState(true);
  19183. }
  19184. else if (this.parent && this.parent._nonUniformScaling) {
  19185. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19186. }
  19187. else {
  19188. this._updateNonUniformScalingState(false);
  19189. }
  19190. this._afterComputeWorldMatrix();
  19191. // Absolute position
  19192. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19193. // Callbacks
  19194. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19195. if (!this._poseMatrix) {
  19196. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19197. }
  19198. // Cache the determinant
  19199. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19200. return this._worldMatrix;
  19201. };
  19202. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19203. };
  19204. /**
  19205. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19206. * @param func: callback function to add
  19207. *
  19208. * Returns the TransformNode.
  19209. */
  19210. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19211. this.onAfterWorldMatrixUpdateObservable.add(func);
  19212. return this;
  19213. };
  19214. /**
  19215. * Removes a registered callback function.
  19216. * Returns the TransformNode.
  19217. */
  19218. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19219. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19220. return this;
  19221. };
  19222. /**
  19223. * Clone the current transform node
  19224. * Returns the new transform node
  19225. * @param name Name of the new clone
  19226. * @param newParent New parent for the clone
  19227. * @param doNotCloneChildren Do not clone children hierarchy
  19228. */
  19229. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19230. var _this = this;
  19231. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19232. result.name = name;
  19233. result.id = name;
  19234. if (newParent) {
  19235. result.parent = newParent;
  19236. }
  19237. if (!doNotCloneChildren) {
  19238. // Children
  19239. var directDescendants = this.getDescendants(true);
  19240. for (var index = 0; index < directDescendants.length; index++) {
  19241. var child = directDescendants[index];
  19242. if (child.clone) {
  19243. child.clone(name + "." + child.name, result);
  19244. }
  19245. }
  19246. }
  19247. return result;
  19248. };
  19249. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19250. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19251. serializationObject.type = this.getClassName();
  19252. // Parent
  19253. if (this.parent) {
  19254. serializationObject.parentId = this.parent.id;
  19255. }
  19256. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19257. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19258. }
  19259. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19260. serializationObject.isEnabled = this.isEnabled();
  19261. // Parent
  19262. if (this.parent) {
  19263. serializationObject.parentId = this.parent.id;
  19264. }
  19265. return serializationObject;
  19266. };
  19267. // Statics
  19268. /**
  19269. * Returns a new TransformNode object parsed from the source provided.
  19270. * The parameter `parsedMesh` is the source.
  19271. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19272. */
  19273. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19274. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19275. if (BABYLON.Tags) {
  19276. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19277. }
  19278. if (parsedTransformNode.localMatrix) {
  19279. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19280. }
  19281. else if (parsedTransformNode.pivotMatrix) {
  19282. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19283. }
  19284. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19285. // Parent
  19286. if (parsedTransformNode.parentId) {
  19287. transformNode._waitingParentId = parsedTransformNode.parentId;
  19288. }
  19289. return transformNode;
  19290. };
  19291. /**
  19292. * Releases resources associated with this transform node.
  19293. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19294. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19295. */
  19296. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19297. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19298. // Animations
  19299. this.getScene().stopAnimation(this);
  19300. // Remove from scene
  19301. this.getScene().removeTransformNode(this);
  19302. this.onAfterWorldMatrixUpdateObservable.clear();
  19303. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19304. };
  19305. // Statics
  19306. TransformNode.BILLBOARDMODE_NONE = 0;
  19307. TransformNode.BILLBOARDMODE_X = 1;
  19308. TransformNode.BILLBOARDMODE_Y = 2;
  19309. TransformNode.BILLBOARDMODE_Z = 4;
  19310. TransformNode.BILLBOARDMODE_ALL = 7;
  19311. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19312. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19313. __decorate([
  19314. BABYLON.serializeAsVector3()
  19315. ], TransformNode.prototype, "_rotation", void 0);
  19316. __decorate([
  19317. BABYLON.serializeAsQuaternion()
  19318. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19319. __decorate([
  19320. BABYLON.serializeAsVector3()
  19321. ], TransformNode.prototype, "_scaling", void 0);
  19322. __decorate([
  19323. BABYLON.serialize()
  19324. ], TransformNode.prototype, "billboardMode", void 0);
  19325. __decorate([
  19326. BABYLON.serialize()
  19327. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19328. __decorate([
  19329. BABYLON.serialize()
  19330. ], TransformNode.prototype, "infiniteDistance", void 0);
  19331. __decorate([
  19332. BABYLON.serializeAsVector3()
  19333. ], TransformNode.prototype, "position", void 0);
  19334. return TransformNode;
  19335. }(BABYLON.Node));
  19336. BABYLON.TransformNode = TransformNode;
  19337. })(BABYLON || (BABYLON = {}));
  19338. //# sourceMappingURL=babylon.transformNode.js.map
  19339. var BABYLON;
  19340. (function (BABYLON) {
  19341. /**
  19342. * Class used to store all common mesh properties
  19343. */
  19344. var AbstractMesh = /** @class */ (function (_super) {
  19345. __extends(AbstractMesh, _super);
  19346. // Constructor
  19347. /**
  19348. * Creates a new AbstractMesh
  19349. * @param name defines the name of the mesh
  19350. * @param scene defines the hosting scene
  19351. */
  19352. function AbstractMesh(name, scene) {
  19353. if (scene === void 0) { scene = null; }
  19354. var _this = _super.call(this, name, scene, false) || this;
  19355. _this._facetNb = 0; // facet number
  19356. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19357. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19358. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19359. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19360. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19361. _this._subDiv = {
  19362. max: 1,
  19363. X: 1,
  19364. Y: 1,
  19365. Z: 1
  19366. };
  19367. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19368. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19369. // Events
  19370. /**
  19371. * An event triggered when this mesh collides with another one
  19372. */
  19373. _this.onCollideObservable = new BABYLON.Observable();
  19374. /**
  19375. * An event triggered when the collision's position changes
  19376. */
  19377. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19378. /**
  19379. * An event triggered when material is changed
  19380. */
  19381. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19382. // Properties
  19383. /**
  19384. * Gets or sets the orientation for POV movement & rotation
  19385. */
  19386. _this.definedFacingForward = true;
  19387. /**
  19388. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19389. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19390. * * 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.
  19391. * @see http://doc.babylonjs.com/features/occlusionquery
  19392. */
  19393. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19394. /**
  19395. * 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:
  19396. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19397. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19398. * * 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.
  19399. * @see http://doc.babylonjs.com/features/occlusionquery
  19400. */
  19401. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19402. /**
  19403. * 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.
  19404. * The default value is -1 which means don't break the query and wait till the result
  19405. * @see http://doc.babylonjs.com/features/occlusionquery
  19406. */
  19407. _this.occlusionRetryCount = -1;
  19408. _this._occlusionInternalRetryCounter = 0;
  19409. _this._isOccluded = false;
  19410. _this._isOcclusionQueryInProgress = false;
  19411. _this._visibility = 1.0;
  19412. /** Gets or sets the alpha index used to sort transparent meshes
  19413. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19414. */
  19415. _this.alphaIndex = Number.MAX_VALUE;
  19416. /**
  19417. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19418. */
  19419. _this.isVisible = true;
  19420. /**
  19421. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19422. */
  19423. _this.isPickable = true;
  19424. /**
  19425. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19426. */
  19427. _this.showBoundingBox = false;
  19428. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19429. _this.showSubMeshesBoundingBox = false;
  19430. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19431. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19432. */
  19433. _this.isBlocker = false;
  19434. /**
  19435. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19436. */
  19437. _this.enablePointerMoveEvents = false;
  19438. /**
  19439. * Specifies the rendering group id for this mesh (0 by default)
  19440. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19441. */
  19442. _this.renderingGroupId = 0;
  19443. _this._receiveShadows = false;
  19444. /**
  19445. * Gets or sets a boolean indicating if the outline must be rendered as well
  19446. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19447. */
  19448. _this.renderOutline = false;
  19449. /** Defines color to use when rendering outline */
  19450. _this.outlineColor = BABYLON.Color3.Red();
  19451. /** Define width to use when rendering outline */
  19452. _this.outlineWidth = 0.02;
  19453. /**
  19454. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19455. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19456. */
  19457. _this.renderOverlay = false;
  19458. /** Defines color to use when rendering overlay */
  19459. _this.overlayColor = BABYLON.Color3.Red();
  19460. /** Defines alpha to use when rendering overlay */
  19461. _this.overlayAlpha = 0.5;
  19462. _this._hasVertexAlpha = false;
  19463. _this._useVertexColors = true;
  19464. _this._computeBonesUsingShaders = true;
  19465. _this._numBoneInfluencers = 4;
  19466. _this._applyFog = true;
  19467. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19468. _this.useOctreeForRenderingSelection = true;
  19469. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19470. _this.useOctreeForPicking = true;
  19471. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19472. _this.useOctreeForCollisions = true;
  19473. _this._layerMask = 0x0FFFFFFF;
  19474. /**
  19475. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19476. */
  19477. _this.alwaysSelectAsActiveMesh = false;
  19478. /**
  19479. * Gets or sets the current action manager
  19480. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19481. */
  19482. _this.actionManager = null;
  19483. /**
  19484. * Gets or sets impostor used for physic simulation
  19485. * @see http://doc.babylonjs.com/features/physics_engine
  19486. */
  19487. _this.physicsImpostor = null;
  19488. // Collisions
  19489. _this._checkCollisions = false;
  19490. _this._collisionMask = -1;
  19491. _this._collisionGroup = -1;
  19492. /**
  19493. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19494. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19495. */
  19496. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19497. /**
  19498. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19499. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19500. */
  19501. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19502. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19503. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19504. // Edges
  19505. /**
  19506. * Defines edge width used when edgesRenderer is enabled
  19507. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19508. */
  19509. _this.edgesWidth = 1;
  19510. /**
  19511. * Defines edge color used when edgesRenderer is enabled
  19512. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19513. */
  19514. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19515. // Cache
  19516. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19517. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19518. /** @hidden */
  19519. _this._renderId = 0;
  19520. /** @hidden */
  19521. _this._intersectionsInProgress = new Array();
  19522. /** @hidden */
  19523. _this._unIndexed = false;
  19524. /** @hidden */
  19525. _this._lightSources = new Array();
  19526. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19527. if (collidedMesh === void 0) { collidedMesh = null; }
  19528. //TODO move this to the collision coordinator!
  19529. if (_this.getScene().workerCollisions)
  19530. newPosition.multiplyInPlace(_this._collider._radius);
  19531. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19532. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19533. _this.position.addInPlace(_this._diffPositionForCollisions);
  19534. }
  19535. if (collidedMesh) {
  19536. _this.onCollideObservable.notifyObservers(collidedMesh);
  19537. }
  19538. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19539. };
  19540. _this.getScene().addMesh(_this);
  19541. _this._resyncLightSources();
  19542. return _this;
  19543. }
  19544. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19545. /**
  19546. * No billboard
  19547. */
  19548. get: function () {
  19549. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19550. },
  19551. enumerable: true,
  19552. configurable: true
  19553. });
  19554. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19555. /** Billboard on X axis */
  19556. get: function () {
  19557. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19558. },
  19559. enumerable: true,
  19560. configurable: true
  19561. });
  19562. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19563. /** Billboard on Y axis */
  19564. get: function () {
  19565. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19566. },
  19567. enumerable: true,
  19568. configurable: true
  19569. });
  19570. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19571. /** Billboard on Z axis */
  19572. get: function () {
  19573. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19574. },
  19575. enumerable: true,
  19576. configurable: true
  19577. });
  19578. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19579. /** Billboard on all axes */
  19580. get: function () {
  19581. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19582. },
  19583. enumerable: true,
  19584. configurable: true
  19585. });
  19586. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19587. /**
  19588. * Gets the number of facets in the mesh
  19589. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19590. */
  19591. get: function () {
  19592. return this._facetNb;
  19593. },
  19594. enumerable: true,
  19595. configurable: true
  19596. });
  19597. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19598. /**
  19599. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19600. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19601. */
  19602. get: function () {
  19603. return this._partitioningSubdivisions;
  19604. },
  19605. set: function (nb) {
  19606. this._partitioningSubdivisions = nb;
  19607. },
  19608. enumerable: true,
  19609. configurable: true
  19610. });
  19611. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19612. /**
  19613. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19614. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19615. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19616. */
  19617. get: function () {
  19618. return this._partitioningBBoxRatio;
  19619. },
  19620. set: function (ratio) {
  19621. this._partitioningBBoxRatio = ratio;
  19622. },
  19623. enumerable: true,
  19624. configurable: true
  19625. });
  19626. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19627. /**
  19628. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19629. * Works only for updatable meshes.
  19630. * Doesn't work with multi-materials
  19631. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19632. */
  19633. get: function () {
  19634. return this._facetDepthSort;
  19635. },
  19636. set: function (sort) {
  19637. this._facetDepthSort = sort;
  19638. },
  19639. enumerable: true,
  19640. configurable: true
  19641. });
  19642. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19643. /**
  19644. * The location (Vector3) where the facet depth sort must be computed from.
  19645. * By default, the active camera position.
  19646. * Used only when facet depth sort is enabled
  19647. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19648. */
  19649. get: function () {
  19650. return this._facetDepthSortFrom;
  19651. },
  19652. set: function (location) {
  19653. this._facetDepthSortFrom = location;
  19654. },
  19655. enumerable: true,
  19656. configurable: true
  19657. });
  19658. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  19659. /**
  19660. * gets a boolean indicating if facetData is enabled
  19661. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19662. */
  19663. get: function () {
  19664. return this._facetDataEnabled;
  19665. },
  19666. enumerable: true,
  19667. configurable: true
  19668. });
  19669. /** @hidden */
  19670. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  19671. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  19672. return false;
  19673. }
  19674. this._markSubMeshesAsMiscDirty();
  19675. return true;
  19676. };
  19677. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  19678. /** Set a function to call when this mesh collides with another one */
  19679. set: function (callback) {
  19680. if (this._onCollideObserver) {
  19681. this.onCollideObservable.remove(this._onCollideObserver);
  19682. }
  19683. this._onCollideObserver = this.onCollideObservable.add(callback);
  19684. },
  19685. enumerable: true,
  19686. configurable: true
  19687. });
  19688. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  19689. /** Set a function to call when the collision's position changes */
  19690. set: function (callback) {
  19691. if (this._onCollisionPositionChangeObserver) {
  19692. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  19693. }
  19694. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  19695. },
  19696. enumerable: true,
  19697. configurable: true
  19698. });
  19699. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  19700. /**
  19701. * 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
  19702. * @see http://doc.babylonjs.com/features/occlusionquery
  19703. */
  19704. get: function () {
  19705. return this._isOccluded;
  19706. },
  19707. set: function (value) {
  19708. this._isOccluded = value;
  19709. },
  19710. enumerable: true,
  19711. configurable: true
  19712. });
  19713. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  19714. /**
  19715. * Flag to check the progress status of the query
  19716. * @see http://doc.babylonjs.com/features/occlusionquery
  19717. */
  19718. get: function () {
  19719. return this._isOcclusionQueryInProgress;
  19720. },
  19721. enumerable: true,
  19722. configurable: true
  19723. });
  19724. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  19725. /**
  19726. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19727. */
  19728. get: function () {
  19729. return this._visibility;
  19730. },
  19731. /**
  19732. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  19733. */
  19734. set: function (value) {
  19735. if (this._visibility === value) {
  19736. return;
  19737. }
  19738. this._visibility = value;
  19739. this._markSubMeshesAsMiscDirty();
  19740. },
  19741. enumerable: true,
  19742. configurable: true
  19743. });
  19744. Object.defineProperty(AbstractMesh.prototype, "material", {
  19745. /** Gets or sets current material */
  19746. get: function () {
  19747. return this._material;
  19748. },
  19749. set: function (value) {
  19750. if (this._material === value) {
  19751. return;
  19752. }
  19753. this._material = value;
  19754. if (this.onMaterialChangedObservable.hasObservers) {
  19755. this.onMaterialChangedObservable.notifyObservers(this);
  19756. }
  19757. if (!this.subMeshes) {
  19758. return;
  19759. }
  19760. this._unBindEffect();
  19761. },
  19762. enumerable: true,
  19763. configurable: true
  19764. });
  19765. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  19766. /**
  19767. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  19768. * @see http://doc.babylonjs.com/babylon101/shadows
  19769. */
  19770. get: function () {
  19771. return this._receiveShadows;
  19772. },
  19773. set: function (value) {
  19774. if (this._receiveShadows === value) {
  19775. return;
  19776. }
  19777. this._receiveShadows = value;
  19778. this._markSubMeshesAsLightDirty();
  19779. },
  19780. enumerable: true,
  19781. configurable: true
  19782. });
  19783. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  19784. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  19785. get: function () {
  19786. return this._hasVertexAlpha;
  19787. },
  19788. set: function (value) {
  19789. if (this._hasVertexAlpha === value) {
  19790. return;
  19791. }
  19792. this._hasVertexAlpha = value;
  19793. this._markSubMeshesAsAttributesDirty();
  19794. this._markSubMeshesAsMiscDirty();
  19795. },
  19796. enumerable: true,
  19797. configurable: true
  19798. });
  19799. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  19800. /** 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) */
  19801. get: function () {
  19802. return this._useVertexColors;
  19803. },
  19804. set: function (value) {
  19805. if (this._useVertexColors === value) {
  19806. return;
  19807. }
  19808. this._useVertexColors = value;
  19809. this._markSubMeshesAsAttributesDirty();
  19810. },
  19811. enumerable: true,
  19812. configurable: true
  19813. });
  19814. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  19815. /**
  19816. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  19817. */
  19818. get: function () {
  19819. return this._computeBonesUsingShaders;
  19820. },
  19821. set: function (value) {
  19822. if (this._computeBonesUsingShaders === value) {
  19823. return;
  19824. }
  19825. this._computeBonesUsingShaders = value;
  19826. this._markSubMeshesAsAttributesDirty();
  19827. },
  19828. enumerable: true,
  19829. configurable: true
  19830. });
  19831. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  19832. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  19833. get: function () {
  19834. return this._numBoneInfluencers;
  19835. },
  19836. set: function (value) {
  19837. if (this._numBoneInfluencers === value) {
  19838. return;
  19839. }
  19840. this._numBoneInfluencers = value;
  19841. this._markSubMeshesAsAttributesDirty();
  19842. },
  19843. enumerable: true,
  19844. configurable: true
  19845. });
  19846. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  19847. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  19848. get: function () {
  19849. return this._applyFog;
  19850. },
  19851. set: function (value) {
  19852. if (this._applyFog === value) {
  19853. return;
  19854. }
  19855. this._applyFog = value;
  19856. this._markSubMeshesAsMiscDirty();
  19857. },
  19858. enumerable: true,
  19859. configurable: true
  19860. });
  19861. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  19862. /**
  19863. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  19864. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  19865. */
  19866. get: function () {
  19867. return this._layerMask;
  19868. },
  19869. set: function (value) {
  19870. if (value === this._layerMask) {
  19871. return;
  19872. }
  19873. this._layerMask = value;
  19874. this._resyncLightSources();
  19875. },
  19876. enumerable: true,
  19877. configurable: true
  19878. });
  19879. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  19880. /**
  19881. * Gets or sets a collision mask used to mask collisions (default is -1).
  19882. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19883. */
  19884. get: function () {
  19885. return this._collisionMask;
  19886. },
  19887. set: function (mask) {
  19888. this._collisionMask = !isNaN(mask) ? mask : -1;
  19889. },
  19890. enumerable: true,
  19891. configurable: true
  19892. });
  19893. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  19894. /**
  19895. * Gets or sets the current collision group mask (-1 by default).
  19896. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  19897. */
  19898. get: function () {
  19899. return this._collisionGroup;
  19900. },
  19901. set: function (mask) {
  19902. this._collisionGroup = !isNaN(mask) ? mask : -1;
  19903. },
  19904. enumerable: true,
  19905. configurable: true
  19906. });
  19907. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  19908. /** @hidden */
  19909. get: function () {
  19910. return null;
  19911. },
  19912. enumerable: true,
  19913. configurable: true
  19914. });
  19915. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  19916. get: function () {
  19917. return this._skeleton;
  19918. },
  19919. /**
  19920. * Gets or sets a skeleton to apply skining transformations
  19921. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  19922. */
  19923. set: function (value) {
  19924. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  19925. this._skeleton._unregisterMeshWithPoseMatrix(this);
  19926. }
  19927. if (value && value.needInitialSkinMatrix) {
  19928. value._registerMeshWithPoseMatrix(this);
  19929. }
  19930. this._skeleton = value;
  19931. if (!this._skeleton) {
  19932. this._bonesTransformMatrices = null;
  19933. }
  19934. this._markSubMeshesAsAttributesDirty();
  19935. },
  19936. enumerable: true,
  19937. configurable: true
  19938. });
  19939. /**
  19940. * Returns the string "AbstractMesh"
  19941. * @returns "AbstractMesh"
  19942. */
  19943. AbstractMesh.prototype.getClassName = function () {
  19944. return "AbstractMesh";
  19945. };
  19946. /**
  19947. * Gets a string representation of the current mesh
  19948. * @param fullDetails defines a boolean indicating if full details must be included
  19949. * @returns a string representation of the current mesh
  19950. */
  19951. AbstractMesh.prototype.toString = function (fullDetails) {
  19952. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  19953. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  19954. if (this._skeleton) {
  19955. ret += ", skeleton: " + this._skeleton.name;
  19956. }
  19957. if (fullDetails) {
  19958. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  19959. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  19960. }
  19961. return ret;
  19962. };
  19963. /** @hidden */
  19964. AbstractMesh.prototype._rebuild = function () {
  19965. if (this._occlusionQuery) {
  19966. this._occlusionQuery = null;
  19967. }
  19968. if (this._edgesRenderer) {
  19969. this._edgesRenderer._rebuild();
  19970. }
  19971. if (!this.subMeshes) {
  19972. return;
  19973. }
  19974. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  19975. var subMesh = _a[_i];
  19976. subMesh._rebuild();
  19977. }
  19978. };
  19979. /** @hidden */
  19980. AbstractMesh.prototype._resyncLightSources = function () {
  19981. this._lightSources.length = 0;
  19982. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  19983. var light = _a[_i];
  19984. if (!light.isEnabled()) {
  19985. continue;
  19986. }
  19987. if (light.canAffectMesh(this)) {
  19988. this._lightSources.push(light);
  19989. }
  19990. }
  19991. this._markSubMeshesAsLightDirty();
  19992. };
  19993. /** @hidden */
  19994. AbstractMesh.prototype._resyncLighSource = function (light) {
  19995. var isIn = light.isEnabled() && light.canAffectMesh(this);
  19996. var index = this._lightSources.indexOf(light);
  19997. if (index === -1) {
  19998. if (!isIn) {
  19999. return;
  20000. }
  20001. this._lightSources.push(light);
  20002. }
  20003. else {
  20004. if (isIn) {
  20005. return;
  20006. }
  20007. this._lightSources.splice(index, 1);
  20008. }
  20009. this._markSubMeshesAsLightDirty();
  20010. };
  20011. /** @hidden */
  20012. AbstractMesh.prototype._unBindEffect = function () {
  20013. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20014. var subMesh = _a[_i];
  20015. subMesh.setEffect(null);
  20016. }
  20017. };
  20018. /** @hidden */
  20019. AbstractMesh.prototype._removeLightSource = function (light) {
  20020. var index = this._lightSources.indexOf(light);
  20021. if (index === -1) {
  20022. return;
  20023. }
  20024. this._lightSources.splice(index, 1);
  20025. this._markSubMeshesAsLightDirty();
  20026. };
  20027. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20028. if (!this.subMeshes) {
  20029. return;
  20030. }
  20031. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20032. var subMesh = _a[_i];
  20033. if (subMesh._materialDefines) {
  20034. func(subMesh._materialDefines);
  20035. }
  20036. }
  20037. };
  20038. /** @hidden */
  20039. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20040. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20041. };
  20042. /** @hidden */
  20043. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20044. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20045. };
  20046. /** @hidden */
  20047. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20048. if (!this.subMeshes) {
  20049. return;
  20050. }
  20051. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20052. var subMesh = _a[_i];
  20053. var material = subMesh.getMaterial();
  20054. if (material) {
  20055. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20056. }
  20057. }
  20058. };
  20059. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20060. /**
  20061. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20062. */
  20063. get: function () {
  20064. return this._scaling;
  20065. },
  20066. set: function (newScaling) {
  20067. this._scaling = newScaling;
  20068. if (this.physicsImpostor) {
  20069. this.physicsImpostor.forceUpdate();
  20070. }
  20071. },
  20072. enumerable: true,
  20073. configurable: true
  20074. });
  20075. // Methods
  20076. /**
  20077. * Disables the mesh edge rendering mode
  20078. * @returns the currentAbstractMesh
  20079. */
  20080. AbstractMesh.prototype.disableEdgesRendering = function () {
  20081. if (this._edgesRenderer) {
  20082. this._edgesRenderer.dispose();
  20083. this._edgesRenderer = null;
  20084. }
  20085. return this;
  20086. };
  20087. /**
  20088. * Enables the edge rendering mode on the mesh.
  20089. * This mode makes the mesh edges visible
  20090. * @param epsilon defines the maximal distance between two angles to detect a face
  20091. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20092. * @returns the currentAbstractMesh
  20093. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20094. */
  20095. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20096. if (epsilon === void 0) { epsilon = 0.95; }
  20097. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20098. this.disableEdgesRendering();
  20099. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20100. return this;
  20101. };
  20102. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20103. /**
  20104. * Returns true if the mesh is blocked. Implemented by child classes
  20105. */
  20106. get: function () {
  20107. return false;
  20108. },
  20109. enumerable: true,
  20110. configurable: true
  20111. });
  20112. /**
  20113. * Returns the mesh itself by default. Implemented by child classes
  20114. * @param camera defines the camera to use to pick the right LOD level
  20115. * @returns the currentAbstractMesh
  20116. */
  20117. AbstractMesh.prototype.getLOD = function (camera) {
  20118. return this;
  20119. };
  20120. /**
  20121. * Returns 0 by default. Implemented by child classes
  20122. * @returns an integer
  20123. */
  20124. AbstractMesh.prototype.getTotalVertices = function () {
  20125. return 0;
  20126. };
  20127. /**
  20128. * Returns null by default. Implemented by child classes
  20129. * @returns null
  20130. */
  20131. AbstractMesh.prototype.getIndices = function () {
  20132. return null;
  20133. };
  20134. /**
  20135. * Returns the array of the requested vertex data kind. Implemented by child classes
  20136. * @param kind defines the vertex data kind to use
  20137. * @returns null
  20138. */
  20139. AbstractMesh.prototype.getVerticesData = function (kind) {
  20140. return null;
  20141. };
  20142. /**
  20143. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20144. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20145. * Note that a new underlying VertexBuffer object is created each call.
  20146. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20147. * @param kind defines vertex data kind:
  20148. * * BABYLON.VertexBuffer.PositionKind
  20149. * * BABYLON.VertexBuffer.UVKind
  20150. * * BABYLON.VertexBuffer.UV2Kind
  20151. * * BABYLON.VertexBuffer.UV3Kind
  20152. * * BABYLON.VertexBuffer.UV4Kind
  20153. * * BABYLON.VertexBuffer.UV5Kind
  20154. * * BABYLON.VertexBuffer.UV6Kind
  20155. * * BABYLON.VertexBuffer.ColorKind
  20156. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20157. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20158. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20159. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20160. * @param data defines the data source
  20161. * @param updatable defines if the data must be flagged as updatable (or static)
  20162. * @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
  20163. * @returns the current mesh
  20164. */
  20165. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20166. return this;
  20167. };
  20168. /**
  20169. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20170. * If the mesh has no geometry, it is simply returned as it is.
  20171. * @param kind defines vertex data kind:
  20172. * * BABYLON.VertexBuffer.PositionKind
  20173. * * BABYLON.VertexBuffer.UVKind
  20174. * * BABYLON.VertexBuffer.UV2Kind
  20175. * * BABYLON.VertexBuffer.UV3Kind
  20176. * * BABYLON.VertexBuffer.UV4Kind
  20177. * * BABYLON.VertexBuffer.UV5Kind
  20178. * * BABYLON.VertexBuffer.UV6Kind
  20179. * * BABYLON.VertexBuffer.ColorKind
  20180. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20181. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20182. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20183. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20184. * @param data defines the data source
  20185. * @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
  20186. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20187. * @returns the current mesh
  20188. */
  20189. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20190. return this;
  20191. };
  20192. /**
  20193. * Sets the mesh indices,
  20194. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20195. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20196. * @param totalVertices Defines the total number of vertices
  20197. * @returns the current mesh
  20198. */
  20199. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20200. return this;
  20201. };
  20202. /**
  20203. * Gets a boolean indicating if specific vertex data is present
  20204. * @param kind defines the vertex data kind to use
  20205. * @returns true is data kind is present
  20206. */
  20207. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20208. return false;
  20209. };
  20210. /**
  20211. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20212. * @returns a BoundingInfo
  20213. */
  20214. AbstractMesh.prototype.getBoundingInfo = function () {
  20215. if (this._masterMesh) {
  20216. return this._masterMesh.getBoundingInfo();
  20217. }
  20218. if (!this._boundingInfo) {
  20219. // this._boundingInfo is being created here
  20220. this._updateBoundingInfo();
  20221. }
  20222. // cannot be null.
  20223. return this._boundingInfo;
  20224. };
  20225. /**
  20226. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20227. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20228. * @returns the current mesh
  20229. */
  20230. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20231. if (includeDescendants === void 0) { includeDescendants = true; }
  20232. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20233. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20234. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20235. if (maxDimension === 0) {
  20236. return this;
  20237. }
  20238. var scale = 1 / maxDimension;
  20239. this.scaling.scaleInPlace(scale);
  20240. return this;
  20241. };
  20242. /**
  20243. * Overwrite the current bounding info
  20244. * @param boundingInfo defines the new bounding info
  20245. * @returns the current mesh
  20246. */
  20247. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20248. this._boundingInfo = boundingInfo;
  20249. return this;
  20250. };
  20251. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20252. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20253. get: function () {
  20254. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. /** @hidden */
  20260. AbstractMesh.prototype._preActivate = function () {
  20261. };
  20262. /** @hidden */
  20263. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20264. };
  20265. /** @hidden */
  20266. AbstractMesh.prototype._activate = function (renderId) {
  20267. this._renderId = renderId;
  20268. };
  20269. /**
  20270. * Gets the current world matrix
  20271. * @returns a Matrix
  20272. */
  20273. AbstractMesh.prototype.getWorldMatrix = function () {
  20274. if (this._masterMesh) {
  20275. return this._masterMesh.getWorldMatrix();
  20276. }
  20277. return _super.prototype.getWorldMatrix.call(this);
  20278. };
  20279. /** @hidden */
  20280. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20281. if (this._masterMesh) {
  20282. return this._masterMesh._getWorldMatrixDeterminant();
  20283. }
  20284. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20285. };
  20286. // ================================== Point of View Movement =================================
  20287. /**
  20288. * Perform relative position change from the point of view of behind the front of the mesh.
  20289. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20290. * Supports definition of mesh facing forward or backward
  20291. * @param amountRight defines the distance on the right axis
  20292. * @param amountUp defines the distance on the up axis
  20293. * @param amountForward defines the distance on the forward axis
  20294. * @returns the current mesh
  20295. */
  20296. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20297. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20298. return this;
  20299. };
  20300. /**
  20301. * Calculate relative position change from the point of view of behind the front of the mesh.
  20302. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20303. * Supports definition of mesh facing forward or backward
  20304. * @param amountRight defines the distance on the right axis
  20305. * @param amountUp defines the distance on the up axis
  20306. * @param amountForward defines the distance on the forward axis
  20307. * @returns the new displacement vector
  20308. */
  20309. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20310. var rotMatrix = new BABYLON.Matrix();
  20311. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20312. rotQuaternion.toRotationMatrix(rotMatrix);
  20313. var translationDelta = BABYLON.Vector3.Zero();
  20314. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20315. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20316. return translationDelta;
  20317. };
  20318. // ================================== Point of View Rotation =================================
  20319. /**
  20320. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20321. * Supports definition of mesh facing forward or backward
  20322. * @param flipBack defines the flip
  20323. * @param twirlClockwise defines the twirl
  20324. * @param tiltRight defines the tilt
  20325. * @returns the current mesh
  20326. */
  20327. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20328. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20329. return this;
  20330. };
  20331. /**
  20332. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20333. * Supports definition of mesh facing forward or backward.
  20334. * @param flipBack defines the flip
  20335. * @param twirlClockwise defines the twirl
  20336. * @param tiltRight defines the tilt
  20337. * @returns the new rotation vector
  20338. */
  20339. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20340. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20341. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20342. };
  20343. /**
  20344. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20345. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20346. * @returns the new bounding vectors
  20347. */
  20348. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants) {
  20349. if (includeDescendants === void 0) { includeDescendants = true; }
  20350. // Ensures that all world matrix will be recomputed.
  20351. this.getScene().incrementRenderId();
  20352. this.computeWorldMatrix(true);
  20353. var min;
  20354. var max;
  20355. var boundingInfo = this.getBoundingInfo();
  20356. if (!this.subMeshes) {
  20357. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20358. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20359. }
  20360. else {
  20361. min = boundingInfo.boundingBox.minimumWorld;
  20362. max = boundingInfo.boundingBox.maximumWorld;
  20363. }
  20364. if (includeDescendants) {
  20365. var descendants = this.getDescendants(false);
  20366. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20367. var descendant = descendants_1[_i];
  20368. var childMesh = descendant;
  20369. childMesh.computeWorldMatrix(true);
  20370. //make sure we have the needed params to get mix and max
  20371. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20372. continue;
  20373. }
  20374. var childBoundingInfo = childMesh.getBoundingInfo();
  20375. var boundingBox = childBoundingInfo.boundingBox;
  20376. var minBox = boundingBox.minimumWorld;
  20377. var maxBox = boundingBox.maximumWorld;
  20378. BABYLON.Tools.CheckExtends(minBox, min, max);
  20379. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20380. }
  20381. }
  20382. return {
  20383. min: min,
  20384. max: max
  20385. };
  20386. };
  20387. /** @hidden */
  20388. AbstractMesh.prototype._updateBoundingInfo = function () {
  20389. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20390. this._boundingInfo.update(this.worldMatrixFromCache);
  20391. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20392. return this;
  20393. };
  20394. /** @hidden */
  20395. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20396. if (!this.subMeshes) {
  20397. return this;
  20398. }
  20399. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20400. var subMesh = this.subMeshes[subIndex];
  20401. if (!subMesh.IsGlobal) {
  20402. subMesh.updateBoundingInfo(matrix);
  20403. }
  20404. }
  20405. return this;
  20406. };
  20407. /** @hidden */
  20408. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20409. // Bounding info
  20410. this._updateBoundingInfo();
  20411. };
  20412. /**
  20413. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20414. * A mesh is in the frustum if its bounding box intersects the frustum
  20415. * @param frustumPlanes defines the frustum to test
  20416. * @returns true if the mesh is in the frustum planes
  20417. */
  20418. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20419. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20420. };
  20421. /**
  20422. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20423. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20424. * @param frustumPlanes defines the frustum to test
  20425. * @returns true if the mesh is completely in the frustum planes
  20426. */
  20427. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20428. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20429. };
  20430. /**
  20431. * True if the mesh intersects another mesh or a SolidParticle object
  20432. * @param mesh defines a target mesh or SolidParticle to test
  20433. * @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)
  20434. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20435. * @returns true if there is an intersection
  20436. */
  20437. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20438. if (precise === void 0) { precise = false; }
  20439. if (!this._boundingInfo || !mesh._boundingInfo) {
  20440. return false;
  20441. }
  20442. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20443. return true;
  20444. }
  20445. if (includeDescendants) {
  20446. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20447. var child = _a[_i];
  20448. if (child.intersectsMesh(mesh, precise, true)) {
  20449. return true;
  20450. }
  20451. }
  20452. }
  20453. return false;
  20454. };
  20455. /**
  20456. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20457. * @param point defines the point to test
  20458. * @returns true if there is an intersection
  20459. */
  20460. AbstractMesh.prototype.intersectsPoint = function (point) {
  20461. if (!this._boundingInfo) {
  20462. return false;
  20463. }
  20464. return this._boundingInfo.intersectsPoint(point);
  20465. };
  20466. /**
  20467. * Gets the current physics impostor
  20468. * @see http://doc.babylonjs.com/features/physics_engine
  20469. * @returns a physics impostor or null
  20470. */
  20471. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20472. return this.physicsImpostor;
  20473. };
  20474. /**
  20475. * Gets the position of the current mesh in camera space
  20476. * @param camera defines the camera to use
  20477. * @returns a position
  20478. */
  20479. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20480. if (camera === void 0) { camera = null; }
  20481. if (!camera) {
  20482. camera = this.getScene().activeCamera;
  20483. }
  20484. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20485. };
  20486. /**
  20487. * Returns the distance from the mesh to the active camera
  20488. * @param camera defines the camera to use
  20489. * @returns the distance
  20490. */
  20491. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20492. if (camera === void 0) { camera = null; }
  20493. if (!camera) {
  20494. camera = this.getScene().activeCamera;
  20495. }
  20496. return this.absolutePosition.subtract(camera.position).length();
  20497. };
  20498. /**
  20499. * Apply a physic impulse to the mesh
  20500. * @param force defines the force to apply
  20501. * @param contactPoint defines where to apply the force
  20502. * @returns the current mesh
  20503. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20504. */
  20505. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20506. if (!this.physicsImpostor) {
  20507. return this;
  20508. }
  20509. this.physicsImpostor.applyImpulse(force, contactPoint);
  20510. return this;
  20511. };
  20512. /**
  20513. * Creates a physic joint between two meshes
  20514. * @param otherMesh defines the other mesh to use
  20515. * @param pivot1 defines the pivot to use on this mesh
  20516. * @param pivot2 defines the pivot to use on the other mesh
  20517. * @param options defines additional options (can be plugin dependent)
  20518. * @returns the current mesh
  20519. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20520. */
  20521. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20522. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20523. return this;
  20524. }
  20525. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20526. mainPivot: pivot1,
  20527. connectedPivot: pivot2,
  20528. nativeParams: options
  20529. });
  20530. return this;
  20531. };
  20532. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20533. // Collisions
  20534. /**
  20535. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20536. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20537. */
  20538. get: function () {
  20539. return this._checkCollisions;
  20540. },
  20541. set: function (collisionEnabled) {
  20542. this._checkCollisions = collisionEnabled;
  20543. if (this.getScene().workerCollisions) {
  20544. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20545. }
  20546. },
  20547. enumerable: true,
  20548. configurable: true
  20549. });
  20550. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20551. /**
  20552. * Gets Collider object used to compute collisions (not physics)
  20553. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20554. */
  20555. get: function () {
  20556. return this._collider;
  20557. },
  20558. enumerable: true,
  20559. configurable: true
  20560. });
  20561. /**
  20562. * Move the mesh using collision engine
  20563. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20564. * @param displacement defines the requested displacement vector
  20565. * @returns the current mesh
  20566. */
  20567. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20568. var globalPosition = this.getAbsolutePosition();
  20569. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20570. if (!this._collider) {
  20571. this._collider = new BABYLON.Collider();
  20572. }
  20573. this._collider._radius = this.ellipsoid;
  20574. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20575. return this;
  20576. };
  20577. // Submeshes octree
  20578. /**
  20579. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20580. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20581. * @param maxCapacity defines the maximum size of each block (64 by default)
  20582. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20583. * @returns the new octree
  20584. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20585. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20586. */
  20587. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20588. if (maxCapacity === void 0) { maxCapacity = 64; }
  20589. if (maxDepth === void 0) { maxDepth = 2; }
  20590. if (!this._submeshesOctree) {
  20591. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20592. }
  20593. this.computeWorldMatrix(true);
  20594. var boundingInfo = this.getBoundingInfo();
  20595. // Update octree
  20596. var bbox = boundingInfo.boundingBox;
  20597. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20598. return this._submeshesOctree;
  20599. };
  20600. // Collisions
  20601. /** @hidden */
  20602. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20603. this._generatePointsArray();
  20604. if (!this._positions) {
  20605. return this;
  20606. }
  20607. // Transformation
  20608. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20609. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20610. subMesh._lastColliderWorldVertices = [];
  20611. subMesh._trianglePlanes = [];
  20612. var start = subMesh.verticesStart;
  20613. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20614. for (var i = start; i < end; i++) {
  20615. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20616. }
  20617. }
  20618. // Collide
  20619. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20620. if (collider.collisionFound) {
  20621. collider.collidedMesh = this;
  20622. }
  20623. return this;
  20624. };
  20625. /** @hidden */
  20626. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20627. var subMeshes;
  20628. var len;
  20629. // Octrees
  20630. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20631. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20632. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20633. len = intersections.length;
  20634. subMeshes = intersections.data;
  20635. }
  20636. else {
  20637. subMeshes = this.subMeshes;
  20638. len = subMeshes.length;
  20639. }
  20640. for (var index = 0; index < len; index++) {
  20641. var subMesh = subMeshes[index];
  20642. // Bounding test
  20643. if (len > 1 && !subMesh._checkCollision(collider))
  20644. continue;
  20645. this._collideForSubMesh(subMesh, transformMatrix, collider);
  20646. }
  20647. return this;
  20648. };
  20649. /** @hidden */
  20650. AbstractMesh.prototype._checkCollision = function (collider) {
  20651. // Bounding box test
  20652. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  20653. return this;
  20654. // Transformation matrix
  20655. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  20656. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  20657. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  20658. return this;
  20659. };
  20660. // Picking
  20661. /** @hidden */
  20662. AbstractMesh.prototype._generatePointsArray = function () {
  20663. return false;
  20664. };
  20665. /**
  20666. * Checks if the passed Ray intersects with the mesh
  20667. * @param ray defines the ray to use
  20668. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  20669. * @returns the picking info
  20670. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  20671. */
  20672. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  20673. var pickingInfo = new BABYLON.PickingInfo();
  20674. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  20675. return pickingInfo;
  20676. }
  20677. if (!this._generatePointsArray()) {
  20678. return pickingInfo;
  20679. }
  20680. var intersectInfo = null;
  20681. // Octrees
  20682. var subMeshes;
  20683. var len;
  20684. if (this._submeshesOctree && this.useOctreeForPicking) {
  20685. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  20686. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  20687. len = intersections.length;
  20688. subMeshes = intersections.data;
  20689. }
  20690. else {
  20691. subMeshes = this.subMeshes;
  20692. len = subMeshes.length;
  20693. }
  20694. for (var index = 0; index < len; index++) {
  20695. var subMesh = subMeshes[index];
  20696. // Bounding test
  20697. if (len > 1 && !subMesh.canIntersects(ray))
  20698. continue;
  20699. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  20700. if (currentIntersectInfo) {
  20701. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  20702. intersectInfo = currentIntersectInfo;
  20703. intersectInfo.subMeshId = index;
  20704. if (fastCheck) {
  20705. break;
  20706. }
  20707. }
  20708. }
  20709. }
  20710. if (intersectInfo) {
  20711. // Get picked point
  20712. var world = this.getWorldMatrix();
  20713. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  20714. var direction = ray.direction.clone();
  20715. direction = direction.scale(intersectInfo.distance);
  20716. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  20717. var pickedPoint = worldOrigin.add(worldDirection);
  20718. // Return result
  20719. pickingInfo.hit = true;
  20720. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  20721. pickingInfo.pickedPoint = pickedPoint;
  20722. pickingInfo.pickedMesh = this;
  20723. pickingInfo.bu = intersectInfo.bu || 0;
  20724. pickingInfo.bv = intersectInfo.bv || 0;
  20725. pickingInfo.faceId = intersectInfo.faceId;
  20726. pickingInfo.subMeshId = intersectInfo.subMeshId;
  20727. return pickingInfo;
  20728. }
  20729. return pickingInfo;
  20730. };
  20731. /**
  20732. * Clones the current mesh
  20733. * @param name defines the mesh name
  20734. * @param newParent defines the new mesh parent
  20735. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  20736. * @returns the new mesh
  20737. */
  20738. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  20739. return null;
  20740. };
  20741. /**
  20742. * Disposes all the submeshes of the current meshnp
  20743. * @returns the current mesh
  20744. */
  20745. AbstractMesh.prototype.releaseSubMeshes = function () {
  20746. if (this.subMeshes) {
  20747. while (this.subMeshes.length) {
  20748. this.subMeshes[0].dispose();
  20749. }
  20750. }
  20751. else {
  20752. this.subMeshes = new Array();
  20753. }
  20754. return this;
  20755. };
  20756. /**
  20757. * Releases resources associated with this abstract mesh.
  20758. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  20759. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  20760. */
  20761. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  20762. var _this = this;
  20763. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  20764. var index;
  20765. // Smart Array Retainers.
  20766. this.getScene().freeActiveMeshes();
  20767. this.getScene().freeRenderingGroups();
  20768. // Action manager
  20769. if (this.actionManager !== undefined && this.actionManager !== null) {
  20770. this.actionManager.dispose();
  20771. this.actionManager = null;
  20772. }
  20773. // Skeleton
  20774. this._skeleton = null;
  20775. // Physics
  20776. if (this.physicsImpostor) {
  20777. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  20778. }
  20779. // Intersections in progress
  20780. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  20781. var other = this._intersectionsInProgress[index];
  20782. var pos = other._intersectionsInProgress.indexOf(this);
  20783. other._intersectionsInProgress.splice(pos, 1);
  20784. }
  20785. this._intersectionsInProgress = [];
  20786. // Lights
  20787. var lights = this.getScene().lights;
  20788. lights.forEach(function (light) {
  20789. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  20790. if (meshIndex !== -1) {
  20791. light.includedOnlyMeshes.splice(meshIndex, 1);
  20792. }
  20793. meshIndex = light.excludedMeshes.indexOf(_this);
  20794. if (meshIndex !== -1) {
  20795. light.excludedMeshes.splice(meshIndex, 1);
  20796. }
  20797. // Shadow generators
  20798. var generator = light.getShadowGenerator();
  20799. if (generator) {
  20800. var shadowMap = generator.getShadowMap();
  20801. if (shadowMap && shadowMap.renderList) {
  20802. meshIndex = shadowMap.renderList.indexOf(_this);
  20803. if (meshIndex !== -1) {
  20804. shadowMap.renderList.splice(meshIndex, 1);
  20805. }
  20806. }
  20807. }
  20808. });
  20809. // Edges
  20810. if (this._edgesRenderer) {
  20811. this._edgesRenderer.dispose();
  20812. this._edgesRenderer = null;
  20813. }
  20814. // SubMeshes
  20815. if (this.getClassName() !== "InstancedMesh") {
  20816. this.releaseSubMeshes();
  20817. }
  20818. // Octree
  20819. var sceneOctree = this.getScene().selectionOctree;
  20820. if (sceneOctree !== undefined && sceneOctree !== null) {
  20821. var index = sceneOctree.dynamicContent.indexOf(this);
  20822. if (index !== -1) {
  20823. sceneOctree.dynamicContent.splice(index, 1);
  20824. }
  20825. }
  20826. // Query
  20827. var engine = this.getScene().getEngine();
  20828. if (this._occlusionQuery) {
  20829. this._isOcclusionQueryInProgress = false;
  20830. engine.deleteQuery(this._occlusionQuery);
  20831. this._occlusionQuery = null;
  20832. }
  20833. // Engine
  20834. engine.wipeCaches();
  20835. // Remove from scene
  20836. this.getScene().removeMesh(this);
  20837. if (disposeMaterialAndTextures) {
  20838. if (this.material) {
  20839. this.material.dispose(false, true);
  20840. }
  20841. }
  20842. if (!doNotRecurse) {
  20843. // Particles
  20844. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  20845. if (this.getScene().particleSystems[index].emitter === this) {
  20846. this.getScene().particleSystems[index].dispose();
  20847. index--;
  20848. }
  20849. }
  20850. }
  20851. // facet data
  20852. if (this._facetDataEnabled) {
  20853. this.disableFacetData();
  20854. }
  20855. this.onAfterWorldMatrixUpdateObservable.clear();
  20856. this.onCollideObservable.clear();
  20857. this.onCollisionPositionChangeObservable.clear();
  20858. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  20859. };
  20860. /**
  20861. * Adds the passed mesh as a child to the current mesh
  20862. * @param mesh defines the child mesh
  20863. * @returns the current mesh
  20864. */
  20865. AbstractMesh.prototype.addChild = function (mesh) {
  20866. mesh.setParent(this);
  20867. return this;
  20868. };
  20869. /**
  20870. * Removes the passed mesh from the current mesh children list
  20871. * @param mesh defines the child mesh
  20872. * @returns the current mesh
  20873. */
  20874. AbstractMesh.prototype.removeChild = function (mesh) {
  20875. mesh.setParent(null);
  20876. return this;
  20877. };
  20878. // Facet data
  20879. /** @hidden */
  20880. AbstractMesh.prototype._initFacetData = function () {
  20881. if (!this._facetNormals) {
  20882. this._facetNormals = new Array();
  20883. }
  20884. if (!this._facetPositions) {
  20885. this._facetPositions = new Array();
  20886. }
  20887. if (!this._facetPartitioning) {
  20888. this._facetPartitioning = new Array();
  20889. }
  20890. this._facetNb = (this.getIndices().length / 3) | 0;
  20891. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  20892. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  20893. for (var f = 0; f < this._facetNb; f++) {
  20894. this._facetNormals[f] = BABYLON.Vector3.Zero();
  20895. this._facetPositions[f] = BABYLON.Vector3.Zero();
  20896. }
  20897. this._facetDataEnabled = true;
  20898. return this;
  20899. };
  20900. /**
  20901. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  20902. * This method can be called within the render loop.
  20903. * 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
  20904. * @returns the current mesh
  20905. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  20906. */
  20907. AbstractMesh.prototype.updateFacetData = function () {
  20908. if (!this._facetDataEnabled) {
  20909. this._initFacetData();
  20910. }
  20911. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  20912. var indices = this.getIndices();
  20913. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  20914. var bInfo = this.getBoundingInfo();
  20915. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  20916. // init arrays, matrix and sort function on first call
  20917. this._facetDepthSortEnabled = true;
  20918. if (indices instanceof Uint16Array) {
  20919. this._depthSortedIndices = new Uint16Array(indices);
  20920. }
  20921. else if (indices instanceof Uint32Array) {
  20922. this._depthSortedIndices = new Uint32Array(indices);
  20923. }
  20924. else {
  20925. var needs32bits = false;
  20926. for (var i = 0; i < indices.length; i++) {
  20927. if (indices[i] > 65535) {
  20928. needs32bits = true;
  20929. break;
  20930. }
  20931. }
  20932. if (needs32bits) {
  20933. this._depthSortedIndices = new Uint32Array(indices);
  20934. }
  20935. else {
  20936. this._depthSortedIndices = new Uint16Array(indices);
  20937. }
  20938. }
  20939. this._facetDepthSortFunction = function (f1, f2) {
  20940. return (f2.sqDistance - f1.sqDistance);
  20941. };
  20942. if (!this._facetDepthSortFrom) {
  20943. var camera = this.getScene().activeCamera;
  20944. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  20945. }
  20946. this._depthSortedFacets = [];
  20947. for (var f = 0; f < this._facetNb; f++) {
  20948. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  20949. this._depthSortedFacets.push(depthSortedFacet);
  20950. }
  20951. this._invertedMatrix = BABYLON.Matrix.Identity();
  20952. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  20953. }
  20954. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  20955. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  20956. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  20957. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  20958. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  20959. this._subDiv.max = this._partitioningSubdivisions;
  20960. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  20961. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  20962. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  20963. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  20964. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  20965. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  20966. // set the parameters for ComputeNormals()
  20967. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  20968. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  20969. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  20970. this._facetParameters.bInfo = bInfo;
  20971. this._facetParameters.bbSize = this._bbSize;
  20972. this._facetParameters.subDiv = this._subDiv;
  20973. this._facetParameters.ratio = this.partitioningBBoxRatio;
  20974. this._facetParameters.depthSort = this._facetDepthSort;
  20975. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20976. this.computeWorldMatrix(true);
  20977. this._worldMatrix.invertToRef(this._invertedMatrix);
  20978. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  20979. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  20980. }
  20981. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  20982. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  20983. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  20984. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  20985. var l = (this._depthSortedIndices.length / 3) | 0;
  20986. for (var f = 0; f < l; f++) {
  20987. var sind = this._depthSortedFacets[f].ind;
  20988. this._depthSortedIndices[f * 3] = indices[sind];
  20989. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  20990. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  20991. }
  20992. this.updateIndices(this._depthSortedIndices);
  20993. }
  20994. return this;
  20995. };
  20996. /**
  20997. * Returns the facetLocalNormals array.
  20998. * The normals are expressed in the mesh local spac
  20999. * @returns an array of Vector3
  21000. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21001. */
  21002. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21003. if (!this._facetNormals) {
  21004. this.updateFacetData();
  21005. }
  21006. return this._facetNormals;
  21007. };
  21008. /**
  21009. * Returns the facetLocalPositions array.
  21010. * The facet positions are expressed in the mesh local space
  21011. * @returns an array of Vector3
  21012. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21013. */
  21014. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21015. if (!this._facetPositions) {
  21016. this.updateFacetData();
  21017. }
  21018. return this._facetPositions;
  21019. };
  21020. /**
  21021. * Returns the facetLocalPartioning array
  21022. * @returns an array of array of numbers
  21023. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21024. */
  21025. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21026. if (!this._facetPartitioning) {
  21027. this.updateFacetData();
  21028. }
  21029. return this._facetPartitioning;
  21030. };
  21031. /**
  21032. * Returns the i-th facet position in the world system.
  21033. * This method allocates a new Vector3 per call
  21034. * @param i defines the facet index
  21035. * @returns a new Vector3
  21036. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21037. */
  21038. AbstractMesh.prototype.getFacetPosition = function (i) {
  21039. var pos = BABYLON.Vector3.Zero();
  21040. this.getFacetPositionToRef(i, pos);
  21041. return pos;
  21042. };
  21043. /**
  21044. * Sets the reference Vector3 with the i-th facet position in the world system
  21045. * @param i defines the facet index
  21046. * @param ref defines the target vector
  21047. * @returns the current mesh
  21048. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21049. */
  21050. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21051. var localPos = (this.getFacetLocalPositions())[i];
  21052. var world = this.getWorldMatrix();
  21053. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21054. return this;
  21055. };
  21056. /**
  21057. * Returns the i-th facet normal in the world system.
  21058. * This method allocates a new Vector3 per call
  21059. * @param i defines the facet index
  21060. * @returns a new Vector3
  21061. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21062. */
  21063. AbstractMesh.prototype.getFacetNormal = function (i) {
  21064. var norm = BABYLON.Vector3.Zero();
  21065. this.getFacetNormalToRef(i, norm);
  21066. return norm;
  21067. };
  21068. /**
  21069. * Sets the reference Vector3 with the i-th facet normal in the world system
  21070. * @param i defines the facet index
  21071. * @param ref defines the target vector
  21072. * @returns the current mesh
  21073. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21074. */
  21075. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21076. var localNorm = (this.getFacetLocalNormals())[i];
  21077. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21078. return this;
  21079. };
  21080. /**
  21081. * 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)
  21082. * @param x defines x coordinate
  21083. * @param y defines y coordinate
  21084. * @param z defines z coordinate
  21085. * @returns the array of facet indexes
  21086. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21087. */
  21088. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21089. var bInfo = this.getBoundingInfo();
  21090. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21091. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21092. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21093. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21094. return null;
  21095. }
  21096. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21097. };
  21098. /**
  21099. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21100. * @param projected sets as the (x,y,z) world projection on the facet
  21101. * @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
  21102. * @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
  21103. * @param x defines x coordinate
  21104. * @param y defines y coordinate
  21105. * @param z defines z coordinate
  21106. * @returns the face index if found (or null instead)
  21107. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21108. */
  21109. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21110. if (checkFace === void 0) { checkFace = false; }
  21111. if (facing === void 0) { facing = true; }
  21112. var world = this.getWorldMatrix();
  21113. var invMat = BABYLON.Tmp.Matrix[5];
  21114. world.invertToRef(invMat);
  21115. var invVect = BABYLON.Tmp.Vector3[8];
  21116. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21117. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21118. if (projected) {
  21119. // tranform the local computed projected vector to world coordinates
  21120. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21121. }
  21122. return closest;
  21123. };
  21124. /**
  21125. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21126. * @param projected sets as the (x,y,z) local projection on the facet
  21127. * @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
  21128. * @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
  21129. * @param x defines x coordinate
  21130. * @param y defines y coordinate
  21131. * @param z defines z coordinate
  21132. * @returns the face index if found (or null instead)
  21133. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21134. */
  21135. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21136. if (checkFace === void 0) { checkFace = false; }
  21137. if (facing === void 0) { facing = true; }
  21138. var closest = null;
  21139. var tmpx = 0.0;
  21140. var tmpy = 0.0;
  21141. var tmpz = 0.0;
  21142. var d = 0.0; // tmp dot facet normal * facet position
  21143. var t0 = 0.0;
  21144. var projx = 0.0;
  21145. var projy = 0.0;
  21146. var projz = 0.0;
  21147. // Get all the facets in the same partitioning block than (x, y, z)
  21148. var facetPositions = this.getFacetLocalPositions();
  21149. var facetNormals = this.getFacetLocalNormals();
  21150. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21151. if (!facetsInBlock) {
  21152. return null;
  21153. }
  21154. // Get the closest facet to (x, y, z)
  21155. var shortest = Number.MAX_VALUE; // init distance vars
  21156. var tmpDistance = shortest;
  21157. var fib; // current facet in the block
  21158. var norm; // current facet normal
  21159. var p0; // current facet barycenter position
  21160. // loop on all the facets in the current partitioning block
  21161. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21162. fib = facetsInBlock[idx];
  21163. norm = facetNormals[fib];
  21164. p0 = facetPositions[fib];
  21165. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21166. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21167. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21168. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21169. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21170. projx = x + norm.x * t0;
  21171. projy = y + norm.y * t0;
  21172. projz = z + norm.z * t0;
  21173. tmpx = projx - x;
  21174. tmpy = projy - y;
  21175. tmpz = projz - z;
  21176. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21177. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21178. shortest = tmpDistance;
  21179. closest = fib;
  21180. if (projected) {
  21181. projected.x = projx;
  21182. projected.y = projy;
  21183. projected.z = projz;
  21184. }
  21185. }
  21186. }
  21187. }
  21188. return closest;
  21189. };
  21190. /**
  21191. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21192. * @returns the parameters
  21193. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21194. */
  21195. AbstractMesh.prototype.getFacetDataParameters = function () {
  21196. return this._facetParameters;
  21197. };
  21198. /**
  21199. * Disables the feature FacetData and frees the related memory
  21200. * @returns the current mesh
  21201. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21202. */
  21203. AbstractMesh.prototype.disableFacetData = function () {
  21204. if (this._facetDataEnabled) {
  21205. this._facetDataEnabled = false;
  21206. this._facetPositions = new Array();
  21207. this._facetNormals = new Array();
  21208. this._facetPartitioning = new Array();
  21209. this._facetParameters = null;
  21210. this._depthSortedIndices = new Uint32Array(0);
  21211. }
  21212. return this;
  21213. };
  21214. /**
  21215. * Updates the AbstractMesh indices array
  21216. * @param indices defines the data source
  21217. * @returns the current mesh
  21218. */
  21219. AbstractMesh.prototype.updateIndices = function (indices) {
  21220. return this;
  21221. };
  21222. /**
  21223. * Creates new normals data for the mesh
  21224. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21225. * @returns the current mesh
  21226. */
  21227. AbstractMesh.prototype.createNormals = function (updatable) {
  21228. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21229. var indices = this.getIndices();
  21230. var normals;
  21231. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21232. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21233. }
  21234. else {
  21235. normals = [];
  21236. }
  21237. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21238. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21239. return this;
  21240. };
  21241. /**
  21242. * Align the mesh with a normal
  21243. * @param normal defines the normal to use
  21244. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21245. * @returns the current mesh
  21246. */
  21247. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21248. if (!upDirection) {
  21249. upDirection = BABYLON.Axis.Y;
  21250. }
  21251. var axisX = BABYLON.Tmp.Vector3[0];
  21252. var axisZ = BABYLON.Tmp.Vector3[1];
  21253. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21254. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21255. if (this.rotationQuaternion) {
  21256. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21257. }
  21258. else {
  21259. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21260. }
  21261. return this;
  21262. };
  21263. /** @hidden */
  21264. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21265. var engine = this.getEngine();
  21266. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21267. this._isOccluded = false;
  21268. return;
  21269. }
  21270. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21271. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21272. if (isOcclusionQueryAvailable) {
  21273. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21274. this._isOcclusionQueryInProgress = false;
  21275. this._occlusionInternalRetryCounter = 0;
  21276. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21277. }
  21278. else {
  21279. this._occlusionInternalRetryCounter++;
  21280. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21281. this._isOcclusionQueryInProgress = false;
  21282. this._occlusionInternalRetryCounter = 0;
  21283. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21284. // if strict continue the last state of the object.
  21285. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21286. }
  21287. else {
  21288. return;
  21289. }
  21290. }
  21291. }
  21292. var scene = this.getScene();
  21293. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21294. if (!this._occlusionQuery) {
  21295. this._occlusionQuery = engine.createQuery();
  21296. }
  21297. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21298. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21299. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21300. this._isOcclusionQueryInProgress = true;
  21301. };
  21302. /** No occlusion */
  21303. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21304. /** Occlusion set to optimisitic */
  21305. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21306. /** Occlusion set to strict */
  21307. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21308. /** Use an accurante occlusion algorithm */
  21309. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21310. /** Use a conservative occlusion algorithm */
  21311. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21312. return AbstractMesh;
  21313. }(BABYLON.TransformNode));
  21314. BABYLON.AbstractMesh = AbstractMesh;
  21315. })(BABYLON || (BABYLON = {}));
  21316. //# sourceMappingURL=babylon.abstractMesh.js.map
  21317. var BABYLON;
  21318. (function (BABYLON) {
  21319. /**
  21320. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21321. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21322. * 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.
  21323. */
  21324. var Light = /** @class */ (function (_super) {
  21325. __extends(Light, _super);
  21326. /**
  21327. * Creates a Light object in the scene.
  21328. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21329. * @param name The firendly name of the light
  21330. * @param scene The scene the light belongs too
  21331. */
  21332. function Light(name, scene) {
  21333. var _this = _super.call(this, name, scene) || this;
  21334. /**
  21335. * Diffuse gives the basic color to an object.
  21336. */
  21337. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21338. /**
  21339. * Specular produces a highlight color on an object.
  21340. * Note: This is note affecting PBR materials.
  21341. */
  21342. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21343. /**
  21344. * Strength of the light.
  21345. * Note: By default it is define in the framework own unit.
  21346. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21347. */
  21348. _this.intensity = 1.0;
  21349. /**
  21350. * Defines how far from the source the light is impacting in scene units.
  21351. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21352. */
  21353. _this.range = Number.MAX_VALUE;
  21354. /**
  21355. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21356. * of light.
  21357. */
  21358. _this._photometricScale = 1.0;
  21359. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21360. _this._radius = 0.00001;
  21361. /**
  21362. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21363. * exceeding the number allowed of the materials.
  21364. */
  21365. _this.renderPriority = 0;
  21366. /**
  21367. * Defines wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21368. * the current shadow generator.
  21369. */
  21370. _this.shadowEnabled = true;
  21371. _this._excludeWithLayerMask = 0;
  21372. _this._includeOnlyWithLayerMask = 0;
  21373. _this._lightmapMode = 0;
  21374. /**
  21375. * @hidden Internal use only.
  21376. */
  21377. _this._excludedMeshesIds = new Array();
  21378. /**
  21379. * @hidden Internal use only.
  21380. */
  21381. _this._includedOnlyMeshesIds = new Array();
  21382. _this.getScene().addLight(_this);
  21383. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21384. _this._buildUniformLayout();
  21385. _this.includedOnlyMeshes = new Array();
  21386. _this.excludedMeshes = new Array();
  21387. _this._resyncMeshes();
  21388. return _this;
  21389. }
  21390. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21391. /**
  21392. * If every light affecting the material is in this lightmapMode,
  21393. * material.lightmapTexture adds or multiplies
  21394. * (depends on material.useLightmapAsShadowmap)
  21395. * after every other light calculations.
  21396. */
  21397. get: function () {
  21398. return Light._LIGHTMAP_DEFAULT;
  21399. },
  21400. enumerable: true,
  21401. configurable: true
  21402. });
  21403. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21404. /**
  21405. * material.lightmapTexture as only diffuse lighting from this light
  21406. * adds only specular lighting from this light
  21407. * adds dynamic shadows
  21408. */
  21409. get: function () {
  21410. return Light._LIGHTMAP_SPECULAR;
  21411. },
  21412. enumerable: true,
  21413. configurable: true
  21414. });
  21415. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21416. /**
  21417. * material.lightmapTexture as only lighting
  21418. * no light calculation from this light
  21419. * only adds dynamic shadows from this light
  21420. */
  21421. get: function () {
  21422. return Light._LIGHTMAP_SHADOWSONLY;
  21423. },
  21424. enumerable: true,
  21425. configurable: true
  21426. });
  21427. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21428. /**
  21429. * Each light type uses the default quantity according to its type:
  21430. * point/spot lights use luminous intensity
  21431. * directional lights use illuminance
  21432. */
  21433. get: function () {
  21434. return Light._INTENSITYMODE_AUTOMATIC;
  21435. },
  21436. enumerable: true,
  21437. configurable: true
  21438. });
  21439. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21440. /**
  21441. * lumen (lm)
  21442. */
  21443. get: function () {
  21444. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21445. },
  21446. enumerable: true,
  21447. configurable: true
  21448. });
  21449. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21450. /**
  21451. * candela (lm/sr)
  21452. */
  21453. get: function () {
  21454. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21455. },
  21456. enumerable: true,
  21457. configurable: true
  21458. });
  21459. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21460. /**
  21461. * lux (lm/m^2)
  21462. */
  21463. get: function () {
  21464. return Light._INTENSITYMODE_ILLUMINANCE;
  21465. },
  21466. enumerable: true,
  21467. configurable: true
  21468. });
  21469. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21470. /**
  21471. * nit (cd/m^2)
  21472. */
  21473. get: function () {
  21474. return Light._INTENSITYMODE_LUMINANCE;
  21475. },
  21476. enumerable: true,
  21477. configurable: true
  21478. });
  21479. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21480. /**
  21481. * Light type const id of the point light.
  21482. */
  21483. get: function () {
  21484. return Light._LIGHTTYPEID_POINTLIGHT;
  21485. },
  21486. enumerable: true,
  21487. configurable: true
  21488. });
  21489. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21490. /**
  21491. * Light type const id of the directional light.
  21492. */
  21493. get: function () {
  21494. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21495. },
  21496. enumerable: true,
  21497. configurable: true
  21498. });
  21499. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21500. /**
  21501. * Light type const id of the spot light.
  21502. */
  21503. get: function () {
  21504. return Light._LIGHTTYPEID_SPOTLIGHT;
  21505. },
  21506. enumerable: true,
  21507. configurable: true
  21508. });
  21509. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21510. /**
  21511. * Light type const id of the hemispheric light.
  21512. */
  21513. get: function () {
  21514. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21515. },
  21516. enumerable: true,
  21517. configurable: true
  21518. });
  21519. Object.defineProperty(Light.prototype, "intensityMode", {
  21520. /**
  21521. * Gets the photometric scale used to interpret the intensity.
  21522. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21523. */
  21524. get: function () {
  21525. return this._intensityMode;
  21526. },
  21527. /**
  21528. * Sets the photometric scale used to interpret the intensity.
  21529. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21530. */
  21531. set: function (value) {
  21532. this._intensityMode = value;
  21533. this._computePhotometricScale();
  21534. },
  21535. enumerable: true,
  21536. configurable: true
  21537. });
  21538. ;
  21539. ;
  21540. Object.defineProperty(Light.prototype, "radius", {
  21541. /**
  21542. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21543. */
  21544. get: function () {
  21545. return this._radius;
  21546. },
  21547. /**
  21548. * sets the light radius used by PBR Materials to simulate soft area lights.
  21549. */
  21550. set: function (value) {
  21551. this._radius = value;
  21552. this._computePhotometricScale();
  21553. },
  21554. enumerable: true,
  21555. configurable: true
  21556. });
  21557. ;
  21558. ;
  21559. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21560. /**
  21561. * Gets the only meshes impacted by this light.
  21562. */
  21563. get: function () {
  21564. return this._includedOnlyMeshes;
  21565. },
  21566. /**
  21567. * Sets the only meshes impacted by this light.
  21568. */
  21569. set: function (value) {
  21570. this._includedOnlyMeshes = value;
  21571. this._hookArrayForIncludedOnly(value);
  21572. },
  21573. enumerable: true,
  21574. configurable: true
  21575. });
  21576. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21577. /**
  21578. * Gets the meshes not impacted by this light.
  21579. */
  21580. get: function () {
  21581. return this._excludedMeshes;
  21582. },
  21583. /**
  21584. * Sets the meshes not impacted by this light.
  21585. */
  21586. set: function (value) {
  21587. this._excludedMeshes = value;
  21588. this._hookArrayForExcluded(value);
  21589. },
  21590. enumerable: true,
  21591. configurable: true
  21592. });
  21593. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21594. /**
  21595. * Gets the layer id use to find what meshes are not impacted by the light.
  21596. * Inactive if 0
  21597. */
  21598. get: function () {
  21599. return this._excludeWithLayerMask;
  21600. },
  21601. /**
  21602. * Sets the layer id use to find what meshes are not impacted by the light.
  21603. * Inactive if 0
  21604. */
  21605. set: function (value) {
  21606. this._excludeWithLayerMask = value;
  21607. this._resyncMeshes();
  21608. },
  21609. enumerable: true,
  21610. configurable: true
  21611. });
  21612. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21613. /**
  21614. * Gets the layer id use to find what meshes are impacted by the light.
  21615. * Inactive if 0
  21616. */
  21617. get: function () {
  21618. return this._includeOnlyWithLayerMask;
  21619. },
  21620. /**
  21621. * Sets the layer id use to find what meshes are impacted by the light.
  21622. * Inactive if 0
  21623. */
  21624. set: function (value) {
  21625. this._includeOnlyWithLayerMask = value;
  21626. this._resyncMeshes();
  21627. },
  21628. enumerable: true,
  21629. configurable: true
  21630. });
  21631. Object.defineProperty(Light.prototype, "lightmapMode", {
  21632. /**
  21633. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21634. */
  21635. get: function () {
  21636. return this._lightmapMode;
  21637. },
  21638. /**
  21639. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  21640. */
  21641. set: function (value) {
  21642. if (this._lightmapMode === value) {
  21643. return;
  21644. }
  21645. this._lightmapMode = value;
  21646. this._markMeshesAsLightDirty();
  21647. },
  21648. enumerable: true,
  21649. configurable: true
  21650. });
  21651. /**
  21652. * Returns the string "Light".
  21653. * @returns the class name
  21654. */
  21655. Light.prototype.getClassName = function () {
  21656. return "Light";
  21657. };
  21658. /**
  21659. * Converts the light information to a readable string for debug purpose.
  21660. * @param fullDetails Supports for multiple levels of logging within scene loading
  21661. * @returns the human readable light info
  21662. */
  21663. Light.prototype.toString = function (fullDetails) {
  21664. var ret = "Name: " + this.name;
  21665. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  21666. if (this.animations) {
  21667. for (var i = 0; i < this.animations.length; i++) {
  21668. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  21669. }
  21670. }
  21671. if (fullDetails) {
  21672. }
  21673. return ret;
  21674. };
  21675. /**
  21676. * Set the enabled state of this node.
  21677. * @param value - the new enabled state
  21678. */
  21679. Light.prototype.setEnabled = function (value) {
  21680. _super.prototype.setEnabled.call(this, value);
  21681. this._resyncMeshes();
  21682. };
  21683. /**
  21684. * Returns the Light associated shadow generator if any.
  21685. * @return the associated shadow generator.
  21686. */
  21687. Light.prototype.getShadowGenerator = function () {
  21688. return this._shadowGenerator;
  21689. };
  21690. /**
  21691. * Returns a Vector3, the absolute light position in the World.
  21692. * @returns the world space position of the light
  21693. */
  21694. Light.prototype.getAbsolutePosition = function () {
  21695. return BABYLON.Vector3.Zero();
  21696. };
  21697. /**
  21698. * Specifies if the light will affect the passed mesh.
  21699. * @param mesh The mesh to test against the light
  21700. * @return true the mesh is affected otherwise, false.
  21701. */
  21702. Light.prototype.canAffectMesh = function (mesh) {
  21703. if (!mesh) {
  21704. return true;
  21705. }
  21706. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  21707. return false;
  21708. }
  21709. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  21710. return false;
  21711. }
  21712. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  21713. return false;
  21714. }
  21715. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  21716. return false;
  21717. }
  21718. return true;
  21719. };
  21720. /**
  21721. * Computes and Returns the light World matrix.
  21722. * @returns the world matrix
  21723. */
  21724. Light.prototype.getWorldMatrix = function () {
  21725. this._currentRenderId = this.getScene().getRenderId();
  21726. this._childRenderId = this._currentRenderId;
  21727. var worldMatrix = this._getWorldMatrix();
  21728. if (this.parent && this.parent.getWorldMatrix) {
  21729. if (!this._parentedWorldMatrix) {
  21730. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  21731. }
  21732. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  21733. this._markSyncedWithParent();
  21734. return this._parentedWorldMatrix;
  21735. }
  21736. return worldMatrix;
  21737. };
  21738. /**
  21739. * Sort function to order lights for rendering.
  21740. * @param a First Light object to compare to second.
  21741. * @param b Second Light object to compare first.
  21742. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  21743. */
  21744. Light.CompareLightsPriority = function (a, b) {
  21745. //shadow-casting lights have priority over non-shadow-casting lights
  21746. //the renderPrioirty is a secondary sort criterion
  21747. if (a.shadowEnabled !== b.shadowEnabled) {
  21748. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  21749. }
  21750. return b.renderPriority - a.renderPriority;
  21751. };
  21752. /**
  21753. * Releases resources associated with this node.
  21754. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21755. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21756. */
  21757. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21758. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21759. if (this._shadowGenerator) {
  21760. this._shadowGenerator.dispose();
  21761. this._shadowGenerator = null;
  21762. }
  21763. // Animations
  21764. this.getScene().stopAnimation(this);
  21765. // Remove from meshes
  21766. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21767. var mesh = _a[_i];
  21768. mesh._removeLightSource(this);
  21769. }
  21770. this._uniformBuffer.dispose();
  21771. // Remove from scene
  21772. this.getScene().removeLight(this);
  21773. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21774. };
  21775. /**
  21776. * Returns the light type ID (integer).
  21777. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  21778. */
  21779. Light.prototype.getTypeID = function () {
  21780. return 0;
  21781. };
  21782. /**
  21783. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  21784. * @returns the scaled intensity in intensity mode unit
  21785. */
  21786. Light.prototype.getScaledIntensity = function () {
  21787. return this._photometricScale * this.intensity;
  21788. };
  21789. /**
  21790. * Returns a new Light object, named "name", from the current one.
  21791. * @param name The name of the cloned light
  21792. * @returns the new created light
  21793. */
  21794. Light.prototype.clone = function (name) {
  21795. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  21796. if (!constructor) {
  21797. return null;
  21798. }
  21799. return BABYLON.SerializationHelper.Clone(constructor, this);
  21800. };
  21801. /**
  21802. * Serializes the current light into a Serialization object.
  21803. * @returns the serialized object.
  21804. */
  21805. Light.prototype.serialize = function () {
  21806. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  21807. // Type
  21808. serializationObject.type = this.getTypeID();
  21809. // Parent
  21810. if (this.parent) {
  21811. serializationObject.parentId = this.parent.id;
  21812. }
  21813. // Inclusion / exclusions
  21814. if (this.excludedMeshes.length > 0) {
  21815. serializationObject.excludedMeshesIds = [];
  21816. this.excludedMeshes.forEach(function (mesh) {
  21817. serializationObject.excludedMeshesIds.push(mesh.id);
  21818. });
  21819. }
  21820. if (this.includedOnlyMeshes.length > 0) {
  21821. serializationObject.includedOnlyMeshesIds = [];
  21822. this.includedOnlyMeshes.forEach(function (mesh) {
  21823. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  21824. });
  21825. }
  21826. // Animations
  21827. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  21828. serializationObject.ranges = this.serializeAnimationRanges();
  21829. return serializationObject;
  21830. };
  21831. /**
  21832. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  21833. * This new light is named "name" and added to the passed scene.
  21834. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  21835. * @param name The friendly name of the light
  21836. * @param scene The scene the new light will belong to
  21837. * @returns the constructor function
  21838. */
  21839. Light.GetConstructorFromName = function (type, name, scene) {
  21840. switch (type) {
  21841. case 0:
  21842. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  21843. case 1:
  21844. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  21845. case 2:
  21846. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  21847. case 3:
  21848. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  21849. }
  21850. return null;
  21851. };
  21852. /**
  21853. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  21854. * @param parsedLight The JSON representation of the light
  21855. * @param scene The scene to create the parsed light in
  21856. * @returns the created light after parsing
  21857. */
  21858. Light.Parse = function (parsedLight, scene) {
  21859. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  21860. if (!constructor) {
  21861. return null;
  21862. }
  21863. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  21864. // Inclusion / exclusions
  21865. if (parsedLight.excludedMeshesIds) {
  21866. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  21867. }
  21868. if (parsedLight.includedOnlyMeshesIds) {
  21869. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  21870. }
  21871. // Parent
  21872. if (parsedLight.parentId) {
  21873. light._waitingParentId = parsedLight.parentId;
  21874. }
  21875. // Animations
  21876. if (parsedLight.animations) {
  21877. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  21878. var parsedAnimation = parsedLight.animations[animationIndex];
  21879. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  21880. }
  21881. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  21882. }
  21883. if (parsedLight.autoAnimate) {
  21884. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  21885. }
  21886. return light;
  21887. };
  21888. Light.prototype._hookArrayForExcluded = function (array) {
  21889. var _this = this;
  21890. var oldPush = array.push;
  21891. array.push = function () {
  21892. var items = [];
  21893. for (var _i = 0; _i < arguments.length; _i++) {
  21894. items[_i] = arguments[_i];
  21895. }
  21896. var result = oldPush.apply(array, items);
  21897. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  21898. var item = items_1[_a];
  21899. item._resyncLighSource(_this);
  21900. }
  21901. return result;
  21902. };
  21903. var oldSplice = array.splice;
  21904. array.splice = function (index, deleteCount) {
  21905. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21906. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  21907. var item = deleted_1[_i];
  21908. item._resyncLighSource(_this);
  21909. }
  21910. return deleted;
  21911. };
  21912. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  21913. var item = array_1[_i];
  21914. item._resyncLighSource(this);
  21915. }
  21916. };
  21917. Light.prototype._hookArrayForIncludedOnly = function (array) {
  21918. var _this = this;
  21919. var oldPush = array.push;
  21920. array.push = function () {
  21921. var items = [];
  21922. for (var _i = 0; _i < arguments.length; _i++) {
  21923. items[_i] = arguments[_i];
  21924. }
  21925. var result = oldPush.apply(array, items);
  21926. _this._resyncMeshes();
  21927. return result;
  21928. };
  21929. var oldSplice = array.splice;
  21930. array.splice = function (index, deleteCount) {
  21931. var deleted = oldSplice.apply(array, [index, deleteCount]);
  21932. _this._resyncMeshes();
  21933. return deleted;
  21934. };
  21935. this._resyncMeshes();
  21936. };
  21937. Light.prototype._resyncMeshes = function () {
  21938. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21939. var mesh = _a[_i];
  21940. mesh._resyncLighSource(this);
  21941. }
  21942. };
  21943. /**
  21944. * Forces the meshes to update their light related information in their rendering used effects
  21945. * @hidden Internal Use Only
  21946. */
  21947. Light.prototype._markMeshesAsLightDirty = function () {
  21948. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  21949. var mesh = _a[_i];
  21950. if (mesh._lightSources.indexOf(this) !== -1) {
  21951. mesh._markSubMeshesAsLightDirty();
  21952. }
  21953. }
  21954. };
  21955. /**
  21956. * Recomputes the cached photometric scale if needed.
  21957. */
  21958. Light.prototype._computePhotometricScale = function () {
  21959. this._photometricScale = this._getPhotometricScale();
  21960. this.getScene().resetCachedMaterial();
  21961. };
  21962. /**
  21963. * Returns the Photometric Scale according to the light type and intensity mode.
  21964. */
  21965. Light.prototype._getPhotometricScale = function () {
  21966. var photometricScale = 0.0;
  21967. var lightTypeID = this.getTypeID();
  21968. //get photometric mode
  21969. var photometricMode = this.intensityMode;
  21970. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  21971. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  21972. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  21973. }
  21974. else {
  21975. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  21976. }
  21977. }
  21978. //compute photometric scale
  21979. switch (lightTypeID) {
  21980. case Light.LIGHTTYPEID_POINTLIGHT:
  21981. case Light.LIGHTTYPEID_SPOTLIGHT:
  21982. switch (photometricMode) {
  21983. case Light.INTENSITYMODE_LUMINOUSPOWER:
  21984. photometricScale = 1.0 / (4.0 * Math.PI);
  21985. break;
  21986. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  21987. photometricScale = 1.0;
  21988. break;
  21989. case Light.INTENSITYMODE_LUMINANCE:
  21990. photometricScale = this.radius * this.radius;
  21991. break;
  21992. }
  21993. break;
  21994. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  21995. switch (photometricMode) {
  21996. case Light.INTENSITYMODE_ILLUMINANCE:
  21997. photometricScale = 1.0;
  21998. break;
  21999. case Light.INTENSITYMODE_LUMINANCE:
  22000. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22001. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22002. var apexAngleRadians = this.radius;
  22003. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22004. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22005. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22006. photometricScale = solidAngle;
  22007. break;
  22008. }
  22009. break;
  22010. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22011. // No fall off in hemisperic light.
  22012. photometricScale = 1.0;
  22013. break;
  22014. }
  22015. return photometricScale;
  22016. };
  22017. /**
  22018. * Reorder the light in the scene according to their defined priority.
  22019. * @hidden Internal Use Only
  22020. */
  22021. Light.prototype._reorderLightsInScene = function () {
  22022. var scene = this.getScene();
  22023. if (this._renderPriority != 0) {
  22024. scene.requireLightSorting = true;
  22025. }
  22026. this.getScene().sortLightsByPriority();
  22027. };
  22028. //lightmapMode Consts
  22029. Light._LIGHTMAP_DEFAULT = 0;
  22030. Light._LIGHTMAP_SPECULAR = 1;
  22031. Light._LIGHTMAP_SHADOWSONLY = 2;
  22032. // Intensity Mode Consts
  22033. Light._INTENSITYMODE_AUTOMATIC = 0;
  22034. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22035. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22036. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22037. Light._INTENSITYMODE_LUMINANCE = 4;
  22038. // Light types ids const.
  22039. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22040. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22041. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22042. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22043. __decorate([
  22044. BABYLON.serializeAsColor3()
  22045. ], Light.prototype, "diffuse", void 0);
  22046. __decorate([
  22047. BABYLON.serializeAsColor3()
  22048. ], Light.prototype, "specular", void 0);
  22049. __decorate([
  22050. BABYLON.serialize()
  22051. ], Light.prototype, "intensity", void 0);
  22052. __decorate([
  22053. BABYLON.serialize()
  22054. ], Light.prototype, "range", void 0);
  22055. __decorate([
  22056. BABYLON.serialize()
  22057. ], Light.prototype, "intensityMode", null);
  22058. __decorate([
  22059. BABYLON.serialize()
  22060. ], Light.prototype, "radius", null);
  22061. __decorate([
  22062. BABYLON.serialize()
  22063. ], Light.prototype, "_renderPriority", void 0);
  22064. __decorate([
  22065. BABYLON.expandToProperty("_reorderLightsInScene")
  22066. ], Light.prototype, "renderPriority", void 0);
  22067. __decorate([
  22068. BABYLON.serialize()
  22069. ], Light.prototype, "shadowEnabled", void 0);
  22070. __decorate([
  22071. BABYLON.serialize("excludeWithLayerMask")
  22072. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22073. __decorate([
  22074. BABYLON.serialize("includeOnlyWithLayerMask")
  22075. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22076. __decorate([
  22077. BABYLON.serialize("lightmapMode")
  22078. ], Light.prototype, "_lightmapMode", void 0);
  22079. return Light;
  22080. }(BABYLON.Node));
  22081. BABYLON.Light = Light;
  22082. })(BABYLON || (BABYLON = {}));
  22083. //# sourceMappingURL=babylon.light.js.map
  22084. var BABYLON;
  22085. (function (BABYLON) {
  22086. var Camera = /** @class */ (function (_super) {
  22087. __extends(Camera, _super);
  22088. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22089. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22090. var _this = _super.call(this, name, scene) || this;
  22091. /**
  22092. * The vector the camera should consider as up.
  22093. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22094. */
  22095. _this.upVector = BABYLON.Vector3.Up();
  22096. _this.orthoLeft = null;
  22097. _this.orthoRight = null;
  22098. _this.orthoBottom = null;
  22099. _this.orthoTop = null;
  22100. /**
  22101. * FOV is set in Radians. (default is 0.8)
  22102. */
  22103. _this.fov = 0.8;
  22104. _this.minZ = 1;
  22105. _this.maxZ = 10000.0;
  22106. _this.inertia = 0.9;
  22107. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22108. _this.isIntermediate = false;
  22109. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22110. /**
  22111. * Restricts the camera to viewing objects with the same layerMask.
  22112. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22113. */
  22114. _this.layerMask = 0x0FFFFFFF;
  22115. /**
  22116. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22117. */
  22118. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22119. // Camera rig members
  22120. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22121. _this._rigCameras = new Array();
  22122. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22123. _this._skipRendering = false;
  22124. _this.customRenderTargets = new Array();
  22125. // Observables
  22126. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22127. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22128. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22129. _this.onRestoreStateObservable = new BABYLON.Observable();
  22130. // Cache
  22131. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22132. _this._projectionMatrix = new BABYLON.Matrix();
  22133. _this._doNotComputeProjectionMatrix = false;
  22134. _this._worldMatrix = BABYLON.Matrix.Identity();
  22135. _this._postProcesses = new Array();
  22136. _this._transformMatrix = BABYLON.Matrix.Zero();
  22137. _this._activeMeshes = new BABYLON.SmartArray(256);
  22138. _this._globalPosition = BABYLON.Vector3.Zero();
  22139. _this._refreshFrustumPlanes = true;
  22140. _this.getScene().addCamera(_this);
  22141. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22142. _this.getScene().activeCamera = _this;
  22143. }
  22144. _this.position = position;
  22145. return _this;
  22146. }
  22147. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22148. get: function () {
  22149. return Camera._PERSPECTIVE_CAMERA;
  22150. },
  22151. enumerable: true,
  22152. configurable: true
  22153. });
  22154. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22155. get: function () {
  22156. return Camera._ORTHOGRAPHIC_CAMERA;
  22157. },
  22158. enumerable: true,
  22159. configurable: true
  22160. });
  22161. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22162. /**
  22163. * This is the default FOV mode for perspective cameras.
  22164. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22165. *
  22166. */
  22167. get: function () {
  22168. return Camera._FOVMODE_VERTICAL_FIXED;
  22169. },
  22170. enumerable: true,
  22171. configurable: true
  22172. });
  22173. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22174. /**
  22175. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22176. *
  22177. */
  22178. get: function () {
  22179. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22180. },
  22181. enumerable: true,
  22182. configurable: true
  22183. });
  22184. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22185. get: function () {
  22186. return Camera._RIG_MODE_NONE;
  22187. },
  22188. enumerable: true,
  22189. configurable: true
  22190. });
  22191. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22192. get: function () {
  22193. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22194. },
  22195. enumerable: true,
  22196. configurable: true
  22197. });
  22198. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22199. get: function () {
  22200. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22201. },
  22202. enumerable: true,
  22203. configurable: true
  22204. });
  22205. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22206. get: function () {
  22207. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22208. },
  22209. enumerable: true,
  22210. configurable: true
  22211. });
  22212. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22213. get: function () {
  22214. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22215. },
  22216. enumerable: true,
  22217. configurable: true
  22218. });
  22219. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22220. get: function () {
  22221. return Camera._RIG_MODE_VR;
  22222. },
  22223. enumerable: true,
  22224. configurable: true
  22225. });
  22226. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22227. get: function () {
  22228. return Camera._RIG_MODE_WEBVR;
  22229. },
  22230. enumerable: true,
  22231. configurable: true
  22232. });
  22233. /**
  22234. * Store current camera state (fov, position, etc..)
  22235. */
  22236. Camera.prototype.storeState = function () {
  22237. this._stateStored = true;
  22238. this._storedFov = this.fov;
  22239. return this;
  22240. };
  22241. /**
  22242. * Restores the camera state values if it has been stored. You must call storeState() first
  22243. */
  22244. Camera.prototype._restoreStateValues = function () {
  22245. if (!this._stateStored) {
  22246. return false;
  22247. }
  22248. this.fov = this._storedFov;
  22249. return true;
  22250. };
  22251. /**
  22252. * Restored camera state. You must call storeState() first
  22253. */
  22254. Camera.prototype.restoreState = function () {
  22255. if (this._restoreStateValues()) {
  22256. this.onRestoreStateObservable.notifyObservers(this);
  22257. return true;
  22258. }
  22259. return false;
  22260. };
  22261. Camera.prototype.getClassName = function () {
  22262. return "Camera";
  22263. };
  22264. /**
  22265. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22266. */
  22267. Camera.prototype.toString = function (fullDetails) {
  22268. var ret = "Name: " + this.name;
  22269. ret += ", type: " + this.getClassName();
  22270. if (this.animations) {
  22271. for (var i = 0; i < this.animations.length; i++) {
  22272. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22273. }
  22274. }
  22275. if (fullDetails) {
  22276. }
  22277. return ret;
  22278. };
  22279. Object.defineProperty(Camera.prototype, "globalPosition", {
  22280. get: function () {
  22281. return this._globalPosition;
  22282. },
  22283. enumerable: true,
  22284. configurable: true
  22285. });
  22286. Camera.prototype.getActiveMeshes = function () {
  22287. return this._activeMeshes;
  22288. };
  22289. Camera.prototype.isActiveMesh = function (mesh) {
  22290. return (this._activeMeshes.indexOf(mesh) !== -1);
  22291. };
  22292. /**
  22293. * Is this camera ready to be used/rendered
  22294. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22295. * @return true if the camera is ready
  22296. */
  22297. Camera.prototype.isReady = function (completeCheck) {
  22298. if (completeCheck === void 0) { completeCheck = false; }
  22299. if (completeCheck) {
  22300. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22301. var pp = _a[_i];
  22302. if (pp && !pp.isReady()) {
  22303. return false;
  22304. }
  22305. }
  22306. }
  22307. return _super.prototype.isReady.call(this, completeCheck);
  22308. };
  22309. //Cache
  22310. Camera.prototype._initCache = function () {
  22311. _super.prototype._initCache.call(this);
  22312. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22313. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22314. this._cache.mode = undefined;
  22315. this._cache.minZ = undefined;
  22316. this._cache.maxZ = undefined;
  22317. this._cache.fov = undefined;
  22318. this._cache.fovMode = undefined;
  22319. this._cache.aspectRatio = undefined;
  22320. this._cache.orthoLeft = undefined;
  22321. this._cache.orthoRight = undefined;
  22322. this._cache.orthoBottom = undefined;
  22323. this._cache.orthoTop = undefined;
  22324. this._cache.renderWidth = undefined;
  22325. this._cache.renderHeight = undefined;
  22326. };
  22327. Camera.prototype._updateCache = function (ignoreParentClass) {
  22328. if (!ignoreParentClass) {
  22329. _super.prototype._updateCache.call(this);
  22330. }
  22331. this._cache.position.copyFrom(this.position);
  22332. this._cache.upVector.copyFrom(this.upVector);
  22333. };
  22334. // Synchronized
  22335. Camera.prototype._isSynchronized = function () {
  22336. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22337. };
  22338. Camera.prototype._isSynchronizedViewMatrix = function () {
  22339. if (!_super.prototype._isSynchronized.call(this))
  22340. return false;
  22341. return this._cache.position.equals(this.position)
  22342. && this._cache.upVector.equals(this.upVector)
  22343. && this.isSynchronizedWithParent();
  22344. };
  22345. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22346. var check = this._cache.mode === this.mode
  22347. && this._cache.minZ === this.minZ
  22348. && this._cache.maxZ === this.maxZ;
  22349. if (!check) {
  22350. return false;
  22351. }
  22352. var engine = this.getEngine();
  22353. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22354. check = this._cache.fov === this.fov
  22355. && this._cache.fovMode === this.fovMode
  22356. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22357. }
  22358. else {
  22359. check = this._cache.orthoLeft === this.orthoLeft
  22360. && this._cache.orthoRight === this.orthoRight
  22361. && this._cache.orthoBottom === this.orthoBottom
  22362. && this._cache.orthoTop === this.orthoTop
  22363. && this._cache.renderWidth === engine.getRenderWidth()
  22364. && this._cache.renderHeight === engine.getRenderHeight();
  22365. }
  22366. return check;
  22367. };
  22368. // Controls
  22369. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22370. };
  22371. Camera.prototype.detachControl = function (element) {
  22372. };
  22373. Camera.prototype.update = function () {
  22374. this._checkInputs();
  22375. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22376. this._updateRigCameras();
  22377. }
  22378. };
  22379. Camera.prototype._checkInputs = function () {
  22380. this.onAfterCheckInputsObservable.notifyObservers(this);
  22381. };
  22382. Object.defineProperty(Camera.prototype, "rigCameras", {
  22383. get: function () {
  22384. return this._rigCameras;
  22385. },
  22386. enumerable: true,
  22387. configurable: true
  22388. });
  22389. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22390. get: function () {
  22391. return this._rigPostProcess;
  22392. },
  22393. enumerable: true,
  22394. configurable: true
  22395. });
  22396. /**
  22397. * Internal, gets the first post proces.
  22398. * @returns the first post process to be run on this camera.
  22399. */
  22400. Camera.prototype._getFirstPostProcess = function () {
  22401. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22402. if (this._postProcesses[ppIndex] !== null) {
  22403. return this._postProcesses[ppIndex];
  22404. }
  22405. }
  22406. return null;
  22407. };
  22408. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22409. // invalidate framebuffer
  22410. var firstPostProcess = this._getFirstPostProcess();
  22411. if (firstPostProcess) {
  22412. firstPostProcess.markTextureDirty();
  22413. }
  22414. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22415. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22416. var cam = this._rigCameras[i];
  22417. var rigPostProcess = cam._rigPostProcess;
  22418. // for VR rig, there does not have to be a post process
  22419. if (rigPostProcess) {
  22420. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22421. if (isPass) {
  22422. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22423. cam.isIntermediate = this._postProcesses.length === 0;
  22424. }
  22425. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22426. rigPostProcess.markTextureDirty();
  22427. }
  22428. else {
  22429. cam._postProcesses = this._postProcesses.slice(0);
  22430. }
  22431. }
  22432. };
  22433. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22434. if (insertAt === void 0) { insertAt = null; }
  22435. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22436. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22437. return 0;
  22438. }
  22439. if (insertAt == null || insertAt < 0) {
  22440. this._postProcesses.push(postProcess);
  22441. }
  22442. else if (this._postProcesses[insertAt] === null) {
  22443. this._postProcesses[insertAt] = postProcess;
  22444. }
  22445. else {
  22446. this._postProcesses.splice(insertAt, 0, postProcess);
  22447. }
  22448. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22449. return this._postProcesses.indexOf(postProcess);
  22450. };
  22451. Camera.prototype.detachPostProcess = function (postProcess) {
  22452. var idx = this._postProcesses.indexOf(postProcess);
  22453. if (idx !== -1) {
  22454. this._postProcesses[idx] = null;
  22455. }
  22456. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22457. };
  22458. Camera.prototype.getWorldMatrix = function () {
  22459. if (this._isSynchronizedViewMatrix()) {
  22460. return this._worldMatrix;
  22461. }
  22462. // Getting the the view matrix will also compute the world matrix.
  22463. this.getViewMatrix();
  22464. return this._worldMatrix;
  22465. };
  22466. Camera.prototype._getViewMatrix = function () {
  22467. return BABYLON.Matrix.Identity();
  22468. };
  22469. Camera.prototype.getViewMatrix = function (force) {
  22470. if (!force && this._isSynchronizedViewMatrix()) {
  22471. return this._computedViewMatrix;
  22472. }
  22473. this.updateCache();
  22474. this._computedViewMatrix = this._getViewMatrix();
  22475. this._currentRenderId = this.getScene().getRenderId();
  22476. this._childRenderId = this._currentRenderId;
  22477. this._refreshFrustumPlanes = true;
  22478. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22479. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22480. }
  22481. this.onViewMatrixChangedObservable.notifyObservers(this);
  22482. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22483. return this._computedViewMatrix;
  22484. };
  22485. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22486. this._doNotComputeProjectionMatrix = true;
  22487. if (projection !== undefined) {
  22488. this._projectionMatrix = projection;
  22489. }
  22490. };
  22491. ;
  22492. Camera.prototype.unfreezeProjectionMatrix = function () {
  22493. this._doNotComputeProjectionMatrix = false;
  22494. };
  22495. ;
  22496. Camera.prototype.getProjectionMatrix = function (force) {
  22497. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22498. return this._projectionMatrix;
  22499. }
  22500. // Cache
  22501. this._cache.mode = this.mode;
  22502. this._cache.minZ = this.minZ;
  22503. this._cache.maxZ = this.maxZ;
  22504. // Matrix
  22505. this._refreshFrustumPlanes = true;
  22506. var engine = this.getEngine();
  22507. var scene = this.getScene();
  22508. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22509. this._cache.fov = this.fov;
  22510. this._cache.fovMode = this.fovMode;
  22511. this._cache.aspectRatio = engine.getAspectRatio(this);
  22512. if (this.minZ <= 0) {
  22513. this.minZ = 0.1;
  22514. }
  22515. if (scene.useRightHandedSystem) {
  22516. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22517. }
  22518. else {
  22519. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22520. }
  22521. }
  22522. else {
  22523. var halfWidth = engine.getRenderWidth() / 2.0;
  22524. var halfHeight = engine.getRenderHeight() / 2.0;
  22525. if (scene.useRightHandedSystem) {
  22526. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22527. }
  22528. else {
  22529. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22530. }
  22531. this._cache.orthoLeft = this.orthoLeft;
  22532. this._cache.orthoRight = this.orthoRight;
  22533. this._cache.orthoBottom = this.orthoBottom;
  22534. this._cache.orthoTop = this.orthoTop;
  22535. this._cache.renderWidth = engine.getRenderWidth();
  22536. this._cache.renderHeight = engine.getRenderHeight();
  22537. }
  22538. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22539. return this._projectionMatrix;
  22540. };
  22541. Camera.prototype.getTranformationMatrix = function () {
  22542. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22543. return this._transformMatrix;
  22544. };
  22545. Camera.prototype.updateFrustumPlanes = function () {
  22546. if (!this._refreshFrustumPlanes) {
  22547. return;
  22548. }
  22549. this.getTranformationMatrix();
  22550. if (!this._frustumPlanes) {
  22551. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22552. }
  22553. else {
  22554. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22555. }
  22556. this._refreshFrustumPlanes = false;
  22557. };
  22558. Camera.prototype.isInFrustum = function (target) {
  22559. this.updateFrustumPlanes();
  22560. return target.isInFrustum(this._frustumPlanes);
  22561. };
  22562. Camera.prototype.isCompletelyInFrustum = function (target) {
  22563. this.updateFrustumPlanes();
  22564. return target.isCompletelyInFrustum(this._frustumPlanes);
  22565. };
  22566. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22567. if (length === void 0) { length = 100; }
  22568. if (!transform) {
  22569. transform = this.getWorldMatrix();
  22570. }
  22571. if (!origin) {
  22572. origin = this.position;
  22573. }
  22574. var forward = new BABYLON.Vector3(0, 0, 1);
  22575. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22576. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22577. return new BABYLON.Ray(origin, direction, length);
  22578. };
  22579. /**
  22580. * Releases resources associated with this node.
  22581. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22582. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22583. */
  22584. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22585. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22586. // Observables
  22587. this.onViewMatrixChangedObservable.clear();
  22588. this.onProjectionMatrixChangedObservable.clear();
  22589. this.onAfterCheckInputsObservable.clear();
  22590. this.onRestoreStateObservable.clear();
  22591. // Inputs
  22592. if (this.inputs) {
  22593. this.inputs.clear();
  22594. }
  22595. // Animations
  22596. this.getScene().stopAnimation(this);
  22597. // Remove from scene
  22598. this.getScene().removeCamera(this);
  22599. while (this._rigCameras.length > 0) {
  22600. var camera = this._rigCameras.pop();
  22601. if (camera) {
  22602. camera.dispose();
  22603. }
  22604. }
  22605. // Postprocesses
  22606. if (this._rigPostProcess) {
  22607. this._rigPostProcess.dispose(this);
  22608. this._rigPostProcess = null;
  22609. this._postProcesses = [];
  22610. }
  22611. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22612. this._rigPostProcess = null;
  22613. this._postProcesses = [];
  22614. }
  22615. else {
  22616. var i = this._postProcesses.length;
  22617. while (--i >= 0) {
  22618. var postProcess = this._postProcesses[i];
  22619. if (postProcess) {
  22620. postProcess.dispose(this);
  22621. }
  22622. }
  22623. }
  22624. // Render targets
  22625. var i = this.customRenderTargets.length;
  22626. while (--i >= 0) {
  22627. this.customRenderTargets[i].dispose();
  22628. }
  22629. this.customRenderTargets = [];
  22630. // Active Meshes
  22631. this._activeMeshes.dispose();
  22632. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22633. };
  22634. Object.defineProperty(Camera.prototype, "leftCamera", {
  22635. // ---- Camera rigs section ----
  22636. get: function () {
  22637. if (this._rigCameras.length < 1) {
  22638. return null;
  22639. }
  22640. return this._rigCameras[0];
  22641. },
  22642. enumerable: true,
  22643. configurable: true
  22644. });
  22645. Object.defineProperty(Camera.prototype, "rightCamera", {
  22646. get: function () {
  22647. if (this._rigCameras.length < 2) {
  22648. return null;
  22649. }
  22650. return this._rigCameras[1];
  22651. },
  22652. enumerable: true,
  22653. configurable: true
  22654. });
  22655. Camera.prototype.getLeftTarget = function () {
  22656. if (this._rigCameras.length < 1) {
  22657. return null;
  22658. }
  22659. return this._rigCameras[0].getTarget();
  22660. };
  22661. Camera.prototype.getRightTarget = function () {
  22662. if (this._rigCameras.length < 2) {
  22663. return null;
  22664. }
  22665. return this._rigCameras[1].getTarget();
  22666. };
  22667. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  22668. if (this.cameraRigMode === mode) {
  22669. return;
  22670. }
  22671. while (this._rigCameras.length > 0) {
  22672. var camera = this._rigCameras.pop();
  22673. if (camera) {
  22674. camera.dispose();
  22675. }
  22676. }
  22677. this.cameraRigMode = mode;
  22678. this._cameraRigParams = {};
  22679. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  22680. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  22681. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  22682. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  22683. // create the rig cameras, unless none
  22684. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22685. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  22686. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  22687. if (leftCamera && rightCamera) {
  22688. this._rigCameras.push(leftCamera);
  22689. this._rigCameras.push(rightCamera);
  22690. }
  22691. }
  22692. switch (this.cameraRigMode) {
  22693. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  22694. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22695. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  22696. break;
  22697. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  22698. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  22699. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  22700. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22701. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  22702. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  22703. break;
  22704. case Camera.RIG_MODE_VR:
  22705. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  22706. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  22707. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22708. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22709. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  22710. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  22711. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  22712. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  22713. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22714. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22715. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  22716. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  22717. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  22718. if (metrics.compensateDistortion) {
  22719. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  22720. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  22721. }
  22722. break;
  22723. case Camera.RIG_MODE_WEBVR:
  22724. if (rigParams.vrDisplay) {
  22725. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  22726. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  22727. //Left eye
  22728. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  22729. this._rigCameras[0].setCameraRigParameter("left", true);
  22730. //leaving this for future reference
  22731. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  22732. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  22733. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  22734. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22735. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22736. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22737. this._rigCameras[0].parent = this;
  22738. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  22739. //Right eye
  22740. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  22741. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  22742. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  22743. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  22744. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  22745. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  22746. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  22747. this._rigCameras[1].parent = this;
  22748. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  22749. if (Camera.UseAlternateWebVRRendering) {
  22750. this._rigCameras[1]._skipRendering = true;
  22751. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  22752. }
  22753. }
  22754. break;
  22755. }
  22756. this._cascadePostProcessesToRigCams();
  22757. this.update();
  22758. };
  22759. Camera.prototype._getVRProjectionMatrix = function () {
  22760. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  22761. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  22762. return this._projectionMatrix;
  22763. };
  22764. Camera.prototype._updateCameraRotationMatrix = function () {
  22765. //Here for WebVR
  22766. };
  22767. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  22768. //Here for WebVR
  22769. };
  22770. /**
  22771. * This function MUST be overwritten by the different WebVR cameras available.
  22772. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22773. */
  22774. Camera.prototype._getWebVRProjectionMatrix = function () {
  22775. return BABYLON.Matrix.Identity();
  22776. };
  22777. /**
  22778. * This function MUST be overwritten by the different WebVR cameras available.
  22779. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  22780. */
  22781. Camera.prototype._getWebVRViewMatrix = function () {
  22782. return BABYLON.Matrix.Identity();
  22783. };
  22784. Camera.prototype.setCameraRigParameter = function (name, value) {
  22785. if (!this._cameraRigParams) {
  22786. this._cameraRigParams = {};
  22787. }
  22788. this._cameraRigParams[name] = value;
  22789. //provisionnally:
  22790. if (name === "interaxialDistance") {
  22791. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  22792. }
  22793. };
  22794. /**
  22795. * needs to be overridden by children so sub has required properties to be copied
  22796. */
  22797. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  22798. return null;
  22799. };
  22800. /**
  22801. * May need to be overridden by children
  22802. */
  22803. Camera.prototype._updateRigCameras = function () {
  22804. for (var i = 0; i < this._rigCameras.length; i++) {
  22805. this._rigCameras[i].minZ = this.minZ;
  22806. this._rigCameras[i].maxZ = this.maxZ;
  22807. this._rigCameras[i].fov = this.fov;
  22808. }
  22809. // only update viewport when ANAGLYPH
  22810. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  22811. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  22812. }
  22813. };
  22814. Camera.prototype._setupInputs = function () {
  22815. };
  22816. Camera.prototype.serialize = function () {
  22817. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22818. // Type
  22819. serializationObject.type = this.getClassName();
  22820. // Parent
  22821. if (this.parent) {
  22822. serializationObject.parentId = this.parent.id;
  22823. }
  22824. if (this.inputs) {
  22825. this.inputs.serialize(serializationObject);
  22826. }
  22827. // Animations
  22828. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22829. serializationObject.ranges = this.serializeAnimationRanges();
  22830. return serializationObject;
  22831. };
  22832. Camera.prototype.clone = function (name) {
  22833. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  22834. };
  22835. Camera.prototype.getDirection = function (localAxis) {
  22836. var result = BABYLON.Vector3.Zero();
  22837. this.getDirectionToRef(localAxis, result);
  22838. return result;
  22839. };
  22840. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  22841. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  22842. };
  22843. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  22844. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  22845. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  22846. switch (type) {
  22847. case "ArcRotateCamera":
  22848. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  22849. case "DeviceOrientationCamera":
  22850. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  22851. case "FollowCamera":
  22852. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  22853. case "ArcFollowCamera":
  22854. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  22855. case "GamepadCamera":
  22856. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22857. case "TouchCamera":
  22858. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  22859. case "VirtualJoysticksCamera":
  22860. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  22861. case "WebVRFreeCamera":
  22862. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22863. case "WebVRGamepadCamera":
  22864. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22865. case "VRDeviceOrientationFreeCamera":
  22866. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  22867. case "VRDeviceOrientationGamepadCamera":
  22868. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  22869. case "AnaglyphArcRotateCamera":
  22870. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22871. case "AnaglyphFreeCamera":
  22872. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22873. case "AnaglyphGamepadCamera":
  22874. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22875. case "AnaglyphUniversalCamera":
  22876. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  22877. case "StereoscopicArcRotateCamera":
  22878. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22879. case "StereoscopicFreeCamera":
  22880. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22881. case "StereoscopicGamepadCamera":
  22882. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22883. case "StereoscopicUniversalCamera":
  22884. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  22885. case "FreeCamera": // Forcing Universal here
  22886. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22887. default: // Universal Camera is the default value
  22888. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  22889. }
  22890. };
  22891. Camera.prototype.computeWorldMatrix = function () {
  22892. return this.getWorldMatrix();
  22893. };
  22894. Camera.Parse = function (parsedCamera, scene) {
  22895. var type = parsedCamera.type;
  22896. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  22897. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  22898. // Parent
  22899. if (parsedCamera.parentId) {
  22900. camera._waitingParentId = parsedCamera.parentId;
  22901. }
  22902. //If camera has an input manager, let it parse inputs settings
  22903. if (camera.inputs) {
  22904. camera.inputs.parse(parsedCamera);
  22905. camera._setupInputs();
  22906. }
  22907. if (camera.setPosition) { // need to force position
  22908. camera.position.copyFromFloats(0, 0, 0);
  22909. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  22910. }
  22911. // Target
  22912. if (parsedCamera.target) {
  22913. if (camera.setTarget) {
  22914. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  22915. }
  22916. }
  22917. // Apply 3d rig, when found
  22918. if (parsedCamera.cameraRigMode) {
  22919. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  22920. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  22921. }
  22922. // Animations
  22923. if (parsedCamera.animations) {
  22924. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  22925. var parsedAnimation = parsedCamera.animations[animationIndex];
  22926. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22927. }
  22928. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  22929. }
  22930. if (parsedCamera.autoAnimate) {
  22931. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  22932. }
  22933. return camera;
  22934. };
  22935. // Statics
  22936. Camera._PERSPECTIVE_CAMERA = 0;
  22937. Camera._ORTHOGRAPHIC_CAMERA = 1;
  22938. Camera._FOVMODE_VERTICAL_FIXED = 0;
  22939. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  22940. Camera._RIG_MODE_NONE = 0;
  22941. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  22942. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  22943. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  22944. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  22945. Camera._RIG_MODE_VR = 20;
  22946. Camera._RIG_MODE_WEBVR = 21;
  22947. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  22948. Camera.UseAlternateWebVRRendering = false;
  22949. __decorate([
  22950. BABYLON.serializeAsVector3()
  22951. ], Camera.prototype, "position", void 0);
  22952. __decorate([
  22953. BABYLON.serializeAsVector3()
  22954. ], Camera.prototype, "upVector", void 0);
  22955. __decorate([
  22956. BABYLON.serialize()
  22957. ], Camera.prototype, "orthoLeft", void 0);
  22958. __decorate([
  22959. BABYLON.serialize()
  22960. ], Camera.prototype, "orthoRight", void 0);
  22961. __decorate([
  22962. BABYLON.serialize()
  22963. ], Camera.prototype, "orthoBottom", void 0);
  22964. __decorate([
  22965. BABYLON.serialize()
  22966. ], Camera.prototype, "orthoTop", void 0);
  22967. __decorate([
  22968. BABYLON.serialize()
  22969. ], Camera.prototype, "fov", void 0);
  22970. __decorate([
  22971. BABYLON.serialize()
  22972. ], Camera.prototype, "minZ", void 0);
  22973. __decorate([
  22974. BABYLON.serialize()
  22975. ], Camera.prototype, "maxZ", void 0);
  22976. __decorate([
  22977. BABYLON.serialize()
  22978. ], Camera.prototype, "inertia", void 0);
  22979. __decorate([
  22980. BABYLON.serialize()
  22981. ], Camera.prototype, "mode", void 0);
  22982. __decorate([
  22983. BABYLON.serialize()
  22984. ], Camera.prototype, "layerMask", void 0);
  22985. __decorate([
  22986. BABYLON.serialize()
  22987. ], Camera.prototype, "fovMode", void 0);
  22988. __decorate([
  22989. BABYLON.serialize()
  22990. ], Camera.prototype, "cameraRigMode", void 0);
  22991. __decorate([
  22992. BABYLON.serialize()
  22993. ], Camera.prototype, "interaxialDistance", void 0);
  22994. __decorate([
  22995. BABYLON.serialize()
  22996. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  22997. return Camera;
  22998. }(BABYLON.Node));
  22999. BABYLON.Camera = Camera;
  23000. })(BABYLON || (BABYLON = {}));
  23001. //# sourceMappingURL=babylon.camera.js.map
  23002. var BABYLON;
  23003. (function (BABYLON) {
  23004. var RenderingManager = /** @class */ (function () {
  23005. function RenderingManager(scene) {
  23006. this._renderingGroups = new Array();
  23007. this._autoClearDepthStencil = {};
  23008. this._customOpaqueSortCompareFn = {};
  23009. this._customAlphaTestSortCompareFn = {};
  23010. this._customTransparentSortCompareFn = {};
  23011. this._renderinGroupInfo = null;
  23012. this._scene = scene;
  23013. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23014. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23015. }
  23016. }
  23017. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23018. if (depth === void 0) { depth = true; }
  23019. if (stencil === void 0) { stencil = true; }
  23020. if (this._depthStencilBufferAlreadyCleaned) {
  23021. return;
  23022. }
  23023. this._scene.getEngine().clear(null, false, depth, stencil);
  23024. this._depthStencilBufferAlreadyCleaned = true;
  23025. };
  23026. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23027. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23028. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23029. var info = null;
  23030. if (observable) {
  23031. if (!this._renderinGroupInfo) {
  23032. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23033. }
  23034. info = this._renderinGroupInfo;
  23035. info.scene = this._scene;
  23036. info.camera = this._scene.activeCamera;
  23037. }
  23038. // Dispatch sprites
  23039. if (renderSprites) {
  23040. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23041. var manager = this._scene.spriteManagers[index];
  23042. this.dispatchSprites(manager);
  23043. }
  23044. }
  23045. // Render
  23046. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23047. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23048. var renderingGroup = this._renderingGroups[index];
  23049. if (!renderingGroup && !observable)
  23050. continue;
  23051. var renderingGroupMask = 0;
  23052. // Fire PRECLEAR stage
  23053. if (observable && info) {
  23054. renderingGroupMask = Math.pow(2, index);
  23055. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23056. info.renderingGroupId = index;
  23057. observable.notifyObservers(info, renderingGroupMask);
  23058. }
  23059. // Clear depth/stencil if needed
  23060. if (RenderingManager.AUTOCLEAR) {
  23061. var autoClear = this._autoClearDepthStencil[index];
  23062. if (autoClear && autoClear.autoClear) {
  23063. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23064. }
  23065. }
  23066. if (observable && info) {
  23067. // Fire PREOPAQUE stage
  23068. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23069. observable.notifyObservers(info, renderingGroupMask);
  23070. // Fire PRETRANSPARENT stage
  23071. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23072. observable.notifyObservers(info, renderingGroupMask);
  23073. }
  23074. if (renderingGroup)
  23075. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23076. // Fire POSTTRANSPARENT stage
  23077. if (observable && info) {
  23078. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23079. observable.notifyObservers(info, renderingGroupMask);
  23080. }
  23081. }
  23082. };
  23083. RenderingManager.prototype.reset = function () {
  23084. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23085. var renderingGroup = this._renderingGroups[index];
  23086. if (renderingGroup) {
  23087. renderingGroup.prepare();
  23088. }
  23089. }
  23090. };
  23091. RenderingManager.prototype.dispose = function () {
  23092. this.freeRenderingGroups();
  23093. this._renderingGroups.length = 0;
  23094. };
  23095. /**
  23096. * Clear the info related to rendering groups preventing retention points during dispose.
  23097. */
  23098. RenderingManager.prototype.freeRenderingGroups = function () {
  23099. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23100. var renderingGroup = this._renderingGroups[index];
  23101. if (renderingGroup) {
  23102. renderingGroup.dispose();
  23103. }
  23104. }
  23105. };
  23106. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23107. if (this._renderingGroups[renderingGroupId] === undefined) {
  23108. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23109. }
  23110. };
  23111. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23112. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23113. this._prepareRenderingGroup(renderingGroupId);
  23114. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23115. };
  23116. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23117. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23118. this._prepareRenderingGroup(renderingGroupId);
  23119. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23120. };
  23121. /**
  23122. * @param subMesh The submesh to dispatch
  23123. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23124. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23125. */
  23126. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23127. if (mesh === undefined) {
  23128. mesh = subMesh.getMesh();
  23129. }
  23130. var renderingGroupId = mesh.renderingGroupId || 0;
  23131. this._prepareRenderingGroup(renderingGroupId);
  23132. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23133. };
  23134. /**
  23135. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23136. * This allowed control for front to back rendering or reversly depending of the special needs.
  23137. *
  23138. * @param renderingGroupId The rendering group id corresponding to its index
  23139. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23140. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23141. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23142. */
  23143. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23144. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23145. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23146. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23147. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23148. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23149. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23150. if (this._renderingGroups[renderingGroupId]) {
  23151. var group = this._renderingGroups[renderingGroupId];
  23152. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23153. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23154. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23155. }
  23156. };
  23157. /**
  23158. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23159. *
  23160. * @param renderingGroupId The rendering group id corresponding to its index
  23161. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23162. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23163. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23164. */
  23165. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23166. if (depth === void 0) { depth = true; }
  23167. if (stencil === void 0) { stencil = true; }
  23168. this._autoClearDepthStencil[renderingGroupId] = {
  23169. autoClear: autoClearDepthStencil,
  23170. depth: depth,
  23171. stencil: stencil
  23172. };
  23173. };
  23174. /**
  23175. * The max id used for rendering groups (not included)
  23176. */
  23177. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23178. /**
  23179. * The min id used for rendering groups (included)
  23180. */
  23181. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23182. /**
  23183. * Used to globally prevent autoclearing scenes.
  23184. */
  23185. RenderingManager.AUTOCLEAR = true;
  23186. return RenderingManager;
  23187. }());
  23188. BABYLON.RenderingManager = RenderingManager;
  23189. })(BABYLON || (BABYLON = {}));
  23190. //# sourceMappingURL=babylon.renderingManager.js.map
  23191. var BABYLON;
  23192. (function (BABYLON) {
  23193. var RenderingGroup = /** @class */ (function () {
  23194. /**
  23195. * Creates a new rendering group.
  23196. * @param index The rendering group index
  23197. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23198. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23199. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23200. */
  23201. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23202. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23203. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23204. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23205. this.index = index;
  23206. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23207. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23208. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23209. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23210. this._particleSystems = new BABYLON.SmartArray(256);
  23211. this._spriteManagers = new BABYLON.SmartArray(256);
  23212. this._edgesRenderers = new BABYLON.SmartArray(16);
  23213. this._scene = scene;
  23214. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23215. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23216. this.transparentSortCompareFn = transparentSortCompareFn;
  23217. }
  23218. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23219. /**
  23220. * Set the opaque sort comparison function.
  23221. * If null the sub meshes will be render in the order they were created
  23222. */
  23223. set: function (value) {
  23224. this._opaqueSortCompareFn = value;
  23225. if (value) {
  23226. this._renderOpaque = this.renderOpaqueSorted;
  23227. }
  23228. else {
  23229. this._renderOpaque = RenderingGroup.renderUnsorted;
  23230. }
  23231. },
  23232. enumerable: true,
  23233. configurable: true
  23234. });
  23235. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23236. /**
  23237. * Set the alpha test sort comparison function.
  23238. * If null the sub meshes will be render in the order they were created
  23239. */
  23240. set: function (value) {
  23241. this._alphaTestSortCompareFn = value;
  23242. if (value) {
  23243. this._renderAlphaTest = this.renderAlphaTestSorted;
  23244. }
  23245. else {
  23246. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23247. }
  23248. },
  23249. enumerable: true,
  23250. configurable: true
  23251. });
  23252. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23253. /**
  23254. * Set the transparent sort comparison function.
  23255. * If null the sub meshes will be render in the order they were created
  23256. */
  23257. set: function (value) {
  23258. if (value) {
  23259. this._transparentSortCompareFn = value;
  23260. }
  23261. else {
  23262. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23263. }
  23264. this._renderTransparent = this.renderTransparentSorted;
  23265. },
  23266. enumerable: true,
  23267. configurable: true
  23268. });
  23269. /**
  23270. * Render all the sub meshes contained in the group.
  23271. * @param customRenderFunction Used to override the default render behaviour of the group.
  23272. * @returns true if rendered some submeshes.
  23273. */
  23274. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23275. if (customRenderFunction) {
  23276. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23277. return;
  23278. }
  23279. var engine = this._scene.getEngine();
  23280. // Depth only
  23281. if (this._depthOnlySubMeshes.length !== 0) {
  23282. engine.setColorWrite(false);
  23283. this._renderAlphaTest(this._depthOnlySubMeshes);
  23284. engine.setColorWrite(true);
  23285. }
  23286. // Opaque
  23287. if (this._opaqueSubMeshes.length !== 0) {
  23288. this._renderOpaque(this._opaqueSubMeshes);
  23289. }
  23290. // Alpha test
  23291. if (this._alphaTestSubMeshes.length !== 0) {
  23292. this._renderAlphaTest(this._alphaTestSubMeshes);
  23293. }
  23294. var stencilState = engine.getStencilBuffer();
  23295. engine.setStencilBuffer(false);
  23296. // Sprites
  23297. if (renderSprites) {
  23298. this._renderSprites();
  23299. }
  23300. // Particles
  23301. if (renderParticles) {
  23302. this._renderParticles(activeMeshes);
  23303. }
  23304. if (this.onBeforeTransparentRendering) {
  23305. this.onBeforeTransparentRendering();
  23306. }
  23307. // Transparent
  23308. if (this._transparentSubMeshes.length !== 0) {
  23309. this._renderTransparent(this._transparentSubMeshes);
  23310. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23311. }
  23312. // Set back stencil to false in case it changes before the edge renderer.
  23313. engine.setStencilBuffer(false);
  23314. // Edges
  23315. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23316. this._edgesRenderers.data[edgesRendererIndex].render();
  23317. }
  23318. // Restore Stencil state.
  23319. engine.setStencilBuffer(stencilState);
  23320. };
  23321. /**
  23322. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23323. * @param subMeshes The submeshes to render
  23324. */
  23325. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23326. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23327. };
  23328. /**
  23329. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23330. * @param subMeshes The submeshes to render
  23331. */
  23332. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23333. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23334. };
  23335. /**
  23336. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23337. * @param subMeshes The submeshes to render
  23338. */
  23339. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23340. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23341. };
  23342. /**
  23343. * Renders the submeshes in a specified order.
  23344. * @param subMeshes The submeshes to sort before render
  23345. * @param sortCompareFn The comparison function use to sort
  23346. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23347. * @param transparent Specifies to activate blending if true
  23348. */
  23349. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23350. var subIndex = 0;
  23351. var subMesh;
  23352. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23353. for (; subIndex < subMeshes.length; subIndex++) {
  23354. subMesh = subMeshes.data[subIndex];
  23355. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23356. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23357. }
  23358. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23359. if (sortCompareFn) {
  23360. sortedArray.sort(sortCompareFn);
  23361. }
  23362. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23363. subMesh = sortedArray[subIndex];
  23364. if (transparent) {
  23365. var material = subMesh.getMaterial();
  23366. if (material && material.needDepthPrePass) {
  23367. var engine = material.getScene().getEngine();
  23368. engine.setColorWrite(false);
  23369. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23370. subMesh.render(false);
  23371. engine.setColorWrite(true);
  23372. }
  23373. }
  23374. subMesh.render(transparent);
  23375. }
  23376. };
  23377. /**
  23378. * Renders the submeshes in the order they were dispatched (no sort applied).
  23379. * @param subMeshes The submeshes to render
  23380. */
  23381. RenderingGroup.renderUnsorted = function (subMeshes) {
  23382. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23383. var submesh = subMeshes.data[subIndex];
  23384. submesh.render(false);
  23385. }
  23386. };
  23387. /**
  23388. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23389. * are rendered back to front if in the same alpha index.
  23390. *
  23391. * @param a The first submesh
  23392. * @param b The second submesh
  23393. * @returns The result of the comparison
  23394. */
  23395. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23396. // Alpha index first
  23397. if (a._alphaIndex > b._alphaIndex) {
  23398. return 1;
  23399. }
  23400. if (a._alphaIndex < b._alphaIndex) {
  23401. return -1;
  23402. }
  23403. // Then distance to camera
  23404. return RenderingGroup.backToFrontSortCompare(a, b);
  23405. };
  23406. /**
  23407. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23408. * are rendered back to front.
  23409. *
  23410. * @param a The first submesh
  23411. * @param b The second submesh
  23412. * @returns The result of the comparison
  23413. */
  23414. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23415. // Then distance to camera
  23416. if (a._distanceToCamera < b._distanceToCamera) {
  23417. return 1;
  23418. }
  23419. if (a._distanceToCamera > b._distanceToCamera) {
  23420. return -1;
  23421. }
  23422. return 0;
  23423. };
  23424. /**
  23425. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23426. * are rendered front to back (prevent overdraw).
  23427. *
  23428. * @param a The first submesh
  23429. * @param b The second submesh
  23430. * @returns The result of the comparison
  23431. */
  23432. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23433. // Then distance to camera
  23434. if (a._distanceToCamera < b._distanceToCamera) {
  23435. return -1;
  23436. }
  23437. if (a._distanceToCamera > b._distanceToCamera) {
  23438. return 1;
  23439. }
  23440. return 0;
  23441. };
  23442. /**
  23443. * Resets the different lists of submeshes to prepare a new frame.
  23444. */
  23445. RenderingGroup.prototype.prepare = function () {
  23446. this._opaqueSubMeshes.reset();
  23447. this._transparentSubMeshes.reset();
  23448. this._alphaTestSubMeshes.reset();
  23449. this._depthOnlySubMeshes.reset();
  23450. this._particleSystems.reset();
  23451. this._spriteManagers.reset();
  23452. this._edgesRenderers.reset();
  23453. };
  23454. RenderingGroup.prototype.dispose = function () {
  23455. this._opaqueSubMeshes.dispose();
  23456. this._transparentSubMeshes.dispose();
  23457. this._alphaTestSubMeshes.dispose();
  23458. this._depthOnlySubMeshes.dispose();
  23459. this._particleSystems.dispose();
  23460. this._spriteManagers.dispose();
  23461. this._edgesRenderers.dispose();
  23462. };
  23463. /**
  23464. * Inserts the submesh in its correct queue depending on its material.
  23465. * @param subMesh The submesh to dispatch
  23466. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23467. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23468. */
  23469. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23470. // Get mesh and materials if not provided
  23471. if (mesh === undefined) {
  23472. mesh = subMesh.getMesh();
  23473. }
  23474. if (material === undefined) {
  23475. material = subMesh.getMaterial();
  23476. }
  23477. if (material === null || material === undefined) {
  23478. return;
  23479. }
  23480. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23481. this._transparentSubMeshes.push(subMesh);
  23482. }
  23483. else if (material.needAlphaTesting()) { // Alpha test
  23484. if (material.needDepthPrePass) {
  23485. this._depthOnlySubMeshes.push(subMesh);
  23486. }
  23487. this._alphaTestSubMeshes.push(subMesh);
  23488. }
  23489. else {
  23490. if (material.needDepthPrePass) {
  23491. this._depthOnlySubMeshes.push(subMesh);
  23492. }
  23493. this._opaqueSubMeshes.push(subMesh); // Opaque
  23494. }
  23495. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined) {
  23496. this._edgesRenderers.push(mesh._edgesRenderer);
  23497. }
  23498. };
  23499. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23500. this._spriteManagers.push(spriteManager);
  23501. };
  23502. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23503. this._particleSystems.push(particleSystem);
  23504. };
  23505. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23506. if (this._particleSystems.length === 0) {
  23507. return;
  23508. }
  23509. // Particles
  23510. var activeCamera = this._scene.activeCamera;
  23511. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23512. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23513. var particleSystem = this._particleSystems.data[particleIndex];
  23514. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23515. continue;
  23516. }
  23517. var emitter = particleSystem.emitter;
  23518. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23519. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23520. }
  23521. }
  23522. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23523. };
  23524. RenderingGroup.prototype._renderSprites = function () {
  23525. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23526. return;
  23527. }
  23528. // Sprites
  23529. var activeCamera = this._scene.activeCamera;
  23530. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23531. for (var id = 0; id < this._spriteManagers.length; id++) {
  23532. var spriteManager = this._spriteManagers.data[id];
  23533. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23534. spriteManager.render();
  23535. }
  23536. }
  23537. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23538. };
  23539. return RenderingGroup;
  23540. }());
  23541. BABYLON.RenderingGroup = RenderingGroup;
  23542. })(BABYLON || (BABYLON = {}));
  23543. //# sourceMappingURL=babylon.renderingGroup.js.map
  23544. var BABYLON;
  23545. (function (BABYLON) {
  23546. /** @hidden */
  23547. var ClickInfo = /** @class */ (function () {
  23548. function ClickInfo() {
  23549. this._singleClick = false;
  23550. this._doubleClick = false;
  23551. this._hasSwiped = false;
  23552. this._ignore = false;
  23553. }
  23554. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23555. get: function () {
  23556. return this._singleClick;
  23557. },
  23558. set: function (b) {
  23559. this._singleClick = b;
  23560. },
  23561. enumerable: true,
  23562. configurable: true
  23563. });
  23564. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23565. get: function () {
  23566. return this._doubleClick;
  23567. },
  23568. set: function (b) {
  23569. this._doubleClick = b;
  23570. },
  23571. enumerable: true,
  23572. configurable: true
  23573. });
  23574. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23575. get: function () {
  23576. return this._hasSwiped;
  23577. },
  23578. set: function (b) {
  23579. this._hasSwiped = b;
  23580. },
  23581. enumerable: true,
  23582. configurable: true
  23583. });
  23584. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23585. get: function () {
  23586. return this._ignore;
  23587. },
  23588. set: function (b) {
  23589. this._ignore = b;
  23590. },
  23591. enumerable: true,
  23592. configurable: true
  23593. });
  23594. return ClickInfo;
  23595. }());
  23596. /**
  23597. * This class is used by the onRenderingGroupObservable
  23598. */
  23599. var RenderingGroupInfo = /** @class */ (function () {
  23600. function RenderingGroupInfo() {
  23601. }
  23602. /**
  23603. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23604. * This stage will be fired no matter what
  23605. */
  23606. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23607. /**
  23608. * Called before opaque object are rendered.
  23609. * This stage will be fired only if there's 3D Opaque content to render
  23610. */
  23611. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23612. /**
  23613. * Called after the opaque objects are rendered and before the transparent ones
  23614. * This stage will be fired only if there's 3D transparent content to render
  23615. */
  23616. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23617. /**
  23618. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23619. * This stage will be fired no matter what
  23620. */
  23621. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  23622. return RenderingGroupInfo;
  23623. }());
  23624. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  23625. /**
  23626. * Represents a scene to be rendered by the engine.
  23627. * @see http://doc.babylonjs.com/features/scene
  23628. */
  23629. var Scene = /** @class */ (function () {
  23630. /**
  23631. * Creates a new Scene
  23632. * @param engine defines the engine to use to render this scene
  23633. */
  23634. function Scene(engine) {
  23635. // Members
  23636. /**
  23637. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  23638. */
  23639. this.autoClear = true;
  23640. /**
  23641. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  23642. */
  23643. this.autoClearDepthAndStencil = true;
  23644. /**
  23645. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  23646. */
  23647. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  23648. /**
  23649. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  23650. */
  23651. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  23652. this._forceWireframe = false;
  23653. this._forcePointsCloud = false;
  23654. /**
  23655. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  23656. */
  23657. this.forceShowBoundingBoxes = false;
  23658. /**
  23659. * Gets or sets a boolean indicating if animations are enabled
  23660. */
  23661. this.animationsEnabled = true;
  23662. this._animationPropertiesOverride = null;
  23663. /**
  23664. * Gets or sets a boolean indicating if a constant deltatime has to be used
  23665. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  23666. */
  23667. this.useConstantAnimationDeltaTime = false;
  23668. /**
  23669. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  23670. * Please note that it requires to run a ray cast through the scene on every frame
  23671. */
  23672. this.constantlyUpdateMeshUnderPointer = false;
  23673. /**
  23674. * Defines the HTML cursor to use when hovering over interactive elements
  23675. */
  23676. this.hoverCursor = "pointer";
  23677. /**
  23678. * Defines the HTML default cursor to use (empty by default)
  23679. */
  23680. this.defaultCursor = "";
  23681. /**
  23682. * This is used to call preventDefault() on pointer down
  23683. * in order to block unwanted artifacts like system double clicks
  23684. */
  23685. this.preventDefaultOnPointerDown = true;
  23686. // Metadata
  23687. /**
  23688. * Gets or sets user defined metadata
  23689. */
  23690. this.metadata = null;
  23691. /**
  23692. * Use this array to add regular expressions used to disable offline support for specific urls
  23693. */
  23694. this.disableOfflineSupportExceptionRules = new Array();
  23695. /**
  23696. * An event triggered when the scene is disposed.
  23697. */
  23698. this.onDisposeObservable = new BABYLON.Observable();
  23699. this._onDisposeObserver = null;
  23700. /**
  23701. * An event triggered before rendering the scene (right after animations and physics)
  23702. */
  23703. this.onBeforeRenderObservable = new BABYLON.Observable();
  23704. this._onBeforeRenderObserver = null;
  23705. /**
  23706. * An event triggered after rendering the scene
  23707. */
  23708. this.onAfterRenderObservable = new BABYLON.Observable();
  23709. this._onAfterRenderObserver = null;
  23710. /**
  23711. * An event triggered before animating the scene
  23712. */
  23713. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  23714. /**
  23715. * An event triggered after animations processing
  23716. */
  23717. this.onAfterAnimationsObservable = new BABYLON.Observable();
  23718. /**
  23719. * An event triggered before draw calls are ready to be sent
  23720. */
  23721. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  23722. /**
  23723. * An event triggered after draw calls have been sent
  23724. */
  23725. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  23726. /**
  23727. * An event triggered when physic simulation is about to be run
  23728. */
  23729. this.onBeforePhysicsObservable = new BABYLON.Observable();
  23730. /**
  23731. * An event triggered when physic simulation has been done
  23732. */
  23733. this.onAfterPhysicsObservable = new BABYLON.Observable();
  23734. /**
  23735. * An event triggered when the scene is ready
  23736. */
  23737. this.onReadyObservable = new BABYLON.Observable();
  23738. /**
  23739. * An event triggered before rendering a camera
  23740. */
  23741. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  23742. this._onBeforeCameraRenderObserver = null;
  23743. /**
  23744. * An event triggered after rendering a camera
  23745. */
  23746. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  23747. this._onAfterCameraRenderObserver = null;
  23748. /**
  23749. * An event triggered when active meshes evaluation is about to start
  23750. */
  23751. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23752. /**
  23753. * An event triggered when active meshes evaluation is done
  23754. */
  23755. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  23756. /**
  23757. * An event triggered when particles rendering is about to start
  23758. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23759. */
  23760. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  23761. /**
  23762. * An event triggered when particles rendering is done
  23763. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  23764. */
  23765. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  23766. /**
  23767. * An event triggered when sprites rendering is about to start
  23768. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23769. */
  23770. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  23771. /**
  23772. * An event triggered when sprites rendering is done
  23773. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  23774. */
  23775. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  23776. /**
  23777. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  23778. */
  23779. this.onDataLoadedObservable = new BABYLON.Observable();
  23780. /**
  23781. * An event triggered when a camera is created
  23782. */
  23783. this.onNewCameraAddedObservable = new BABYLON.Observable();
  23784. /**
  23785. * An event triggered when a camera is removed
  23786. */
  23787. this.onCameraRemovedObservable = new BABYLON.Observable();
  23788. /**
  23789. * An event triggered when a light is created
  23790. */
  23791. this.onNewLightAddedObservable = new BABYLON.Observable();
  23792. /**
  23793. * An event triggered when a light is removed
  23794. */
  23795. this.onLightRemovedObservable = new BABYLON.Observable();
  23796. /**
  23797. * An event triggered when a geometry is created
  23798. */
  23799. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  23800. /**
  23801. * An event triggered when a geometry is removed
  23802. */
  23803. this.onGeometryRemovedObservable = new BABYLON.Observable();
  23804. /**
  23805. * An event triggered when a transform node is created
  23806. */
  23807. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  23808. /**
  23809. * An event triggered when a transform node is removed
  23810. */
  23811. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  23812. /**
  23813. * An event triggered when a mesh is created
  23814. */
  23815. this.onNewMeshAddedObservable = new BABYLON.Observable();
  23816. /**
  23817. * An event triggered when a mesh is removed
  23818. */
  23819. this.onMeshRemovedObservable = new BABYLON.Observable();
  23820. /**
  23821. * An event triggered when render targets are about to be rendered
  23822. * Can happen multiple times per frame.
  23823. */
  23824. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  23825. /**
  23826. * An event triggered when render targets were rendered.
  23827. * Can happen multiple times per frame.
  23828. */
  23829. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  23830. /**
  23831. * An event triggered before calculating deterministic simulation step
  23832. */
  23833. this.onBeforeStepObservable = new BABYLON.Observable();
  23834. /**
  23835. * An event triggered after calculating deterministic simulation step
  23836. */
  23837. this.onAfterStepObservable = new BABYLON.Observable();
  23838. /**
  23839. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  23840. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  23841. * 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)
  23842. */
  23843. this.onRenderingGroupObservable = new BABYLON.Observable();
  23844. // Animations
  23845. /**
  23846. * Gets a list of Animations associated with the scene
  23847. */
  23848. this.animations = [];
  23849. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  23850. /**
  23851. * 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).
  23852. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  23853. */
  23854. this.onPrePointerObservable = new BABYLON.Observable();
  23855. /**
  23856. * Observable event triggered each time an input event is received from the rendering canvas
  23857. */
  23858. this.onPointerObservable = new BABYLON.Observable();
  23859. this._meshPickProceed = false;
  23860. this._currentPickResult = null;
  23861. this._previousPickResult = null;
  23862. this._totalPointersPressed = 0;
  23863. this._doubleClickOccured = false;
  23864. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  23865. this.cameraToUseForPointers = null;
  23866. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  23867. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  23868. this._startingPointerTime = 0;
  23869. this._previousStartingPointerTime = 0;
  23870. this._pointerCaptures = {};
  23871. // Deterministic lockstep
  23872. this._timeAccumulator = 0;
  23873. this._currentStepId = 0;
  23874. this._currentInternalStep = 0;
  23875. // Keyboard
  23876. /**
  23877. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  23878. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  23879. */
  23880. this.onPreKeyboardObservable = new BABYLON.Observable();
  23881. /**
  23882. * Observable event triggered each time an keyboard event is received from the hosting window
  23883. */
  23884. this.onKeyboardObservable = new BABYLON.Observable();
  23885. // Coordinates system
  23886. this._useRightHandedSystem = false;
  23887. // Fog
  23888. this._fogEnabled = true;
  23889. this._fogMode = Scene.FOGMODE_NONE;
  23890. /**
  23891. * Gets or sets the fog color to use
  23892. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23893. */
  23894. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  23895. /**
  23896. * Gets or sets the fog density to use
  23897. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23898. */
  23899. this.fogDensity = 0.1;
  23900. /**
  23901. * Gets or sets the fog start distance to use
  23902. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23903. */
  23904. this.fogStart = 0;
  23905. /**
  23906. * Gets or sets the fog end distance to use
  23907. * @see http://doc.babylonjs.com/babylon101/environment#fog
  23908. */
  23909. this.fogEnd = 1000.0;
  23910. // Lights
  23911. this._shadowsEnabled = true;
  23912. this._lightsEnabled = true;
  23913. /**
  23914. * All of the lights added to this scene
  23915. * @see http://doc.babylonjs.com/babylon101/lights
  23916. */
  23917. this.lights = new Array();
  23918. // Cameras
  23919. /** All of the cameras added to this scene.
  23920. * @see http://doc.babylonjs.com/babylon101/cameras
  23921. */
  23922. this.cameras = new Array();
  23923. /** All of the active cameras added to this scene. */
  23924. this.activeCameras = new Array();
  23925. // Meshes
  23926. /**
  23927. * All of the tranform nodes added to this scene
  23928. * @see http://doc.babylonjs.com/how_to/transformnode
  23929. */
  23930. this.transformNodes = new Array();
  23931. /**
  23932. * All of the (abstract) meshes added to this scene
  23933. */
  23934. this.meshes = new Array();
  23935. /**
  23936. * All of the animation groups added to this scene
  23937. * @see http://doc.babylonjs.com/how_to/group
  23938. */
  23939. this.animationGroups = new Array();
  23940. // Geometries
  23941. this._geometries = new Array();
  23942. /**
  23943. * All of the materials added to this scene
  23944. * @see http://doc.babylonjs.com/babylon101/materials
  23945. */
  23946. this.materials = new Array();
  23947. /**
  23948. * All of the multi-materials added to this scene
  23949. * @see http://doc.babylonjs.com/how_to/multi_materials
  23950. */
  23951. this.multiMaterials = new Array();
  23952. // Textures
  23953. this._texturesEnabled = true;
  23954. /**
  23955. * All of the textures added to this scene
  23956. */
  23957. this.textures = new Array();
  23958. // Particles
  23959. /**
  23960. * Gets or sets a boolean indicating if particles are enabled on this scene
  23961. */
  23962. this.particlesEnabled = true;
  23963. /**
  23964. * All of the particle systems added to this scene
  23965. * @see http://doc.babylonjs.com/babylon101/particles
  23966. */
  23967. this.particleSystems = new Array();
  23968. // Sprites
  23969. /**
  23970. * Gets or sets a boolean indicating if sprites are enabled on this scene
  23971. */
  23972. this.spritesEnabled = true;
  23973. /**
  23974. * All of the sprite managers added to this scene
  23975. * @see http://doc.babylonjs.com/babylon101/sprites
  23976. */
  23977. this.spriteManagers = new Array();
  23978. /**
  23979. * The list of layers (background and foreground) of the scene
  23980. */
  23981. this.layers = new Array();
  23982. /**
  23983. * The list of effect layers (highlights/glow) added to the scene
  23984. * @see http://doc.babylonjs.com/how_to/highlight_layer
  23985. * @see http://doc.babylonjs.com/how_to/glow_layer
  23986. */
  23987. this.effectLayers = new Array();
  23988. // Skeletons
  23989. this._skeletonsEnabled = true;
  23990. /**
  23991. * The list of skeletons added to the scene
  23992. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  23993. */
  23994. this.skeletons = new Array();
  23995. // Morph targets
  23996. /**
  23997. * The list of morph target managers added to the scene
  23998. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  23999. */
  24000. this.morphTargetManagers = new Array();
  24001. // Lens flares
  24002. /**
  24003. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24004. */
  24005. this.lensFlaresEnabled = true;
  24006. /**
  24007. * The list of lens flare system added to the scene
  24008. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24009. */
  24010. this.lensFlareSystems = new Array();
  24011. // Collisions
  24012. /**
  24013. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24014. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24015. */
  24016. this.collisionsEnabled = true;
  24017. /**
  24018. * Defines the gravity applied to this scene (used only for collisions)
  24019. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24020. */
  24021. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24022. // Postprocesses
  24023. /**
  24024. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24025. */
  24026. this.postProcessesEnabled = true;
  24027. /**
  24028. * The list of postprocesses added to the scene
  24029. */
  24030. this.postProcesses = new Array();
  24031. // Customs render targets
  24032. /**
  24033. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24034. */
  24035. this.renderTargetsEnabled = true;
  24036. /**
  24037. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24038. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24039. */
  24040. this.dumpNextRenderTargets = false;
  24041. /**
  24042. * The list of user defined render targets added to the scene
  24043. */
  24044. this.customRenderTargets = new Array();
  24045. /**
  24046. * Gets the list of meshes imported to the scene through SceneLoader
  24047. */
  24048. this.importedMeshesFiles = new Array();
  24049. // Probes
  24050. /**
  24051. * Gets or sets a boolean indicating if probes are enabled on this scene
  24052. */
  24053. this.probesEnabled = true;
  24054. /**
  24055. * The list of reflection probes added to the scene
  24056. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24057. */
  24058. this.reflectionProbes = new Array();
  24059. /** @hidden */
  24060. this._actionManagers = new Array();
  24061. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24062. // Procedural textures
  24063. /**
  24064. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24065. */
  24066. this.proceduralTexturesEnabled = true;
  24067. /**
  24068. * The list of procedural textures added to the scene
  24069. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24070. */
  24071. this.proceduralTextures = new Array();
  24072. /**
  24073. * The list of sound tracks added to the scene
  24074. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24075. */
  24076. this.soundTracks = new Array();
  24077. this._audioEnabled = true;
  24078. this._headphone = false;
  24079. // Performance counters
  24080. this._totalVertices = new BABYLON.PerfCounter();
  24081. /** @hidden */
  24082. this._activeIndices = new BABYLON.PerfCounter();
  24083. /** @hidden */
  24084. this._activeParticles = new BABYLON.PerfCounter();
  24085. /** @hidden */
  24086. this._activeBones = new BABYLON.PerfCounter();
  24087. this._animationTime = 0;
  24088. /**
  24089. * Gets or sets a general scale for animation speed
  24090. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24091. */
  24092. this.animationTimeScale = 1;
  24093. this._renderId = 0;
  24094. this._executeWhenReadyTimeoutId = -1;
  24095. this._intermediateRendering = false;
  24096. this._viewUpdateFlag = -1;
  24097. this._projectionUpdateFlag = -1;
  24098. this._alternateViewUpdateFlag = -1;
  24099. this._alternateProjectionUpdateFlag = -1;
  24100. /** @hidden */
  24101. this._toBeDisposed = new BABYLON.SmartArray(256);
  24102. this._activeRequests = new Array();
  24103. this._pendingData = new Array();
  24104. this._isDisposed = false;
  24105. /**
  24106. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24107. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24108. */
  24109. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24110. this._activeMeshes = new BABYLON.SmartArray(256);
  24111. this._processedMaterials = new BABYLON.SmartArray(256);
  24112. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24113. /** @hidden */
  24114. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24115. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24116. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24117. /** @hidden */
  24118. this._activeAnimatables = new Array();
  24119. this._transformMatrix = BABYLON.Matrix.Zero();
  24120. this._useAlternateCameraConfiguration = false;
  24121. this._alternateRendering = false;
  24122. /**
  24123. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24124. * This is useful if there are more lights that the maximum simulteanous authorized
  24125. */
  24126. this.requireLightSorting = false;
  24127. this._depthRenderer = {};
  24128. this._activeMeshesFrozen = false;
  24129. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24130. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24131. this._engine.scenes.push(this);
  24132. this._uid = null;
  24133. this._renderingManager = new BABYLON.RenderingManager(this);
  24134. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24135. if (BABYLON.OutlineRenderer) {
  24136. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24137. }
  24138. if (BABYLON.Tools.IsWindowObjectExist()) {
  24139. this.attachControl();
  24140. }
  24141. //simplification queue
  24142. if (BABYLON.SimplificationQueue) {
  24143. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24144. }
  24145. //collision coordinator initialization. For now legacy per default.
  24146. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24147. // Uniform Buffer
  24148. this._createUbo();
  24149. // Default Image processing definition.
  24150. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24151. }
  24152. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24153. /** The fog is deactivated */
  24154. get: function () {
  24155. return Scene._FOGMODE_NONE;
  24156. },
  24157. enumerable: true,
  24158. configurable: true
  24159. });
  24160. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24161. /** The fog density is following an exponential function */
  24162. get: function () {
  24163. return Scene._FOGMODE_EXP;
  24164. },
  24165. enumerable: true,
  24166. configurable: true
  24167. });
  24168. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24169. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24170. get: function () {
  24171. return Scene._FOGMODE_EXP2;
  24172. },
  24173. enumerable: true,
  24174. configurable: true
  24175. });
  24176. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24177. /** The fog density is following a linear function. */
  24178. get: function () {
  24179. return Scene._FOGMODE_LINEAR;
  24180. },
  24181. enumerable: true,
  24182. configurable: true
  24183. });
  24184. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24185. /**
  24186. * Texture used in all pbr material as the reflection texture.
  24187. * As in the majority of the scene they are the same (exception for multi room and so on),
  24188. * this is easier to reference from here than from all the materials.
  24189. */
  24190. get: function () {
  24191. return this._environmentTexture;
  24192. },
  24193. /**
  24194. * Texture used in all pbr material as the reflection texture.
  24195. * As in the majority of the scene they are the same (exception for multi room and so on),
  24196. * this is easier to set here than in all the materials.
  24197. */
  24198. set: function (value) {
  24199. if (this._environmentTexture === value) {
  24200. return;
  24201. }
  24202. this._environmentTexture = value;
  24203. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24204. },
  24205. enumerable: true,
  24206. configurable: true
  24207. });
  24208. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24209. /**
  24210. * Default image processing configuration used either in the rendering
  24211. * Forward main pass or through the imageProcessingPostProcess if present.
  24212. * As in the majority of the scene they are the same (exception for multi camera),
  24213. * this is easier to reference from here than from all the materials and post process.
  24214. *
  24215. * No setter as we it is a shared configuration, you can set the values instead.
  24216. */
  24217. get: function () {
  24218. return this._imageProcessingConfiguration;
  24219. },
  24220. enumerable: true,
  24221. configurable: true
  24222. });
  24223. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24224. get: function () {
  24225. return this._forceWireframe;
  24226. },
  24227. /**
  24228. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24229. */
  24230. set: function (value) {
  24231. if (this._forceWireframe === value) {
  24232. return;
  24233. }
  24234. this._forceWireframe = value;
  24235. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24236. },
  24237. enumerable: true,
  24238. configurable: true
  24239. });
  24240. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24241. get: function () {
  24242. return this._forcePointsCloud;
  24243. },
  24244. /**
  24245. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24246. */
  24247. set: function (value) {
  24248. if (this._forcePointsCloud === value) {
  24249. return;
  24250. }
  24251. this._forcePointsCloud = value;
  24252. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24253. },
  24254. enumerable: true,
  24255. configurable: true
  24256. });
  24257. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24258. /**
  24259. * Gets or sets the animation properties override
  24260. */
  24261. get: function () {
  24262. return this._animationPropertiesOverride;
  24263. },
  24264. set: function (value) {
  24265. this._animationPropertiesOverride = value;
  24266. },
  24267. enumerable: true,
  24268. configurable: true
  24269. });
  24270. Object.defineProperty(Scene.prototype, "onDispose", {
  24271. /** Sets a function to be executed when this scene is disposed. */
  24272. set: function (callback) {
  24273. if (this._onDisposeObserver) {
  24274. this.onDisposeObservable.remove(this._onDisposeObserver);
  24275. }
  24276. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24277. },
  24278. enumerable: true,
  24279. configurable: true
  24280. });
  24281. Object.defineProperty(Scene.prototype, "beforeRender", {
  24282. /** Sets a function to be executed before rendering this scene */
  24283. set: function (callback) {
  24284. if (this._onBeforeRenderObserver) {
  24285. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24286. }
  24287. if (callback) {
  24288. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24289. }
  24290. },
  24291. enumerable: true,
  24292. configurable: true
  24293. });
  24294. Object.defineProperty(Scene.prototype, "afterRender", {
  24295. /** Sets a function to be executed after rendering this scene */
  24296. set: function (callback) {
  24297. if (this._onAfterRenderObserver) {
  24298. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24299. }
  24300. if (callback) {
  24301. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24302. }
  24303. },
  24304. enumerable: true,
  24305. configurable: true
  24306. });
  24307. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24308. /** Sets a function to be executed before rendering a camera*/
  24309. set: function (callback) {
  24310. if (this._onBeforeCameraRenderObserver) {
  24311. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24312. }
  24313. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24314. },
  24315. enumerable: true,
  24316. configurable: true
  24317. });
  24318. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24319. /** Sets a function to be executed after rendering a camera*/
  24320. set: function (callback) {
  24321. if (this._onAfterCameraRenderObserver) {
  24322. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24323. }
  24324. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24325. },
  24326. enumerable: true,
  24327. configurable: true
  24328. });
  24329. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24330. /**
  24331. * Gets the gamepad manager associated with the scene
  24332. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24333. */
  24334. get: function () {
  24335. if (!this._gamepadManager) {
  24336. this._gamepadManager = new BABYLON.GamepadManager(this);
  24337. }
  24338. return this._gamepadManager;
  24339. },
  24340. enumerable: true,
  24341. configurable: true
  24342. });
  24343. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24344. /**
  24345. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24346. */
  24347. get: function () {
  24348. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24349. },
  24350. enumerable: true,
  24351. configurable: true
  24352. });
  24353. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24354. get: function () {
  24355. return this._useRightHandedSystem;
  24356. },
  24357. /**
  24358. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24359. */
  24360. set: function (value) {
  24361. if (this._useRightHandedSystem === value) {
  24362. return;
  24363. }
  24364. this._useRightHandedSystem = value;
  24365. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24366. },
  24367. enumerable: true,
  24368. configurable: true
  24369. });
  24370. /**
  24371. * Sets the step Id used by deterministic lock step
  24372. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24373. * @param newStepId defines the step Id
  24374. */
  24375. Scene.prototype.setStepId = function (newStepId) {
  24376. this._currentStepId = newStepId;
  24377. };
  24378. ;
  24379. /**
  24380. * Gets the step Id used by deterministic lock step
  24381. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24382. * @returns the step Id
  24383. */
  24384. Scene.prototype.getStepId = function () {
  24385. return this._currentStepId;
  24386. };
  24387. ;
  24388. /**
  24389. * Gets the internal step used by deterministic lock step
  24390. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24391. * @returns the internal step
  24392. */
  24393. Scene.prototype.getInternalStep = function () {
  24394. return this._currentInternalStep;
  24395. };
  24396. ;
  24397. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24398. get: function () {
  24399. return this._fogEnabled;
  24400. },
  24401. /**
  24402. * Gets or sets a boolean indicating if fog is enabled on this scene
  24403. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24404. */
  24405. set: function (value) {
  24406. if (this._fogEnabled === value) {
  24407. return;
  24408. }
  24409. this._fogEnabled = value;
  24410. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24411. },
  24412. enumerable: true,
  24413. configurable: true
  24414. });
  24415. Object.defineProperty(Scene.prototype, "fogMode", {
  24416. get: function () {
  24417. return this._fogMode;
  24418. },
  24419. /**
  24420. * Gets or sets the fog mode to use
  24421. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24422. */
  24423. set: function (value) {
  24424. if (this._fogMode === value) {
  24425. return;
  24426. }
  24427. this._fogMode = value;
  24428. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24429. },
  24430. enumerable: true,
  24431. configurable: true
  24432. });
  24433. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24434. get: function () {
  24435. return this._shadowsEnabled;
  24436. },
  24437. /**
  24438. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24439. */
  24440. set: function (value) {
  24441. if (this._shadowsEnabled === value) {
  24442. return;
  24443. }
  24444. this._shadowsEnabled = value;
  24445. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24446. },
  24447. enumerable: true,
  24448. configurable: true
  24449. });
  24450. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24451. get: function () {
  24452. return this._lightsEnabled;
  24453. },
  24454. /**
  24455. * Gets or sets a boolean indicating if lights are enabled on this scene
  24456. */
  24457. set: function (value) {
  24458. if (this._lightsEnabled === value) {
  24459. return;
  24460. }
  24461. this._lightsEnabled = value;
  24462. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24463. },
  24464. enumerable: true,
  24465. configurable: true
  24466. });
  24467. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24468. /** The default material used on meshes when no material is affected */
  24469. get: function () {
  24470. if (!this._defaultMaterial) {
  24471. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24472. }
  24473. return this._defaultMaterial;
  24474. },
  24475. /** The default material used on meshes when no material is affected */
  24476. set: function (value) {
  24477. this._defaultMaterial = value;
  24478. },
  24479. enumerable: true,
  24480. configurable: true
  24481. });
  24482. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24483. get: function () {
  24484. return this._texturesEnabled;
  24485. },
  24486. /**
  24487. * Gets or sets a boolean indicating if textures are enabled on this scene
  24488. */
  24489. set: function (value) {
  24490. if (this._texturesEnabled === value) {
  24491. return;
  24492. }
  24493. this._texturesEnabled = value;
  24494. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24495. },
  24496. enumerable: true,
  24497. configurable: true
  24498. });
  24499. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24500. get: function () {
  24501. return this._skeletonsEnabled;
  24502. },
  24503. /**
  24504. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24505. */
  24506. set: function (value) {
  24507. if (this._skeletonsEnabled === value) {
  24508. return;
  24509. }
  24510. this._skeletonsEnabled = value;
  24511. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24512. },
  24513. enumerable: true,
  24514. configurable: true
  24515. });
  24516. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24517. /**
  24518. * Gets the postprocess render pipeline manager
  24519. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24520. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24521. */
  24522. get: function () {
  24523. if (!this._postProcessRenderPipelineManager) {
  24524. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24525. }
  24526. return this._postProcessRenderPipelineManager;
  24527. },
  24528. enumerable: true,
  24529. configurable: true
  24530. });
  24531. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24532. /**
  24533. * Gets the main soundtrack associated with the scene
  24534. */
  24535. get: function () {
  24536. if (!this._mainSoundTrack) {
  24537. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24538. }
  24539. return this._mainSoundTrack;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24545. /** @hidden */
  24546. get: function () {
  24547. return this._alternateRendering;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24553. /**
  24554. * Gets the list of frustum planes (built from the active camera)
  24555. */
  24556. get: function () {
  24557. return this._frustumPlanes;
  24558. },
  24559. enumerable: true,
  24560. configurable: true
  24561. });
  24562. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24563. /**
  24564. * Gets the current geometry buffer associated to the scene.
  24565. */
  24566. get: function () {
  24567. return this._geometryBufferRenderer;
  24568. },
  24569. /**
  24570. * Sets the current geometry buffer for the scene.
  24571. */
  24572. set: function (geometryBufferRenderer) {
  24573. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24574. this._geometryBufferRenderer = geometryBufferRenderer;
  24575. }
  24576. },
  24577. enumerable: true,
  24578. configurable: true
  24579. });
  24580. Object.defineProperty(Scene.prototype, "debugLayer", {
  24581. /**
  24582. * Gets the debug layer associated with the scene
  24583. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24584. */
  24585. get: function () {
  24586. if (!this._debugLayer) {
  24587. this._debugLayer = new BABYLON.DebugLayer(this);
  24588. }
  24589. return this._debugLayer;
  24590. },
  24591. enumerable: true,
  24592. configurable: true
  24593. });
  24594. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24595. /**
  24596. * Gets a boolean indicating if collisions are processed on a web worker
  24597. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24598. */
  24599. get: function () {
  24600. return this._workerCollisions;
  24601. },
  24602. set: function (enabled) {
  24603. if (!BABYLON.CollisionCoordinatorLegacy) {
  24604. return;
  24605. }
  24606. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24607. this._workerCollisions = enabled;
  24608. if (this.collisionCoordinator) {
  24609. this.collisionCoordinator.destroy();
  24610. }
  24611. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24612. this.collisionCoordinator.init(this);
  24613. },
  24614. enumerable: true,
  24615. configurable: true
  24616. });
  24617. Object.defineProperty(Scene.prototype, "selectionOctree", {
  24618. /**
  24619. * Gets the octree used to boost mesh selection (picking)
  24620. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  24621. */
  24622. get: function () {
  24623. return this._selectionOctree;
  24624. },
  24625. enumerable: true,
  24626. configurable: true
  24627. });
  24628. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  24629. /**
  24630. * Gets the mesh that is currently under the pointer
  24631. */
  24632. get: function () {
  24633. return this._pointerOverMesh;
  24634. },
  24635. enumerable: true,
  24636. configurable: true
  24637. });
  24638. Object.defineProperty(Scene.prototype, "pointerX", {
  24639. /**
  24640. * Gets the current on-screen X position of the pointer
  24641. */
  24642. get: function () {
  24643. return this._pointerX;
  24644. },
  24645. enumerable: true,
  24646. configurable: true
  24647. });
  24648. Object.defineProperty(Scene.prototype, "pointerY", {
  24649. /**
  24650. * Gets the current on-screen Y position of the pointer
  24651. */
  24652. get: function () {
  24653. return this._pointerY;
  24654. },
  24655. enumerable: true,
  24656. configurable: true
  24657. });
  24658. /**
  24659. * Gets the cached material (ie. the latest rendered one)
  24660. * @returns the cached material
  24661. */
  24662. Scene.prototype.getCachedMaterial = function () {
  24663. return this._cachedMaterial;
  24664. };
  24665. /**
  24666. * Gets the cached effect (ie. the latest rendered one)
  24667. * @returns the cached effect
  24668. */
  24669. Scene.prototype.getCachedEffect = function () {
  24670. return this._cachedEffect;
  24671. };
  24672. /**
  24673. * Gets the cached visibility state (ie. the latest rendered one)
  24674. * @returns the cached visibility state
  24675. */
  24676. Scene.prototype.getCachedVisibility = function () {
  24677. return this._cachedVisibility;
  24678. };
  24679. /**
  24680. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  24681. * @param material defines the current material
  24682. * @param effect defines the current effect
  24683. * @param visibility defines the current visibility state
  24684. * @returns true if one parameter is not cached
  24685. */
  24686. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  24687. if (visibility === void 0) { visibility = 1; }
  24688. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  24689. };
  24690. /**
  24691. * Gets the bounding box renderer associated with the scene
  24692. * @returns a BoundingBoxRenderer
  24693. */
  24694. Scene.prototype.getBoundingBoxRenderer = function () {
  24695. if (!this._boundingBoxRenderer) {
  24696. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  24697. }
  24698. return this._boundingBoxRenderer;
  24699. };
  24700. /**
  24701. * Gets the outline renderer associated with the scene
  24702. * @returns a OutlineRenderer
  24703. */
  24704. Scene.prototype.getOutlineRenderer = function () {
  24705. return this._outlineRenderer;
  24706. };
  24707. /**
  24708. * Gets the engine associated with the scene
  24709. * @returns an Engine
  24710. */
  24711. Scene.prototype.getEngine = function () {
  24712. return this._engine;
  24713. };
  24714. /**
  24715. * Gets the total number of vertices rendered per frame
  24716. * @returns the total number of vertices rendered per frame
  24717. */
  24718. Scene.prototype.getTotalVertices = function () {
  24719. return this._totalVertices.current;
  24720. };
  24721. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  24722. /**
  24723. * Gets the performance counter for total vertices
  24724. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24725. */
  24726. get: function () {
  24727. return this._totalVertices;
  24728. },
  24729. enumerable: true,
  24730. configurable: true
  24731. });
  24732. /**
  24733. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  24734. * @returns the total number of active indices rendered per frame
  24735. */
  24736. Scene.prototype.getActiveIndices = function () {
  24737. return this._activeIndices.current;
  24738. };
  24739. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  24740. /**
  24741. * Gets the performance counter for active indices
  24742. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24743. */
  24744. get: function () {
  24745. return this._activeIndices;
  24746. },
  24747. enumerable: true,
  24748. configurable: true
  24749. });
  24750. /**
  24751. * Gets the total number of active particles rendered per frame
  24752. * @returns the total number of active particles rendered per frame
  24753. */
  24754. Scene.prototype.getActiveParticles = function () {
  24755. return this._activeParticles.current;
  24756. };
  24757. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  24758. /**
  24759. * Gets the performance counter for active particles
  24760. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24761. */
  24762. get: function () {
  24763. return this._activeParticles;
  24764. },
  24765. enumerable: true,
  24766. configurable: true
  24767. });
  24768. /**
  24769. * Gets the total number of active bones rendered per frame
  24770. * @returns the total number of active bones rendered per frame
  24771. */
  24772. Scene.prototype.getActiveBones = function () {
  24773. return this._activeBones.current;
  24774. };
  24775. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  24776. /**
  24777. * Gets the performance counter for active bones
  24778. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  24779. */
  24780. get: function () {
  24781. return this._activeBones;
  24782. },
  24783. enumerable: true,
  24784. configurable: true
  24785. });
  24786. /** @hidden */
  24787. Scene.prototype.getInterFramePerfCounter = function () {
  24788. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24789. return 0;
  24790. };
  24791. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  24792. /** @hidden */
  24793. get: function () {
  24794. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24795. return null;
  24796. },
  24797. enumerable: true,
  24798. configurable: true
  24799. });
  24800. /** @hidden */
  24801. Scene.prototype.getLastFrameDuration = function () {
  24802. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  24803. return 0;
  24804. };
  24805. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  24806. /** @hidden */
  24807. get: function () {
  24808. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  24809. return null;
  24810. },
  24811. enumerable: true,
  24812. configurable: true
  24813. });
  24814. /** @hidden */
  24815. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  24816. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  24817. return 0;
  24818. };
  24819. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  24820. /** @hidden */
  24821. get: function () {
  24822. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24823. return null;
  24824. },
  24825. enumerable: true,
  24826. configurable: true
  24827. });
  24828. /**
  24829. * Gets the array of active meshes
  24830. * @returns an array of AbstractMesh
  24831. */
  24832. Scene.prototype.getActiveMeshes = function () {
  24833. return this._activeMeshes;
  24834. };
  24835. /** @hidden */
  24836. Scene.prototype.getRenderTargetsDuration = function () {
  24837. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  24838. return 0;
  24839. };
  24840. /** @hidden */
  24841. Scene.prototype.getRenderDuration = function () {
  24842. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  24843. return 0;
  24844. };
  24845. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  24846. /** @hidden */
  24847. get: function () {
  24848. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24849. return null;
  24850. },
  24851. enumerable: true,
  24852. configurable: true
  24853. });
  24854. /** @hidden */
  24855. Scene.prototype.getParticlesDuration = function () {
  24856. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  24857. return 0;
  24858. };
  24859. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  24860. /** @hidden */
  24861. get: function () {
  24862. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  24863. return null;
  24864. },
  24865. enumerable: true,
  24866. configurable: true
  24867. });
  24868. /** @hidden */
  24869. Scene.prototype.getSpritesDuration = function () {
  24870. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  24871. return 0;
  24872. };
  24873. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  24874. /** @hidden */
  24875. get: function () {
  24876. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  24877. return null;
  24878. },
  24879. enumerable: true,
  24880. configurable: true
  24881. });
  24882. /**
  24883. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  24884. * @returns a number
  24885. */
  24886. Scene.prototype.getAnimationRatio = function () {
  24887. return this._animationRatio;
  24888. };
  24889. /**
  24890. * Gets an unique Id for the current frame
  24891. * @returns a number
  24892. */
  24893. Scene.prototype.getRenderId = function () {
  24894. return this._renderId;
  24895. };
  24896. /** Call this function if you want to manually increment the render Id*/
  24897. Scene.prototype.incrementRenderId = function () {
  24898. this._renderId++;
  24899. };
  24900. Scene.prototype._updatePointerPosition = function (evt) {
  24901. var canvasRect = this._engine.getRenderingCanvasClientRect();
  24902. if (!canvasRect) {
  24903. return;
  24904. }
  24905. this._pointerX = evt.clientX - canvasRect.left;
  24906. this._pointerY = evt.clientY - canvasRect.top;
  24907. this._unTranslatedPointerX = this._pointerX;
  24908. this._unTranslatedPointerY = this._pointerY;
  24909. };
  24910. Scene.prototype._createUbo = function () {
  24911. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24912. this._sceneUbo.addUniform("viewProjection", 16);
  24913. this._sceneUbo.addUniform("view", 16);
  24914. };
  24915. Scene.prototype._createAlternateUbo = function () {
  24916. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  24917. this._alternateSceneUbo.addUniform("viewProjection", 16);
  24918. this._alternateSceneUbo.addUniform("view", 16);
  24919. };
  24920. // Pointers handling
  24921. /**
  24922. * Use this method to simulate a pointer move on a mesh
  24923. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24924. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24925. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24926. * @returns the current scene
  24927. */
  24928. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  24929. var evt = new PointerEvent("pointermove", pointerEventInit);
  24930. return this._processPointerMove(pickResult, evt);
  24931. };
  24932. Scene.prototype._processPointerMove = function (pickResult, evt) {
  24933. var canvas = this._engine.getRenderingCanvas();
  24934. if (!canvas) {
  24935. return this;
  24936. }
  24937. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24938. this.setPointerOverSprite(null);
  24939. this.setPointerOverMesh(pickResult.pickedMesh);
  24940. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  24941. if (this._pointerOverMesh.actionManager.hoverCursor) {
  24942. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  24943. }
  24944. else {
  24945. canvas.style.cursor = this.hoverCursor;
  24946. }
  24947. }
  24948. else {
  24949. canvas.style.cursor = this.defaultCursor;
  24950. }
  24951. }
  24952. else {
  24953. this.setPointerOverMesh(null);
  24954. // Sprites
  24955. pickResult = this.pickSprite(this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  24956. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  24957. this.setPointerOverSprite(pickResult.pickedSprite);
  24958. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  24959. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  24960. }
  24961. else {
  24962. canvas.style.cursor = this.hoverCursor;
  24963. }
  24964. }
  24965. else {
  24966. this.setPointerOverSprite(null);
  24967. // Restore pointer
  24968. canvas.style.cursor = this.defaultCursor;
  24969. }
  24970. }
  24971. if (pickResult) {
  24972. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  24973. if (this.onPointerMove) {
  24974. this.onPointerMove(evt, pickResult, type);
  24975. }
  24976. if (this.onPointerObservable.hasObservers()) {
  24977. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  24978. this.onPointerObservable.notifyObservers(pi, type);
  24979. }
  24980. }
  24981. return this;
  24982. };
  24983. /**
  24984. * Use this method to simulate a pointer down on a mesh
  24985. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  24986. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  24987. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  24988. * @returns the current scene
  24989. */
  24990. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  24991. var evt = new PointerEvent("pointerdown", pointerEventInit);
  24992. return this._processPointerDown(pickResult, evt);
  24993. };
  24994. Scene.prototype._processPointerDown = function (pickResult, evt) {
  24995. var _this = this;
  24996. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  24997. this._pickedDownMesh = pickResult.pickedMesh;
  24998. var actionManager = pickResult.pickedMesh.actionManager;
  24999. if (actionManager) {
  25000. if (actionManager.hasPickTriggers) {
  25001. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25002. switch (evt.button) {
  25003. case 0:
  25004. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25005. break;
  25006. case 1:
  25007. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25008. break;
  25009. case 2:
  25010. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25011. break;
  25012. }
  25013. }
  25014. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25015. window.setTimeout(function () {
  25016. 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);
  25017. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25018. if (_this._totalPointersPressed !== 0 &&
  25019. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25020. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25021. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25022. _this._startingPointerTime = 0;
  25023. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25024. }
  25025. }
  25026. }, Scene.LongPressDelay);
  25027. }
  25028. }
  25029. }
  25030. if (pickResult) {
  25031. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25032. if (this.onPointerDown) {
  25033. this.onPointerDown(evt, pickResult, type);
  25034. }
  25035. if (this.onPointerObservable.hasObservers()) {
  25036. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25037. this.onPointerObservable.notifyObservers(pi, type);
  25038. }
  25039. }
  25040. return this;
  25041. };
  25042. /**
  25043. * Use this method to simulate a pointer up on a mesh
  25044. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25045. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25046. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25047. * @returns the current scene
  25048. */
  25049. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25050. var evt = new PointerEvent("pointerup", pointerEventInit);
  25051. var clickInfo = new ClickInfo();
  25052. clickInfo.singleClick = true;
  25053. clickInfo.ignore = true;
  25054. return this._processPointerUp(pickResult, evt, clickInfo);
  25055. };
  25056. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25057. if (pickResult && pickResult && pickResult.pickedMesh) {
  25058. this._pickedUpMesh = pickResult.pickedMesh;
  25059. if (this._pickedDownMesh === this._pickedUpMesh) {
  25060. if (this.onPointerPick) {
  25061. this.onPointerPick(evt, pickResult);
  25062. }
  25063. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25064. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25065. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25066. this.onPointerObservable.notifyObservers(pi, type_1);
  25067. }
  25068. }
  25069. if (pickResult.pickedMesh.actionManager) {
  25070. if (clickInfo.ignore) {
  25071. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25072. }
  25073. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25074. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25075. }
  25076. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25077. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25078. }
  25079. }
  25080. }
  25081. if (this._pickedDownMesh &&
  25082. this._pickedDownMesh.actionManager &&
  25083. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25084. this._pickedDownMesh !== this._pickedUpMesh) {
  25085. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25086. }
  25087. var type = BABYLON.PointerEventTypes.POINTERUP;
  25088. if (this.onPointerObservable.hasObservers()) {
  25089. if (!clickInfo.ignore) {
  25090. if (!clickInfo.hasSwiped) {
  25091. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25092. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25093. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25094. this.onPointerObservable.notifyObservers(pi, type_2);
  25095. }
  25096. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25097. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25098. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25099. this.onPointerObservable.notifyObservers(pi, type_3);
  25100. }
  25101. }
  25102. }
  25103. else {
  25104. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25105. this.onPointerObservable.notifyObservers(pi, type);
  25106. }
  25107. }
  25108. if (this.onPointerUp) {
  25109. this.onPointerUp(evt, pickResult, type);
  25110. }
  25111. return this;
  25112. };
  25113. /**
  25114. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25115. * @param attachUp defines if you want to attach events to pointerup
  25116. * @param attachDown defines if you want to attach events to pointerdown
  25117. * @param attachMove defines if you want to attach events to pointermove
  25118. */
  25119. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25120. var _this = this;
  25121. if (attachUp === void 0) { attachUp = true; }
  25122. if (attachDown === void 0) { attachDown = true; }
  25123. if (attachMove === void 0) { attachMove = true; }
  25124. this._initActionManager = function (act, clickInfo) {
  25125. if (!_this._meshPickProceed) {
  25126. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25127. _this._currentPickResult = pickResult;
  25128. if (pickResult) {
  25129. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25130. }
  25131. _this._meshPickProceed = true;
  25132. }
  25133. return act;
  25134. };
  25135. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25136. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25137. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25138. btn !== _this._previousButtonPressed) {
  25139. _this._doubleClickOccured = false;
  25140. clickInfo.singleClick = true;
  25141. clickInfo.ignore = false;
  25142. cb(clickInfo, _this._currentPickResult);
  25143. }
  25144. };
  25145. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25146. var clickInfo = new ClickInfo();
  25147. _this._currentPickResult = null;
  25148. var act = null;
  25149. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25150. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25151. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25152. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25153. act = _this._initActionManager(act, clickInfo);
  25154. if (act)
  25155. checkPicking = act.hasPickTriggers;
  25156. }
  25157. if (checkPicking) {
  25158. var btn = evt.button;
  25159. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25160. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25161. if (!clickInfo.hasSwiped) {
  25162. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25163. if (!checkSingleClickImmediately) {
  25164. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25165. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25166. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25167. act = _this._initActionManager(act, clickInfo);
  25168. if (act)
  25169. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25170. }
  25171. }
  25172. if (checkSingleClickImmediately) {
  25173. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25174. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25175. btn !== _this._previousButtonPressed) {
  25176. clickInfo.singleClick = true;
  25177. cb(clickInfo, _this._currentPickResult);
  25178. }
  25179. }
  25180. // at least one double click is required to be check and exclusive double click is enabled
  25181. else {
  25182. // wait that no double click has been raised during the double click delay
  25183. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25184. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25185. }
  25186. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25187. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25188. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25189. act = _this._initActionManager(act, clickInfo);
  25190. if (act)
  25191. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25192. }
  25193. if (checkDoubleClick) {
  25194. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25195. if (btn === _this._previousButtonPressed &&
  25196. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25197. !_this._doubleClickOccured) {
  25198. // pointer has not moved for 2 clicks, it's a double click
  25199. if (!clickInfo.hasSwiped &&
  25200. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25201. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25202. _this._previousStartingPointerTime = 0;
  25203. _this._doubleClickOccured = true;
  25204. clickInfo.doubleClick = true;
  25205. clickInfo.ignore = false;
  25206. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25207. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25208. }
  25209. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25210. cb(clickInfo, _this._currentPickResult);
  25211. }
  25212. // if the two successive clicks are too far, it's just two simple clicks
  25213. else {
  25214. _this._doubleClickOccured = false;
  25215. _this._previousStartingPointerTime = _this._startingPointerTime;
  25216. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25217. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25218. _this._previousButtonPressed = btn;
  25219. if (Scene.ExclusiveDoubleClickMode) {
  25220. if (_this._previousDelayedSimpleClickTimeout) {
  25221. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25222. }
  25223. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25224. cb(clickInfo, _this._previousPickResult);
  25225. }
  25226. else {
  25227. cb(clickInfo, _this._currentPickResult);
  25228. }
  25229. }
  25230. }
  25231. // just the first click of the double has been raised
  25232. else {
  25233. _this._doubleClickOccured = false;
  25234. _this._previousStartingPointerTime = _this._startingPointerTime;
  25235. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25236. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25237. _this._previousButtonPressed = btn;
  25238. }
  25239. }
  25240. }
  25241. }
  25242. clickInfo.ignore = true;
  25243. cb(clickInfo, _this._currentPickResult);
  25244. };
  25245. this._spritePredicate = function (sprite) {
  25246. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25247. };
  25248. this._onPointerMove = function (evt) {
  25249. _this._updatePointerPosition(evt);
  25250. // PreObservable support
  25251. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25252. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25253. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25254. _this.onPrePointerObservable.notifyObservers(pi, type);
  25255. if (pi.skipOnPointerObservable) {
  25256. return;
  25257. }
  25258. }
  25259. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25260. return;
  25261. }
  25262. if (!_this.pointerMovePredicate) {
  25263. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25264. }
  25265. // Meshes
  25266. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25267. _this._processPointerMove(pickResult, evt);
  25268. };
  25269. this._onPointerDown = function (evt) {
  25270. _this._totalPointersPressed++;
  25271. _this._pickedDownMesh = null;
  25272. _this._meshPickProceed = false;
  25273. _this._updatePointerPosition(evt);
  25274. if (_this.preventDefaultOnPointerDown && canvas) {
  25275. evt.preventDefault();
  25276. canvas.focus();
  25277. }
  25278. // PreObservable support
  25279. if (_this.onPrePointerObservable.hasObservers()) {
  25280. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25281. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25282. _this.onPrePointerObservable.notifyObservers(pi, type);
  25283. if (pi.skipOnPointerObservable) {
  25284. return;
  25285. }
  25286. }
  25287. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25288. return;
  25289. }
  25290. _this._pointerCaptures[evt.pointerId] = true;
  25291. _this._startingPointerPosition.x = _this._pointerX;
  25292. _this._startingPointerPosition.y = _this._pointerY;
  25293. _this._startingPointerTime = Date.now();
  25294. if (!_this.pointerDownPredicate) {
  25295. _this.pointerDownPredicate = function (mesh) {
  25296. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25297. };
  25298. }
  25299. // Meshes
  25300. _this._pickedDownMesh = null;
  25301. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25302. _this._processPointerDown(pickResult, evt);
  25303. // Sprites
  25304. _this._pickedDownSprite = null;
  25305. if (_this.spriteManagers.length > 0) {
  25306. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25307. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25308. if (pickResult.pickedSprite.actionManager) {
  25309. _this._pickedDownSprite = pickResult.pickedSprite;
  25310. switch (evt.button) {
  25311. case 0:
  25312. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25313. break;
  25314. case 1:
  25315. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25316. break;
  25317. case 2:
  25318. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25319. break;
  25320. }
  25321. if (pickResult.pickedSprite.actionManager) {
  25322. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25323. }
  25324. }
  25325. }
  25326. }
  25327. };
  25328. this._onPointerUp = function (evt) {
  25329. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25330. return; // So we need to test it the pointer down was pressed before.
  25331. }
  25332. _this._totalPointersPressed--;
  25333. _this._pickedUpMesh = null;
  25334. _this._meshPickProceed = false;
  25335. _this._updatePointerPosition(evt);
  25336. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25337. // PreObservable support
  25338. if (_this.onPrePointerObservable.hasObservers() && !_this._pointerCaptures[evt.pointerId]) {
  25339. if (!clickInfo.ignore) {
  25340. if (!clickInfo.hasSwiped) {
  25341. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25342. var type = BABYLON.PointerEventTypes.POINTERTAP;
  25343. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25344. _this.onPrePointerObservable.notifyObservers(pi, type);
  25345. if (pi.skipOnPointerObservable) {
  25346. return;
  25347. }
  25348. }
  25349. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25350. var type = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25351. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25352. _this.onPrePointerObservable.notifyObservers(pi, type);
  25353. if (pi.skipOnPointerObservable) {
  25354. return;
  25355. }
  25356. }
  25357. }
  25358. }
  25359. else {
  25360. var type = BABYLON.PointerEventTypes.POINTERUP;
  25361. var pi = new BABYLON.PointerInfoPre(type, evt, _this._unTranslatedPointerX, _this._unTranslatedPointerY);
  25362. _this.onPrePointerObservable.notifyObservers(pi, type);
  25363. if (pi.skipOnPointerObservable) {
  25364. return;
  25365. }
  25366. }
  25367. }
  25368. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25369. return;
  25370. }
  25371. _this._pointerCaptures[evt.pointerId] = false;
  25372. if (!_this.pointerUpPredicate) {
  25373. _this.pointerUpPredicate = function (mesh) {
  25374. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25375. };
  25376. }
  25377. // Meshes
  25378. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25379. _this._initActionManager(null, clickInfo);
  25380. }
  25381. if (!pickResult) {
  25382. pickResult = _this._currentPickResult;
  25383. }
  25384. _this._processPointerUp(pickResult, evt, clickInfo);
  25385. // Sprites
  25386. if (!clickInfo.ignore) {
  25387. if (_this.spriteManagers.length > 0) {
  25388. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25389. if (spritePickResult) {
  25390. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25391. if (spritePickResult.pickedSprite.actionManager) {
  25392. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25393. if (spritePickResult.pickedSprite.actionManager) {
  25394. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25395. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25396. }
  25397. }
  25398. }
  25399. }
  25400. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25401. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25402. }
  25403. }
  25404. }
  25405. }
  25406. _this._previousPickResult = _this._currentPickResult;
  25407. });
  25408. };
  25409. this._onKeyDown = function (evt) {
  25410. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25411. if (_this.onPreKeyboardObservable.hasObservers()) {
  25412. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25413. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25414. if (pi.skipOnPointerObservable) {
  25415. return;
  25416. }
  25417. }
  25418. if (_this.onKeyboardObservable.hasObservers()) {
  25419. var pi = new BABYLON.KeyboardInfo(type, evt);
  25420. _this.onKeyboardObservable.notifyObservers(pi, type);
  25421. }
  25422. if (_this.actionManager) {
  25423. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25424. }
  25425. };
  25426. this._onKeyUp = function (evt) {
  25427. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25428. if (_this.onPreKeyboardObservable.hasObservers()) {
  25429. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25430. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25431. if (pi.skipOnPointerObservable) {
  25432. return;
  25433. }
  25434. }
  25435. if (_this.onKeyboardObservable.hasObservers()) {
  25436. var pi = new BABYLON.KeyboardInfo(type, evt);
  25437. _this.onKeyboardObservable.notifyObservers(pi, type);
  25438. }
  25439. if (_this.actionManager) {
  25440. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25441. }
  25442. };
  25443. var engine = this.getEngine();
  25444. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25445. if (!canvas) {
  25446. return;
  25447. }
  25448. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25449. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25450. });
  25451. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25452. if (!canvas) {
  25453. return;
  25454. }
  25455. canvas.removeEventListener("keydown", _this._onKeyDown);
  25456. canvas.removeEventListener("keyup", _this._onKeyUp);
  25457. });
  25458. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25459. var canvas = this._engine.getRenderingCanvas();
  25460. if (!canvas) {
  25461. return;
  25462. }
  25463. if (attachMove) {
  25464. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25465. // Wheel
  25466. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25467. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25468. }
  25469. if (attachDown) {
  25470. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25471. }
  25472. if (attachUp) {
  25473. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25474. }
  25475. canvas.tabIndex = 1;
  25476. };
  25477. /** Detaches all event handlers*/
  25478. Scene.prototype.detachControl = function () {
  25479. var engine = this.getEngine();
  25480. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25481. var canvas = engine.getRenderingCanvas();
  25482. if (!canvas) {
  25483. return;
  25484. }
  25485. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25486. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25487. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25488. if (this._onCanvasBlurObserver) {
  25489. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25490. }
  25491. if (this._onCanvasFocusObserver) {
  25492. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25493. }
  25494. // Wheel
  25495. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25496. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25497. // Keyboard
  25498. canvas.removeEventListener("keydown", this._onKeyDown);
  25499. canvas.removeEventListener("keyup", this._onKeyUp);
  25500. // Observables
  25501. this.onKeyboardObservable.clear();
  25502. this.onPreKeyboardObservable.clear();
  25503. this.onPointerObservable.clear();
  25504. this.onPrePointerObservable.clear();
  25505. };
  25506. /**
  25507. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25508. * Delay loaded resources are not taking in account
  25509. * @return true if all required resources are ready
  25510. */
  25511. Scene.prototype.isReady = function () {
  25512. if (this._isDisposed) {
  25513. return false;
  25514. }
  25515. if (this._pendingData.length > 0) {
  25516. return false;
  25517. }
  25518. var index;
  25519. var engine = this.getEngine();
  25520. // Geometries
  25521. for (index = 0; index < this._geometries.length; index++) {
  25522. var geometry = this._geometries[index];
  25523. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25524. return false;
  25525. }
  25526. }
  25527. // Meshes
  25528. for (index = 0; index < this.meshes.length; index++) {
  25529. var mesh = this.meshes[index];
  25530. if (!mesh.isEnabled()) {
  25531. continue;
  25532. }
  25533. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25534. continue;
  25535. }
  25536. if (!mesh.isReady(true)) {
  25537. return false;
  25538. }
  25539. // Effect layers
  25540. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25541. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25542. var layer = _a[_i];
  25543. if (!layer.hasMesh(mesh)) {
  25544. continue;
  25545. }
  25546. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25547. var subMesh = _c[_b];
  25548. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25549. return false;
  25550. }
  25551. }
  25552. }
  25553. }
  25554. // Post-processes
  25555. if (this.activeCameras && this.activeCameras.length > 0) {
  25556. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25557. var camera = _e[_d];
  25558. if (!camera.isReady(true)) {
  25559. return false;
  25560. }
  25561. }
  25562. }
  25563. else if (this.activeCamera) {
  25564. if (!this.activeCamera.isReady(true)) {
  25565. return false;
  25566. }
  25567. }
  25568. // Particles
  25569. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25570. var particleSystem = _g[_f];
  25571. if (!particleSystem.isReady()) {
  25572. return false;
  25573. }
  25574. }
  25575. return true;
  25576. };
  25577. /** Resets all cached information relative to material (including effect and visibility) */
  25578. Scene.prototype.resetCachedMaterial = function () {
  25579. this._cachedMaterial = null;
  25580. this._cachedEffect = null;
  25581. this._cachedVisibility = null;
  25582. };
  25583. /**
  25584. * Registers a function to be called before every frame render
  25585. * @param func defines the function to register
  25586. */
  25587. Scene.prototype.registerBeforeRender = function (func) {
  25588. this.onBeforeRenderObservable.add(func);
  25589. };
  25590. /**
  25591. * Unregisters a function called before every frame render
  25592. * @param func defines the function to unregister
  25593. */
  25594. Scene.prototype.unregisterBeforeRender = function (func) {
  25595. this.onBeforeRenderObservable.removeCallback(func);
  25596. };
  25597. /**
  25598. * Registers a function to be called after every frame render
  25599. * @param func defines the function to register
  25600. */
  25601. Scene.prototype.registerAfterRender = function (func) {
  25602. this.onAfterRenderObservable.add(func);
  25603. };
  25604. /**
  25605. * Unregisters a function called after every frame render
  25606. * @param func defines the function to unregister
  25607. */
  25608. Scene.prototype.unregisterAfterRender = function (func) {
  25609. this.onAfterRenderObservable.removeCallback(func);
  25610. };
  25611. Scene.prototype._executeOnceBeforeRender = function (func) {
  25612. var _this = this;
  25613. var execFunc = function () {
  25614. func();
  25615. setTimeout(function () {
  25616. _this.unregisterBeforeRender(execFunc);
  25617. });
  25618. };
  25619. this.registerBeforeRender(execFunc);
  25620. };
  25621. /**
  25622. * The provided function will run before render once and will be disposed afterwards.
  25623. * A timeout delay can be provided so that the function will be executed in N ms.
  25624. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  25625. * @param func The function to be executed.
  25626. * @param timeout optional delay in ms
  25627. */
  25628. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  25629. var _this = this;
  25630. if (timeout !== undefined) {
  25631. setTimeout(function () {
  25632. _this._executeOnceBeforeRender(func);
  25633. }, timeout);
  25634. }
  25635. else {
  25636. this._executeOnceBeforeRender(func);
  25637. }
  25638. };
  25639. /** @hidden */
  25640. Scene.prototype._addPendingData = function (data) {
  25641. this._pendingData.push(data);
  25642. };
  25643. /** @hidden */
  25644. Scene.prototype._removePendingData = function (data) {
  25645. var wasLoading = this.isLoading;
  25646. var index = this._pendingData.indexOf(data);
  25647. if (index !== -1) {
  25648. this._pendingData.splice(index, 1);
  25649. }
  25650. if (wasLoading && !this.isLoading) {
  25651. this.onDataLoadedObservable.notifyObservers(this);
  25652. }
  25653. };
  25654. /**
  25655. * Returns the number of items waiting to be loaded
  25656. * @returns the number of items waiting to be loaded
  25657. */
  25658. Scene.prototype.getWaitingItemsCount = function () {
  25659. return this._pendingData.length;
  25660. };
  25661. Object.defineProperty(Scene.prototype, "isLoading", {
  25662. /**
  25663. * Returns a boolean indicating if the scene is still loading data
  25664. */
  25665. get: function () {
  25666. return this._pendingData.length > 0;
  25667. },
  25668. enumerable: true,
  25669. configurable: true
  25670. });
  25671. /**
  25672. * Registers a function to be executed when the scene is ready
  25673. * @param {Function} func - the function to be executed
  25674. */
  25675. Scene.prototype.executeWhenReady = function (func) {
  25676. var _this = this;
  25677. this.onReadyObservable.add(func);
  25678. if (this._executeWhenReadyTimeoutId !== -1) {
  25679. return;
  25680. }
  25681. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25682. _this._checkIsReady();
  25683. }, 150);
  25684. };
  25685. /**
  25686. * Returns a promise that resolves when the scene is ready
  25687. * @returns A promise that resolves when the scene is ready
  25688. */
  25689. Scene.prototype.whenReadyAsync = function () {
  25690. var _this = this;
  25691. return new Promise(function (resolve) {
  25692. _this.executeWhenReady(function () {
  25693. resolve();
  25694. });
  25695. });
  25696. };
  25697. /** @hidden */
  25698. Scene.prototype._checkIsReady = function () {
  25699. var _this = this;
  25700. if (this.isReady()) {
  25701. this.onReadyObservable.notifyObservers(this);
  25702. this.onReadyObservable.clear();
  25703. this._executeWhenReadyTimeoutId = -1;
  25704. return;
  25705. }
  25706. this._executeWhenReadyTimeoutId = setTimeout(function () {
  25707. _this._checkIsReady();
  25708. }, 150);
  25709. };
  25710. // Animations
  25711. /**
  25712. * Will start the animation sequence of a given target
  25713. * @param target defines the target
  25714. * @param from defines from which frame should animation start
  25715. * @param to defines until which frame should animation run.
  25716. * @param weight defines the weight to apply to the animation (1.0 by default)
  25717. * @param loop defines if the animation loops
  25718. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25719. * @param onAnimationEnd defines the function to be executed when the animation ends
  25720. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25721. * @returns the animatable object created for this animation
  25722. */
  25723. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  25724. if (weight === void 0) { weight = 1.0; }
  25725. if (speedRatio === void 0) { speedRatio = 1.0; }
  25726. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  25727. returnedAnimatable.weight = weight;
  25728. return returnedAnimatable;
  25729. };
  25730. /**
  25731. * Will start the animation sequence of a given target
  25732. * @param target defines the target
  25733. * @param from defines from which frame should animation start
  25734. * @param to defines until which frame should animation run.
  25735. * @param loop defines if the animation loops
  25736. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  25737. * @param onAnimationEnd defines the function to be executed when the animation ends
  25738. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  25739. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  25740. * @returns the animatable object created for this animation
  25741. */
  25742. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  25743. if (speedRatio === void 0) { speedRatio = 1.0; }
  25744. if (stopCurrent === void 0) { stopCurrent = true; }
  25745. if (from > to && speedRatio > 0) {
  25746. speedRatio *= -1;
  25747. }
  25748. if (stopCurrent) {
  25749. this.stopAnimation(target);
  25750. }
  25751. if (!animatable) {
  25752. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  25753. }
  25754. // Local animations
  25755. if (target.animations) {
  25756. animatable.appendAnimations(target, target.animations);
  25757. }
  25758. // Children animations
  25759. if (target.getAnimatables) {
  25760. var animatables = target.getAnimatables();
  25761. for (var index = 0; index < animatables.length; index++) {
  25762. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  25763. }
  25764. }
  25765. animatable.reset();
  25766. return animatable;
  25767. };
  25768. /**
  25769. * Begin a new animation on a given node
  25770. * @param target defines the target where the animation will take place
  25771. * @param animations defines the list of animations to start
  25772. * @param from defines the initial value
  25773. * @param to defines the final value
  25774. * @param loop defines if you want animation to loop (off by default)
  25775. * @param speedRatio defines the speed ratio to apply to all animations
  25776. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25777. * @returns the list of created animatables
  25778. */
  25779. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25780. if (speedRatio === undefined) {
  25781. speedRatio = 1.0;
  25782. }
  25783. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  25784. return animatable;
  25785. };
  25786. /**
  25787. * Begin a new animation on a given node and its hierarchy
  25788. * @param target defines the root node where the animation will take place
  25789. * @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.
  25790. * @param animations defines the list of animations to start
  25791. * @param from defines the initial value
  25792. * @param to defines the final value
  25793. * @param loop defines if you want animation to loop (off by default)
  25794. * @param speedRatio defines the speed ratio to apply to all animations
  25795. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  25796. * @returns the list of animatables created for all nodes
  25797. */
  25798. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  25799. var children = target.getDescendants(directDescendantsOnly);
  25800. var result = [];
  25801. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  25802. var child = children_1[_i];
  25803. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  25804. }
  25805. return result;
  25806. };
  25807. /**
  25808. * Gets the animatable associated with a specific target
  25809. * @param target defines the target of the animatable
  25810. * @returns the required animatable if found
  25811. */
  25812. Scene.prototype.getAnimatableByTarget = function (target) {
  25813. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25814. if (this._activeAnimatables[index].target === target) {
  25815. return this._activeAnimatables[index];
  25816. }
  25817. }
  25818. return null;
  25819. };
  25820. /**
  25821. * Gets all animatables associated with a given target
  25822. * @param target defines the target to look animatables for
  25823. * @returns an array of Animatables
  25824. */
  25825. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  25826. var result = [];
  25827. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25828. if (this._activeAnimatables[index].target === target) {
  25829. result.push(this._activeAnimatables[index]);
  25830. }
  25831. }
  25832. return result;
  25833. };
  25834. Object.defineProperty(Scene.prototype, "animatables", {
  25835. /**
  25836. * Gets all animatable attached to the scene
  25837. */
  25838. get: function () {
  25839. return this._activeAnimatables;
  25840. },
  25841. enumerable: true,
  25842. configurable: true
  25843. });
  25844. /**
  25845. * Will stop the animation of the given target
  25846. * @param target - the target
  25847. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  25848. */
  25849. Scene.prototype.stopAnimation = function (target, animationName) {
  25850. var animatables = this.getAllAnimatablesByTarget(target);
  25851. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  25852. var animatable = animatables_1[_i];
  25853. animatable.stop(animationName);
  25854. }
  25855. };
  25856. /**
  25857. * Stops and removes all animations that have been applied to the scene
  25858. */
  25859. Scene.prototype.stopAllAnimations = function () {
  25860. if (this._activeAnimatables) {
  25861. for (var i = 0; i < this._activeAnimatables.length; i++) {
  25862. this._activeAnimatables[i].stop();
  25863. }
  25864. this._activeAnimatables = [];
  25865. }
  25866. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  25867. var group = _a[_i];
  25868. group.stop();
  25869. }
  25870. };
  25871. Scene.prototype._animate = function () {
  25872. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  25873. return;
  25874. }
  25875. // Getting time
  25876. var now = BABYLON.Tools.Now;
  25877. if (!this._animationTimeLast) {
  25878. if (this._pendingData.length > 0) {
  25879. return;
  25880. }
  25881. this._animationTimeLast = now;
  25882. }
  25883. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  25884. this._animationTime += deltaTime;
  25885. this._animationTimeLast = now;
  25886. for (var index = 0; index < this._activeAnimatables.length; index++) {
  25887. this._activeAnimatables[index]._animate(this._animationTime);
  25888. }
  25889. // Late animation bindings
  25890. this._processLateAnimationBindings();
  25891. };
  25892. /** @hidden */
  25893. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  25894. var target = runtimeAnimation.target;
  25895. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  25896. if (!target._lateAnimationHolders) {
  25897. target._lateAnimationHolders = {};
  25898. }
  25899. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  25900. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  25901. totalWeight: 0,
  25902. animations: [],
  25903. originalValue: originalValue
  25904. };
  25905. }
  25906. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  25907. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  25908. };
  25909. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  25910. var normalizer = 1.0;
  25911. var finalPosition = BABYLON.Tmp.Vector3[0];
  25912. var finalScaling = BABYLON.Tmp.Vector3[1];
  25913. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  25914. var startIndex = 0;
  25915. var originalAnimation = holder.animations[0];
  25916. var originalValue = holder.originalValue;
  25917. var scale = 1;
  25918. if (holder.totalWeight < 1.0) {
  25919. // We need to mix the original value in
  25920. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25921. scale = 1.0 - holder.totalWeight;
  25922. }
  25923. else {
  25924. startIndex = 1;
  25925. // We need to normalize the weights
  25926. normalizer = holder.totalWeight;
  25927. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  25928. scale = originalAnimation.weight / normalizer;
  25929. if (scale == 1) {
  25930. return originalAnimation.currentValue;
  25931. }
  25932. }
  25933. finalScaling.scaleInPlace(scale);
  25934. finalPosition.scaleInPlace(scale);
  25935. finalQuaternion.scaleInPlace(scale);
  25936. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  25937. var runtimeAnimation = holder.animations[animIndex];
  25938. var scale = runtimeAnimation.weight / normalizer;
  25939. var currentPosition = BABYLON.Tmp.Vector3[2];
  25940. var currentScaling = BABYLON.Tmp.Vector3[3];
  25941. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  25942. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  25943. currentScaling.scaleAndAddToRef(scale, finalScaling);
  25944. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  25945. currentPosition.scaleAndAddToRef(scale, finalPosition);
  25946. }
  25947. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  25948. return originalAnimation._workValue;
  25949. };
  25950. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  25951. var originalAnimation = holder.animations[0];
  25952. var originalValue = holder.originalValue;
  25953. if (holder.animations.length === 1) {
  25954. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  25955. }
  25956. var normalizer = 1.0;
  25957. var quaternions;
  25958. var weights;
  25959. if (holder.totalWeight < 1.0) {
  25960. var scale = 1.0 - holder.totalWeight;
  25961. quaternions = [];
  25962. weights = [];
  25963. quaternions.push(originalValue);
  25964. weights.push(scale);
  25965. }
  25966. else {
  25967. if (holder.animations.length === 2) { // Slerp as soon as we can
  25968. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  25969. }
  25970. quaternions = [];
  25971. weights = [];
  25972. normalizer = holder.totalWeight;
  25973. }
  25974. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  25975. var runtimeAnimation = holder.animations[animIndex];
  25976. quaternions.push(runtimeAnimation.currentValue);
  25977. weights.push(runtimeAnimation.weight / normalizer);
  25978. }
  25979. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  25980. var cumulativeAmount = 0;
  25981. var cumulativeQuaternion = null;
  25982. for (var index = 0; index < quaternions.length;) {
  25983. if (!cumulativeQuaternion) {
  25984. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  25985. cumulativeAmount = weights[index] + weights[index + 1];
  25986. index += 2;
  25987. continue;
  25988. }
  25989. cumulativeAmount += weights[index];
  25990. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  25991. index++;
  25992. }
  25993. return cumulativeQuaternion;
  25994. };
  25995. Scene.prototype._processLateAnimationBindings = function () {
  25996. if (!this._registeredForLateAnimationBindings.length) {
  25997. return;
  25998. }
  25999. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26000. var target = this._registeredForLateAnimationBindings.data[index];
  26001. for (var path in target._lateAnimationHolders) {
  26002. var holder = target._lateAnimationHolders[path];
  26003. var originalAnimation = holder.animations[0];
  26004. var originalValue = holder.originalValue;
  26005. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26006. var finalValue = void 0;
  26007. if (matrixDecomposeMode) {
  26008. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26009. }
  26010. else {
  26011. var quaternionMode = originalValue.w !== undefined;
  26012. if (quaternionMode) {
  26013. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26014. }
  26015. else {
  26016. var startIndex = 0;
  26017. var normalizer = 1.0;
  26018. if (holder.totalWeight < 1.0) {
  26019. // We need to mix the original value in
  26020. if (originalValue.scale) {
  26021. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26022. }
  26023. else {
  26024. finalValue = originalValue * (1.0 - holder.totalWeight);
  26025. }
  26026. }
  26027. else {
  26028. // We need to normalize the weights
  26029. normalizer = holder.totalWeight;
  26030. var scale_1 = originalAnimation.weight / normalizer;
  26031. if (scale_1 !== 1) {
  26032. if (originalAnimation.currentValue.scale) {
  26033. finalValue = originalAnimation.currentValue.scale(scale_1);
  26034. }
  26035. else {
  26036. finalValue = originalAnimation.currentValue * scale_1;
  26037. }
  26038. }
  26039. else {
  26040. finalValue = originalAnimation.currentValue;
  26041. }
  26042. startIndex = 1;
  26043. }
  26044. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26045. var runtimeAnimation = holder.animations[animIndex];
  26046. var scale = runtimeAnimation.weight / normalizer;
  26047. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26048. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26049. }
  26050. else {
  26051. finalValue += runtimeAnimation.currentValue * scale;
  26052. }
  26053. }
  26054. }
  26055. }
  26056. target[path] = finalValue;
  26057. }
  26058. target._lateAnimationHolders = {};
  26059. }
  26060. this._registeredForLateAnimationBindings.reset();
  26061. };
  26062. // Matrix
  26063. /** @hidden */
  26064. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26065. this._useAlternateCameraConfiguration = active;
  26066. };
  26067. /**
  26068. * Gets the current view matrix
  26069. * @returns a Matrix
  26070. */
  26071. Scene.prototype.getViewMatrix = function () {
  26072. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26073. };
  26074. /**
  26075. * Gets the current projection matrix
  26076. * @returns a Matrix
  26077. */
  26078. Scene.prototype.getProjectionMatrix = function () {
  26079. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26080. };
  26081. /**
  26082. * Gets the current transform matrix
  26083. * @returns a Matrix made of View * Projection
  26084. */
  26085. Scene.prototype.getTransformMatrix = function () {
  26086. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26087. };
  26088. /**
  26089. * Sets the current transform matrix
  26090. * @param view defines the View matrix to use
  26091. * @param projection defines the Projection matrix to use
  26092. */
  26093. Scene.prototype.setTransformMatrix = function (view, projection) {
  26094. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26095. return;
  26096. }
  26097. this._viewUpdateFlag = view.updateFlag;
  26098. this._projectionUpdateFlag = projection.updateFlag;
  26099. this._viewMatrix = view;
  26100. this._projectionMatrix = projection;
  26101. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26102. // Update frustum
  26103. if (!this._frustumPlanes) {
  26104. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26105. }
  26106. else {
  26107. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26108. }
  26109. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26110. var otherCamera = this.activeCamera._alternateCamera;
  26111. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26112. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26113. }
  26114. if (this._sceneUbo.useUbo) {
  26115. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26116. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26117. this._sceneUbo.update();
  26118. }
  26119. };
  26120. /** @hidden */
  26121. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26122. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26123. return;
  26124. }
  26125. this._alternateViewUpdateFlag = view.updateFlag;
  26126. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26127. this._alternateViewMatrix = view;
  26128. this._alternateProjectionMatrix = projection;
  26129. if (!this._alternateTransformMatrix) {
  26130. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26131. }
  26132. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26133. if (!this._alternateSceneUbo) {
  26134. this._createAlternateUbo();
  26135. }
  26136. if (this._alternateSceneUbo.useUbo) {
  26137. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26138. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26139. this._alternateSceneUbo.update();
  26140. }
  26141. };
  26142. /**
  26143. * Gets the uniform buffer used to store scene data
  26144. * @returns a UniformBuffer
  26145. */
  26146. Scene.prototype.getSceneUniformBuffer = function () {
  26147. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26148. };
  26149. /**
  26150. * Gets an unique (relatively to the current scene) Id
  26151. * @returns an unique number for the scene
  26152. */
  26153. Scene.prototype.getUniqueId = function () {
  26154. var result = Scene._uniqueIdCounter;
  26155. Scene._uniqueIdCounter++;
  26156. return result;
  26157. };
  26158. /**
  26159. * Add a mesh to the list of scene's meshes
  26160. * @param newMesh defines the mesh to add
  26161. */
  26162. Scene.prototype.addMesh = function (newMesh) {
  26163. this.meshes.push(newMesh);
  26164. //notify the collision coordinator
  26165. if (this.collisionCoordinator) {
  26166. this.collisionCoordinator.onMeshAdded(newMesh);
  26167. }
  26168. newMesh._resyncLightSources();
  26169. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26170. };
  26171. /**
  26172. * Remove a mesh for the list of scene's meshes
  26173. * @param toRemove defines the mesh to remove
  26174. * @param recursive if all child meshes should also be removed from the scene
  26175. * @returns the index where the mesh was in the mesh list
  26176. */
  26177. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26178. var _this = this;
  26179. if (recursive === void 0) { recursive = false; }
  26180. var index = this.meshes.indexOf(toRemove);
  26181. if (index !== -1) {
  26182. // Remove from the scene if mesh found
  26183. this.meshes.splice(index, 1);
  26184. }
  26185. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26186. if (recursive) {
  26187. toRemove.getChildMeshes().forEach(function (m) {
  26188. _this.removeMesh(m);
  26189. });
  26190. }
  26191. return index;
  26192. };
  26193. /**
  26194. * Add a transform node to the list of scene's transform nodes
  26195. * @param newTransformNode defines the transform node to add
  26196. */
  26197. Scene.prototype.addTransformNode = function (newTransformNode) {
  26198. this.transformNodes.push(newTransformNode);
  26199. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26200. };
  26201. /**
  26202. * Remove a transform node for the list of scene's transform nodes
  26203. * @param toRemove defines the transform node to remove
  26204. * @returns the index where the transform node was in the transform node list
  26205. */
  26206. Scene.prototype.removeTransformNode = function (toRemove) {
  26207. var index = this.transformNodes.indexOf(toRemove);
  26208. if (index !== -1) {
  26209. // Remove from the scene if found
  26210. this.transformNodes.splice(index, 1);
  26211. }
  26212. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26213. return index;
  26214. };
  26215. /**
  26216. * Remove a skeleton for the list of scene's skeletons
  26217. * @param toRemove defines the skeleton to remove
  26218. * @returns the index where the skeleton was in the skeleton list
  26219. */
  26220. Scene.prototype.removeSkeleton = function (toRemove) {
  26221. var index = this.skeletons.indexOf(toRemove);
  26222. if (index !== -1) {
  26223. // Remove from the scene if found
  26224. this.skeletons.splice(index, 1);
  26225. }
  26226. return index;
  26227. };
  26228. /**
  26229. * Remove a morph target for the list of scene's morph targets
  26230. * @param toRemove defines the morph target to remove
  26231. * @returns the index where the morph target was in the morph target list
  26232. */
  26233. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26234. var index = this.morphTargetManagers.indexOf(toRemove);
  26235. if (index !== -1) {
  26236. // Remove from the scene if found
  26237. this.morphTargetManagers.splice(index, 1);
  26238. }
  26239. return index;
  26240. };
  26241. /**
  26242. * Remove a light for the list of scene's lights
  26243. * @param toRemove defines the light to remove
  26244. * @returns the index where the light was in the light list
  26245. */
  26246. Scene.prototype.removeLight = function (toRemove) {
  26247. var index = this.lights.indexOf(toRemove);
  26248. if (index !== -1) {
  26249. // Remove from meshes
  26250. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26251. var mesh = _a[_i];
  26252. mesh._removeLightSource(toRemove);
  26253. }
  26254. // Remove from the scene if mesh found
  26255. this.lights.splice(index, 1);
  26256. this.sortLightsByPriority();
  26257. }
  26258. this.onLightRemovedObservable.notifyObservers(toRemove);
  26259. return index;
  26260. };
  26261. /**
  26262. * Remove a camera for the list of scene's cameras
  26263. * @param toRemove defines the camera to remove
  26264. * @returns the index where the camera was in the camera list
  26265. */
  26266. Scene.prototype.removeCamera = function (toRemove) {
  26267. var index = this.cameras.indexOf(toRemove);
  26268. if (index !== -1) {
  26269. // Remove from the scene if mesh found
  26270. this.cameras.splice(index, 1);
  26271. }
  26272. // Remove from activeCameras
  26273. var index2 = this.activeCameras.indexOf(toRemove);
  26274. if (index2 !== -1) {
  26275. // Remove from the scene if mesh found
  26276. this.activeCameras.splice(index2, 1);
  26277. }
  26278. // Reset the activeCamera
  26279. if (this.activeCamera === toRemove) {
  26280. if (this.cameras.length > 0) {
  26281. this.activeCamera = this.cameras[0];
  26282. }
  26283. else {
  26284. this.activeCamera = null;
  26285. }
  26286. }
  26287. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26288. return index;
  26289. };
  26290. /**
  26291. * Remove a particle system for the list of scene's particle systems
  26292. * @param toRemove defines the particle system to remove
  26293. * @returns the index where the particle system was in the particle system list
  26294. */
  26295. Scene.prototype.removeParticleSystem = function (toRemove) {
  26296. var index = this.particleSystems.indexOf(toRemove);
  26297. if (index !== -1) {
  26298. this.particleSystems.splice(index, 1);
  26299. }
  26300. return index;
  26301. };
  26302. /**
  26303. * Remove a animation for the list of scene's animations
  26304. * @param toRemove defines the animation to remove
  26305. * @returns the index where the animation was in the animation list
  26306. */
  26307. Scene.prototype.removeAnimation = function (toRemove) {
  26308. var index = this.animations.indexOf(toRemove);
  26309. if (index !== -1) {
  26310. this.animations.splice(index, 1);
  26311. }
  26312. return index;
  26313. };
  26314. /**
  26315. * Removes the given animation group from this scene.
  26316. * @param toRemove The animation group to remove
  26317. * @returns The index of the removed animation group
  26318. */
  26319. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26320. var index = this.animationGroups.indexOf(toRemove);
  26321. if (index !== -1) {
  26322. this.animationGroups.splice(index, 1);
  26323. }
  26324. return index;
  26325. };
  26326. /**
  26327. * Removes the given multi-material from this scene.
  26328. * @param toRemove The multi-material to remove
  26329. * @returns The index of the removed multi-material
  26330. */
  26331. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26332. var index = this.multiMaterials.indexOf(toRemove);
  26333. if (index !== -1) {
  26334. this.multiMaterials.splice(index, 1);
  26335. }
  26336. return index;
  26337. };
  26338. /**
  26339. * Removes the given material from this scene.
  26340. * @param toRemove The material to remove
  26341. * @returns The index of the removed material
  26342. */
  26343. Scene.prototype.removeMaterial = function (toRemove) {
  26344. var index = this.materials.indexOf(toRemove);
  26345. if (index !== -1) {
  26346. this.materials.splice(index, 1);
  26347. }
  26348. return index;
  26349. };
  26350. /**
  26351. * Removes the given lens flare system from this scene.
  26352. * @param toRemove The lens flare system to remove
  26353. * @returns The index of the removed lens flare system
  26354. */
  26355. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26356. var index = this.lensFlareSystems.indexOf(toRemove);
  26357. if (index !== -1) {
  26358. this.lensFlareSystems.splice(index, 1);
  26359. }
  26360. return index;
  26361. };
  26362. /**
  26363. * Removes the given action manager from this scene.
  26364. * @param toRemove The action manager to remove
  26365. * @returns The index of the removed action manager
  26366. */
  26367. Scene.prototype.removeActionManager = function (toRemove) {
  26368. var index = this._actionManagers.indexOf(toRemove);
  26369. if (index !== -1) {
  26370. this._actionManagers.splice(index, 1);
  26371. }
  26372. return index;
  26373. };
  26374. /**
  26375. * Removes the given effect layer from this scene.
  26376. * @param toRemove defines the effect layer to remove
  26377. * @returns the index of the removed effect layer
  26378. */
  26379. Scene.prototype.removeEffectLayer = function (toRemove) {
  26380. var index = this.effectLayers.indexOf(toRemove);
  26381. if (index !== -1) {
  26382. this.effectLayers.splice(index, 1);
  26383. }
  26384. return index;
  26385. };
  26386. /**
  26387. * Removes the given texture from this scene.
  26388. * @param toRemove The texture to remove
  26389. * @returns The index of the removed texture
  26390. */
  26391. Scene.prototype.removeTexture = function (toRemove) {
  26392. var index = this.textures.indexOf(toRemove);
  26393. if (index !== -1) {
  26394. this.textures.splice(index, 1);
  26395. }
  26396. return index;
  26397. };
  26398. /**
  26399. * Adds the given light to this scene
  26400. * @param newLight The light to add
  26401. */
  26402. Scene.prototype.addLight = function (newLight) {
  26403. this.lights.push(newLight);
  26404. this.sortLightsByPriority();
  26405. // Add light to all meshes (To support if the light is removed and then readded)
  26406. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26407. var mesh = _a[_i];
  26408. if (mesh._lightSources.indexOf(newLight) === -1) {
  26409. mesh._lightSources.push(newLight);
  26410. mesh._resyncLightSources();
  26411. }
  26412. }
  26413. this.onNewLightAddedObservable.notifyObservers(newLight);
  26414. };
  26415. /**
  26416. * Sorts the list list based on light priorities
  26417. */
  26418. Scene.prototype.sortLightsByPriority = function () {
  26419. if (this.requireLightSorting) {
  26420. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26421. }
  26422. };
  26423. /**
  26424. * Adds the given camera to this scene
  26425. * @param newCamera The camera to add
  26426. */
  26427. Scene.prototype.addCamera = function (newCamera) {
  26428. this.cameras.push(newCamera);
  26429. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26430. };
  26431. /**
  26432. * Adds the given skeleton to this scene
  26433. * @param newSkeleton The skeleton to add
  26434. */
  26435. Scene.prototype.addSkeleton = function (newSkeleton) {
  26436. this.skeletons.push(newSkeleton);
  26437. };
  26438. /**
  26439. * Adds the given particle system to this scene
  26440. * @param newParticleSystem The particle system to add
  26441. */
  26442. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26443. this.particleSystems.push(newParticleSystem);
  26444. };
  26445. /**
  26446. * Adds the given animation to this scene
  26447. * @param newAnimation The animation to add
  26448. */
  26449. Scene.prototype.addAnimation = function (newAnimation) {
  26450. this.animations.push(newAnimation);
  26451. };
  26452. /**
  26453. * Adds the given animation group to this scene.
  26454. * @param newAnimationGroup The animation group to add
  26455. */
  26456. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26457. this.animationGroups.push(newAnimationGroup);
  26458. };
  26459. /**
  26460. * Adds the given multi-material to this scene
  26461. * @param newMultiMaterial The multi-material to add
  26462. */
  26463. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26464. this.multiMaterials.push(newMultiMaterial);
  26465. };
  26466. /**
  26467. * Adds the given material to this scene
  26468. * @param newMaterial The material to add
  26469. */
  26470. Scene.prototype.addMaterial = function (newMaterial) {
  26471. this.materials.push(newMaterial);
  26472. };
  26473. /**
  26474. * Adds the given morph target to this scene
  26475. * @param newMorphTargetManager The morph target to add
  26476. */
  26477. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26478. this.morphTargetManagers.push(newMorphTargetManager);
  26479. };
  26480. /**
  26481. * Adds the given geometry to this scene
  26482. * @param newGeometry The geometry to add
  26483. */
  26484. Scene.prototype.addGeometry = function (newGeometry) {
  26485. this._geometries.push(newGeometry);
  26486. };
  26487. /**
  26488. * Adds the given lens flare system to this scene
  26489. * @param newLensFlareSystem The lens flare system to add
  26490. */
  26491. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26492. this.lensFlareSystems.push(newLensFlareSystem);
  26493. };
  26494. /**
  26495. * Adds the given effect layer to this scene
  26496. * @param newEffectLayer defines the effect layer to add
  26497. */
  26498. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26499. this.effectLayers.push(newEffectLayer);
  26500. };
  26501. /**
  26502. * Adds the given action manager to this scene
  26503. * @param newActionManager The action manager to add
  26504. */
  26505. Scene.prototype.addActionManager = function (newActionManager) {
  26506. this._actionManagers.push(newActionManager);
  26507. };
  26508. /**
  26509. * Adds the given texture to this scene.
  26510. * @param newTexture The texture to add
  26511. */
  26512. Scene.prototype.addTexture = function (newTexture) {
  26513. this.textures.push(newTexture);
  26514. };
  26515. /**
  26516. * Switch active camera
  26517. * @param newCamera defines the new active camera
  26518. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26519. */
  26520. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26521. if (attachControl === void 0) { attachControl = true; }
  26522. var canvas = this._engine.getRenderingCanvas();
  26523. if (!canvas) {
  26524. return;
  26525. }
  26526. if (this.activeCamera) {
  26527. this.activeCamera.detachControl(canvas);
  26528. }
  26529. this.activeCamera = newCamera;
  26530. if (attachControl) {
  26531. newCamera.attachControl(canvas);
  26532. }
  26533. };
  26534. /**
  26535. * sets the active camera of the scene using its ID
  26536. * @param id defines the camera's ID
  26537. * @return the new active camera or null if none found.
  26538. */
  26539. Scene.prototype.setActiveCameraByID = function (id) {
  26540. var camera = this.getCameraByID(id);
  26541. if (camera) {
  26542. this.activeCamera = camera;
  26543. return camera;
  26544. }
  26545. return null;
  26546. };
  26547. /**
  26548. * sets the active camera of the scene using its name
  26549. * @param name defines the camera's name
  26550. * @returns the new active camera or null if none found.
  26551. */
  26552. Scene.prototype.setActiveCameraByName = function (name) {
  26553. var camera = this.getCameraByName(name);
  26554. if (camera) {
  26555. this.activeCamera = camera;
  26556. return camera;
  26557. }
  26558. return null;
  26559. };
  26560. /**
  26561. * get an animation group using its name
  26562. * @param name defines the material's name
  26563. * @return the animation group or null if none found.
  26564. */
  26565. Scene.prototype.getAnimationGroupByName = function (name) {
  26566. for (var index = 0; index < this.animationGroups.length; index++) {
  26567. if (this.animationGroups[index].name === name) {
  26568. return this.animationGroups[index];
  26569. }
  26570. }
  26571. return null;
  26572. };
  26573. /**
  26574. * get a material using its id
  26575. * @param id defines the material's ID
  26576. * @return the material or null if none found.
  26577. */
  26578. Scene.prototype.getMaterialByID = function (id) {
  26579. for (var index = 0; index < this.materials.length; index++) {
  26580. if (this.materials[index].id === id) {
  26581. return this.materials[index];
  26582. }
  26583. }
  26584. return null;
  26585. };
  26586. /**
  26587. * Gets a material using its name
  26588. * @param name defines the material's name
  26589. * @return the material or null if none found.
  26590. */
  26591. Scene.prototype.getMaterialByName = function (name) {
  26592. for (var index = 0; index < this.materials.length; index++) {
  26593. if (this.materials[index].name === name) {
  26594. return this.materials[index];
  26595. }
  26596. }
  26597. return null;
  26598. };
  26599. /**
  26600. * Gets a lens flare system using its name
  26601. * @param name defines the name to look for
  26602. * @returns the lens flare system or null if not found
  26603. */
  26604. Scene.prototype.getLensFlareSystemByName = function (name) {
  26605. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26606. if (this.lensFlareSystems[index].name === name) {
  26607. return this.lensFlareSystems[index];
  26608. }
  26609. }
  26610. return null;
  26611. };
  26612. /**
  26613. * Gets a lens flare system using its id
  26614. * @param id defines the id to look for
  26615. * @returns the lens flare system or null if not found
  26616. */
  26617. Scene.prototype.getLensFlareSystemByID = function (id) {
  26618. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  26619. if (this.lensFlareSystems[index].id === id) {
  26620. return this.lensFlareSystems[index];
  26621. }
  26622. }
  26623. return null;
  26624. };
  26625. /**
  26626. * Gets a camera using its id
  26627. * @param id defines the id to look for
  26628. * @returns the camera or null if not found
  26629. */
  26630. Scene.prototype.getCameraByID = function (id) {
  26631. for (var index = 0; index < this.cameras.length; index++) {
  26632. if (this.cameras[index].id === id) {
  26633. return this.cameras[index];
  26634. }
  26635. }
  26636. return null;
  26637. };
  26638. /**
  26639. * Gets a camera using its unique id
  26640. * @param uniqueId defines the unique id to look for
  26641. * @returns the camera or null if not found
  26642. */
  26643. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  26644. for (var index = 0; index < this.cameras.length; index++) {
  26645. if (this.cameras[index].uniqueId === uniqueId) {
  26646. return this.cameras[index];
  26647. }
  26648. }
  26649. return null;
  26650. };
  26651. /**
  26652. * Gets a camera using its name
  26653. * @param name defines the camera's name
  26654. * @return the camera or null if none found.
  26655. */
  26656. Scene.prototype.getCameraByName = function (name) {
  26657. for (var index = 0; index < this.cameras.length; index++) {
  26658. if (this.cameras[index].name === name) {
  26659. return this.cameras[index];
  26660. }
  26661. }
  26662. return null;
  26663. };
  26664. /**
  26665. * Gets a bone using its id
  26666. * @param id defines the bone's id
  26667. * @return the bone or null if not found
  26668. */
  26669. Scene.prototype.getBoneByID = function (id) {
  26670. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26671. var skeleton = this.skeletons[skeletonIndex];
  26672. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26673. if (skeleton.bones[boneIndex].id === id) {
  26674. return skeleton.bones[boneIndex];
  26675. }
  26676. }
  26677. }
  26678. return null;
  26679. };
  26680. /**
  26681. * Gets a bone using its id
  26682. * @param name defines the bone's name
  26683. * @return the bone or null if not found
  26684. */
  26685. Scene.prototype.getBoneByName = function (name) {
  26686. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  26687. var skeleton = this.skeletons[skeletonIndex];
  26688. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  26689. if (skeleton.bones[boneIndex].name === name) {
  26690. return skeleton.bones[boneIndex];
  26691. }
  26692. }
  26693. }
  26694. return null;
  26695. };
  26696. /**
  26697. * Gets a light node using its name
  26698. * @param name defines the the light's name
  26699. * @return the light or null if none found.
  26700. */
  26701. Scene.prototype.getLightByName = function (name) {
  26702. for (var index = 0; index < this.lights.length; index++) {
  26703. if (this.lights[index].name === name) {
  26704. return this.lights[index];
  26705. }
  26706. }
  26707. return null;
  26708. };
  26709. /**
  26710. * Gets a light node using its id
  26711. * @param id defines the light's id
  26712. * @return the light or null if none found.
  26713. */
  26714. Scene.prototype.getLightByID = function (id) {
  26715. for (var index = 0; index < this.lights.length; index++) {
  26716. if (this.lights[index].id === id) {
  26717. return this.lights[index];
  26718. }
  26719. }
  26720. return null;
  26721. };
  26722. /**
  26723. * Gets a light node using its scene-generated unique ID
  26724. * @param uniqueId defines the light's unique id
  26725. * @return the light or null if none found.
  26726. */
  26727. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  26728. for (var index = 0; index < this.lights.length; index++) {
  26729. if (this.lights[index].uniqueId === uniqueId) {
  26730. return this.lights[index];
  26731. }
  26732. }
  26733. return null;
  26734. };
  26735. /**
  26736. * Gets a particle system by id
  26737. * @param id defines the particle system id
  26738. * @return the corresponding system or null if none found
  26739. */
  26740. Scene.prototype.getParticleSystemByID = function (id) {
  26741. for (var index = 0; index < this.particleSystems.length; index++) {
  26742. if (this.particleSystems[index].id === id) {
  26743. return this.particleSystems[index];
  26744. }
  26745. }
  26746. return null;
  26747. };
  26748. /**
  26749. * Gets a geometry using its ID
  26750. * @param id defines the geometry's id
  26751. * @return the geometry or null if none found.
  26752. */
  26753. Scene.prototype.getGeometryByID = function (id) {
  26754. for (var index = 0; index < this._geometries.length; index++) {
  26755. if (this._geometries[index].id === id) {
  26756. return this._geometries[index];
  26757. }
  26758. }
  26759. return null;
  26760. };
  26761. /**
  26762. * Add a new geometry to this scene
  26763. * @param geometry defines the geometry to be added to the scene.
  26764. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  26765. * @return a boolean defining if the geometry was added or not
  26766. */
  26767. Scene.prototype.pushGeometry = function (geometry, force) {
  26768. if (!force && this.getGeometryByID(geometry.id)) {
  26769. return false;
  26770. }
  26771. this._geometries.push(geometry);
  26772. //notify the collision coordinator
  26773. if (this.collisionCoordinator) {
  26774. this.collisionCoordinator.onGeometryAdded(geometry);
  26775. }
  26776. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  26777. return true;
  26778. };
  26779. /**
  26780. * Removes an existing geometry
  26781. * @param geometry defines the geometry to be removed from the scene
  26782. * @return a boolean defining if the geometry was removed or not
  26783. */
  26784. Scene.prototype.removeGeometry = function (geometry) {
  26785. var index = this._geometries.indexOf(geometry);
  26786. if (index > -1) {
  26787. this._geometries.splice(index, 1);
  26788. //notify the collision coordinator
  26789. if (this.collisionCoordinator) {
  26790. this.collisionCoordinator.onGeometryDeleted(geometry);
  26791. }
  26792. this.onGeometryRemovedObservable.notifyObservers(geometry);
  26793. return true;
  26794. }
  26795. return false;
  26796. };
  26797. /**
  26798. * Gets the list of geometries attached to the scene
  26799. * @returns an array of Geometry
  26800. */
  26801. Scene.prototype.getGeometries = function () {
  26802. return this._geometries;
  26803. };
  26804. /**
  26805. * Gets the first added mesh found of a given ID
  26806. * @param id defines the id to search for
  26807. * @return the mesh found or null if not found at all
  26808. */
  26809. Scene.prototype.getMeshByID = function (id) {
  26810. for (var index = 0; index < this.meshes.length; index++) {
  26811. if (this.meshes[index].id === id) {
  26812. return this.meshes[index];
  26813. }
  26814. }
  26815. return null;
  26816. };
  26817. /**
  26818. * Gets a list of meshes using their id
  26819. * @param id defines the id to search for
  26820. * @returns a list of meshes
  26821. */
  26822. Scene.prototype.getMeshesByID = function (id) {
  26823. return this.meshes.filter(function (m) {
  26824. return m.id === id;
  26825. });
  26826. };
  26827. /**
  26828. * Gets the first added transform node found of a given ID
  26829. * @param id defines the id to search for
  26830. * @return the found transform node or null if not found at all.
  26831. */
  26832. Scene.prototype.getTransformNodeByID = function (id) {
  26833. for (var index = 0; index < this.transformNodes.length; index++) {
  26834. if (this.transformNodes[index].id === id) {
  26835. return this.transformNodes[index];
  26836. }
  26837. }
  26838. return null;
  26839. };
  26840. /**
  26841. * Gets a list of transform nodes using their id
  26842. * @param id defines the id to search for
  26843. * @returns a list of transform nodes
  26844. */
  26845. Scene.prototype.getTransformNodesByID = function (id) {
  26846. return this.transformNodes.filter(function (m) {
  26847. return m.id === id;
  26848. });
  26849. };
  26850. /**
  26851. * Gets a mesh with its auto-generated unique id
  26852. * @param uniqueId defines the unique id to search for
  26853. * @return the found mesh or null if not found at all.
  26854. */
  26855. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  26856. for (var index = 0; index < this.meshes.length; index++) {
  26857. if (this.meshes[index].uniqueId === uniqueId) {
  26858. return this.meshes[index];
  26859. }
  26860. }
  26861. return null;
  26862. };
  26863. /**
  26864. * Gets a the last added mesh using a given id
  26865. * @param id defines the id to search for
  26866. * @return the found mesh or null if not found at all.
  26867. */
  26868. Scene.prototype.getLastMeshByID = function (id) {
  26869. for (var index = this.meshes.length - 1; index >= 0; index--) {
  26870. if (this.meshes[index].id === id) {
  26871. return this.meshes[index];
  26872. }
  26873. }
  26874. return null;
  26875. };
  26876. /**
  26877. * Gets a the last added node (Mesh, Camera, Light) using a given id
  26878. * @param id defines the id to search for
  26879. * @return the found node or null if not found at all
  26880. */
  26881. Scene.prototype.getLastEntryByID = function (id) {
  26882. var index;
  26883. for (index = this.meshes.length - 1; index >= 0; index--) {
  26884. if (this.meshes[index].id === id) {
  26885. return this.meshes[index];
  26886. }
  26887. }
  26888. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  26889. if (this.transformNodes[index].id === id) {
  26890. return this.transformNodes[index];
  26891. }
  26892. }
  26893. for (index = this.cameras.length - 1; index >= 0; index--) {
  26894. if (this.cameras[index].id === id) {
  26895. return this.cameras[index];
  26896. }
  26897. }
  26898. for (index = this.lights.length - 1; index >= 0; index--) {
  26899. if (this.lights[index].id === id) {
  26900. return this.lights[index];
  26901. }
  26902. }
  26903. return null;
  26904. };
  26905. /**
  26906. * Gets a node (Mesh, Camera, Light) using a given id
  26907. * @param id defines the id to search for
  26908. * @return the found node or null if not found at all
  26909. */
  26910. Scene.prototype.getNodeByID = function (id) {
  26911. var mesh = this.getMeshByID(id);
  26912. if (mesh) {
  26913. return mesh;
  26914. }
  26915. var light = this.getLightByID(id);
  26916. if (light) {
  26917. return light;
  26918. }
  26919. var camera = this.getCameraByID(id);
  26920. if (camera) {
  26921. return camera;
  26922. }
  26923. var bone = this.getBoneByID(id);
  26924. return bone;
  26925. };
  26926. /**
  26927. * Gets a node (Mesh, Camera, Light) using a given name
  26928. * @param name defines the name to search for
  26929. * @return the found node or null if not found at all.
  26930. */
  26931. Scene.prototype.getNodeByName = function (name) {
  26932. var mesh = this.getMeshByName(name);
  26933. if (mesh) {
  26934. return mesh;
  26935. }
  26936. var light = this.getLightByName(name);
  26937. if (light) {
  26938. return light;
  26939. }
  26940. var camera = this.getCameraByName(name);
  26941. if (camera) {
  26942. return camera;
  26943. }
  26944. var bone = this.getBoneByName(name);
  26945. return bone;
  26946. };
  26947. /**
  26948. * Gets a mesh using a given name
  26949. * @param name defines the name to search for
  26950. * @return the found mesh or null if not found at all.
  26951. */
  26952. Scene.prototype.getMeshByName = function (name) {
  26953. for (var index = 0; index < this.meshes.length; index++) {
  26954. if (this.meshes[index].name === name) {
  26955. return this.meshes[index];
  26956. }
  26957. }
  26958. return null;
  26959. };
  26960. /**
  26961. * Gets a transform node using a given name
  26962. * @param name defines the name to search for
  26963. * @return the found transform node or null if not found at all.
  26964. */
  26965. Scene.prototype.getTransformNodeByName = function (name) {
  26966. for (var index = 0; index < this.transformNodes.length; index++) {
  26967. if (this.transformNodes[index].name === name) {
  26968. return this.transformNodes[index];
  26969. }
  26970. }
  26971. return null;
  26972. };
  26973. /**
  26974. * Gets a sound using a given name
  26975. * @param name defines the name to search for
  26976. * @return the found sound or null if not found at all.
  26977. */
  26978. Scene.prototype.getSoundByName = function (name) {
  26979. var index;
  26980. if (BABYLON.AudioEngine) {
  26981. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  26982. if (this.mainSoundTrack.soundCollection[index].name === name) {
  26983. return this.mainSoundTrack.soundCollection[index];
  26984. }
  26985. }
  26986. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  26987. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  26988. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  26989. return this.soundTracks[sdIndex].soundCollection[index];
  26990. }
  26991. }
  26992. }
  26993. }
  26994. return null;
  26995. };
  26996. /**
  26997. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  26998. * @param id defines the id to search for
  26999. * @return the found skeleton or null if not found at all.
  27000. */
  27001. Scene.prototype.getLastSkeletonByID = function (id) {
  27002. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27003. if (this.skeletons[index].id === id) {
  27004. return this.skeletons[index];
  27005. }
  27006. }
  27007. return null;
  27008. };
  27009. /**
  27010. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27011. * @param id defines the id to search for
  27012. * @return the found skeleton or null if not found at all.
  27013. */
  27014. Scene.prototype.getSkeletonById = function (id) {
  27015. for (var index = 0; index < this.skeletons.length; index++) {
  27016. if (this.skeletons[index].id === id) {
  27017. return this.skeletons[index];
  27018. }
  27019. }
  27020. return null;
  27021. };
  27022. /**
  27023. * Gets a skeleton using a given name
  27024. * @param name defines the name to search for
  27025. * @return the found skeleton or null if not found at all.
  27026. */
  27027. Scene.prototype.getSkeletonByName = function (name) {
  27028. for (var index = 0; index < this.skeletons.length; index++) {
  27029. if (this.skeletons[index].name === name) {
  27030. return this.skeletons[index];
  27031. }
  27032. }
  27033. return null;
  27034. };
  27035. /**
  27036. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27037. * @param id defines the id to search for
  27038. * @return the found morph target manager or null if not found at all.
  27039. */
  27040. Scene.prototype.getMorphTargetManagerById = function (id) {
  27041. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27042. if (this.morphTargetManagers[index].uniqueId === id) {
  27043. return this.morphTargetManagers[index];
  27044. }
  27045. }
  27046. return null;
  27047. };
  27048. /**
  27049. * Gets a boolean indicating if the given mesh is active
  27050. * @param mesh defines the mesh to look for
  27051. * @returns true if the mesh is in the active list
  27052. */
  27053. Scene.prototype.isActiveMesh = function (mesh) {
  27054. return (this._activeMeshes.indexOf(mesh) !== -1);
  27055. };
  27056. /**
  27057. * Return a the first highlight layer of the scene with a given name.
  27058. * @param name The name of the highlight layer to look for.
  27059. * @return The highlight layer if found otherwise null.
  27060. */
  27061. Scene.prototype.getHighlightLayerByName = function (name) {
  27062. for (var index = 0; index < this.effectLayers.length; index++) {
  27063. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27064. return this.effectLayers[index];
  27065. }
  27066. }
  27067. return null;
  27068. };
  27069. /**
  27070. * Return a the first highlight layer of the scene with a given name.
  27071. * @param name The name of the highlight layer to look for.
  27072. * @return The highlight layer if found otherwise null.
  27073. */
  27074. Scene.prototype.getGlowLayerByName = function (name) {
  27075. for (var index = 0; index < this.effectLayers.length; index++) {
  27076. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27077. return this.effectLayers[index];
  27078. }
  27079. }
  27080. return null;
  27081. };
  27082. Object.defineProperty(Scene.prototype, "uid", {
  27083. /**
  27084. * Return a unique id as a string which can serve as an identifier for the scene
  27085. */
  27086. get: function () {
  27087. if (!this._uid) {
  27088. this._uid = BABYLON.Tools.RandomId();
  27089. }
  27090. return this._uid;
  27091. },
  27092. enumerable: true,
  27093. configurable: true
  27094. });
  27095. /**
  27096. * Add an externaly attached data from its key.
  27097. * This method call will fail and return false, if such key already exists.
  27098. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27099. * @param key the unique key that identifies the data
  27100. * @param data the data object to associate to the key for this Engine instance
  27101. * @return true if no such key were already present and the data was added successfully, false otherwise
  27102. */
  27103. Scene.prototype.addExternalData = function (key, data) {
  27104. if (!this._externalData) {
  27105. this._externalData = new BABYLON.StringDictionary();
  27106. }
  27107. return this._externalData.add(key, data);
  27108. };
  27109. /**
  27110. * Get an externaly attached data from its key
  27111. * @param key the unique key that identifies the data
  27112. * @return the associated data, if present (can be null), or undefined if not present
  27113. */
  27114. Scene.prototype.getExternalData = function (key) {
  27115. if (!this._externalData) {
  27116. return null;
  27117. }
  27118. return this._externalData.get(key);
  27119. };
  27120. /**
  27121. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27122. * @param key the unique key that identifies the data
  27123. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27124. * @return the associated data, can be null if the factory returned null.
  27125. */
  27126. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27127. if (!this._externalData) {
  27128. this._externalData = new BABYLON.StringDictionary();
  27129. }
  27130. return this._externalData.getOrAddWithFactory(key, factory);
  27131. };
  27132. /**
  27133. * Remove an externaly attached data from the Engine instance
  27134. * @param key the unique key that identifies the data
  27135. * @return true if the data was successfully removed, false if it doesn't exist
  27136. */
  27137. Scene.prototype.removeExternalData = function (key) {
  27138. return this._externalData.remove(key);
  27139. };
  27140. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27141. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27142. if (mesh.showSubMeshesBoundingBox) {
  27143. var boundingInfo = subMesh.getBoundingInfo();
  27144. if (boundingInfo !== null && boundingInfo !== undefined) {
  27145. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27146. }
  27147. }
  27148. var material = subMesh.getMaterial();
  27149. if (material !== null && material !== undefined) {
  27150. // Render targets
  27151. if (material.getRenderTargetTextures !== undefined) {
  27152. if (this._processedMaterials.indexOf(material) === -1) {
  27153. this._processedMaterials.push(material);
  27154. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27155. }
  27156. }
  27157. // Dispatch
  27158. this._activeIndices.addCount(subMesh.indexCount, false);
  27159. this._renderingManager.dispatch(subMesh, mesh, material);
  27160. }
  27161. }
  27162. };
  27163. /**
  27164. * Clear the processed materials smart array preventing retention point in material dispose.
  27165. */
  27166. Scene.prototype.freeProcessedMaterials = function () {
  27167. this._processedMaterials.dispose();
  27168. };
  27169. /**
  27170. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27171. */
  27172. Scene.prototype.freeActiveMeshes = function () {
  27173. this._activeMeshes.dispose();
  27174. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27175. this.activeCamera._activeMeshes.dispose();
  27176. }
  27177. if (this.activeCameras) {
  27178. for (var i = 0; i < this.activeCameras.length; i++) {
  27179. var activeCamera = this.activeCameras[i];
  27180. if (activeCamera && activeCamera._activeMeshes) {
  27181. activeCamera._activeMeshes.dispose();
  27182. }
  27183. }
  27184. }
  27185. };
  27186. /**
  27187. * Clear the info related to rendering groups preventing retention points during dispose.
  27188. */
  27189. Scene.prototype.freeRenderingGroups = function () {
  27190. if (this._renderingManager) {
  27191. this._renderingManager.freeRenderingGroups();
  27192. }
  27193. if (this.textures) {
  27194. for (var i = 0; i < this.textures.length; i++) {
  27195. var texture = this.textures[i];
  27196. if (texture && texture.renderList) {
  27197. texture.freeRenderingGroups();
  27198. }
  27199. }
  27200. }
  27201. };
  27202. /** @hidden */
  27203. Scene.prototype._isInIntermediateRendering = function () {
  27204. return this._intermediateRendering;
  27205. };
  27206. /**
  27207. * Defines the current active mesh candidate provider
  27208. * @param provider defines the provider to use
  27209. */
  27210. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27211. this._activeMeshCandidateProvider = provider;
  27212. };
  27213. /**
  27214. * Gets the current active mesh candidate provider
  27215. * @returns the current active mesh candidate provider
  27216. */
  27217. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27218. return this._activeMeshCandidateProvider;
  27219. };
  27220. /**
  27221. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27222. * @returns the current scene
  27223. */
  27224. Scene.prototype.freezeActiveMeshes = function () {
  27225. if (!this.activeCamera) {
  27226. return this;
  27227. }
  27228. if (!this._frustumPlanes) {
  27229. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27230. }
  27231. this._evaluateActiveMeshes();
  27232. this._activeMeshesFrozen = true;
  27233. return this;
  27234. };
  27235. /**
  27236. * Use this function to restart evaluating active meshes on every frame
  27237. * @returns the current scene
  27238. */
  27239. Scene.prototype.unfreezeActiveMeshes = function () {
  27240. this._activeMeshesFrozen = false;
  27241. return this;
  27242. };
  27243. Scene.prototype._evaluateActiveMeshes = function () {
  27244. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27245. return;
  27246. }
  27247. if (!this.activeCamera) {
  27248. return;
  27249. }
  27250. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27251. this.activeCamera._activeMeshes.reset();
  27252. this._activeMeshes.reset();
  27253. this._renderingManager.reset();
  27254. this._processedMaterials.reset();
  27255. this._activeParticleSystems.reset();
  27256. this._activeSkeletons.reset();
  27257. this._softwareSkinnedMeshes.reset();
  27258. if (this._boundingBoxRenderer) {
  27259. this._boundingBoxRenderer.reset();
  27260. }
  27261. // Meshes
  27262. var meshes;
  27263. var len;
  27264. var checkIsEnabled = true;
  27265. // Determine mesh candidates
  27266. if (this._activeMeshCandidateProvider !== undefined) {
  27267. // Use _activeMeshCandidateProvider
  27268. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27269. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27270. if (meshes !== undefined) {
  27271. len = meshes.length;
  27272. }
  27273. else {
  27274. len = 0;
  27275. }
  27276. }
  27277. else if (this._selectionOctree !== undefined) {
  27278. // Octree
  27279. var selection = this._selectionOctree.select(this._frustumPlanes);
  27280. meshes = selection.data;
  27281. len = selection.length;
  27282. }
  27283. else {
  27284. // Full scene traversal
  27285. len = this.meshes.length;
  27286. meshes = this.meshes;
  27287. }
  27288. // Check each mesh
  27289. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27290. mesh = meshes[meshIndex];
  27291. if (mesh.isBlocked) {
  27292. continue;
  27293. }
  27294. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27295. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27296. continue;
  27297. }
  27298. mesh.computeWorldMatrix();
  27299. // Intersections
  27300. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27301. this._meshesForIntersections.pushNoDuplicate(mesh);
  27302. }
  27303. // Switch to current LOD
  27304. meshLOD = mesh.getLOD(this.activeCamera);
  27305. if (meshLOD === undefined || meshLOD === null) {
  27306. continue;
  27307. }
  27308. mesh._preActivate();
  27309. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27310. this._activeMeshes.push(mesh);
  27311. this.activeCamera._activeMeshes.push(mesh);
  27312. mesh._activate(this._renderId);
  27313. if (meshLOD !== mesh) {
  27314. meshLOD._activate(this._renderId);
  27315. }
  27316. this._activeMesh(mesh, meshLOD);
  27317. }
  27318. }
  27319. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27320. // Particle systems
  27321. if (this.particlesEnabled) {
  27322. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27323. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27324. var particleSystem = this.particleSystems[particleIndex];
  27325. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27326. continue;
  27327. }
  27328. var emitter = particleSystem.emitter;
  27329. if (!emitter.position || emitter.isEnabled()) {
  27330. this._activeParticleSystems.push(particleSystem);
  27331. particleSystem.animate();
  27332. this._renderingManager.dispatchParticles(particleSystem);
  27333. }
  27334. }
  27335. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27336. }
  27337. };
  27338. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27339. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27340. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27341. mesh.skeleton.prepare();
  27342. }
  27343. if (!mesh.computeBonesUsingShaders) {
  27344. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27345. }
  27346. }
  27347. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27348. var boundingInfo = sourceMesh.getBoundingInfo();
  27349. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27350. }
  27351. if (mesh !== undefined && mesh !== null
  27352. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27353. // Submeshes Octrees
  27354. var len;
  27355. var subMeshes;
  27356. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27357. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27358. len = intersections.length;
  27359. subMeshes = intersections.data;
  27360. }
  27361. else {
  27362. subMeshes = mesh.subMeshes;
  27363. len = subMeshes.length;
  27364. }
  27365. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27366. subMesh = subMeshes[subIndex];
  27367. this._evaluateSubMesh(subMesh, mesh);
  27368. }
  27369. }
  27370. };
  27371. /**
  27372. * Update the transform matrix to update from the current active camera
  27373. * @param force defines a boolean used to force the update even if cache is up to date
  27374. */
  27375. Scene.prototype.updateTransformMatrix = function (force) {
  27376. if (!this.activeCamera) {
  27377. return;
  27378. }
  27379. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27380. };
  27381. /**
  27382. * 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)
  27383. * @param alternateCamera defines the camera to use
  27384. */
  27385. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27386. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27387. };
  27388. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27389. if (camera && camera._skipRendering) {
  27390. return;
  27391. }
  27392. var engine = this._engine;
  27393. this.activeCamera = camera;
  27394. if (!this.activeCamera)
  27395. throw new Error("Active camera not set");
  27396. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27397. // Viewport
  27398. engine.setViewport(this.activeCamera.viewport);
  27399. // Camera
  27400. this.resetCachedMaterial();
  27401. this._renderId++;
  27402. this.updateTransformMatrix();
  27403. if (camera._alternateCamera) {
  27404. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27405. this._alternateRendering = true;
  27406. }
  27407. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27408. // Meshes
  27409. this._evaluateActiveMeshes();
  27410. // Software skinning
  27411. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27412. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27413. mesh.applySkeleton(mesh.skeleton);
  27414. }
  27415. // Render targets
  27416. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27417. var needsRestoreFrameBuffer = false;
  27418. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27419. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27420. }
  27421. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27422. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27423. }
  27424. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27425. this._intermediateRendering = true;
  27426. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27427. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27428. var renderTarget = this._renderTargets.data[renderIndex];
  27429. if (renderTarget._shouldRender()) {
  27430. this._renderId++;
  27431. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27432. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27433. }
  27434. }
  27435. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27436. this._intermediateRendering = false;
  27437. this._renderId++;
  27438. needsRestoreFrameBuffer = true; // Restore back buffer
  27439. }
  27440. // Render EffecttLayer Texture
  27441. var stencilState = this._engine.getStencilBuffer();
  27442. var renderEffects = false;
  27443. var needStencil = false;
  27444. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27445. this._intermediateRendering = true;
  27446. for (var i = 0; i < this.effectLayers.length; i++) {
  27447. var effectLayer = this.effectLayers[i];
  27448. if (effectLayer.shouldRender() &&
  27449. (!effectLayer.camera ||
  27450. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27451. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27452. renderEffects = true;
  27453. needStencil = needStencil || effectLayer.needStencil();
  27454. var renderTarget = effectLayer._mainTexture;
  27455. if (renderTarget._shouldRender()) {
  27456. this._renderId++;
  27457. renderTarget.render(false, false);
  27458. needsRestoreFrameBuffer = true;
  27459. }
  27460. }
  27461. }
  27462. this._intermediateRendering = false;
  27463. this._renderId++;
  27464. }
  27465. if (needsRestoreFrameBuffer) {
  27466. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27467. }
  27468. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27469. // Prepare Frame
  27470. this.postProcessManager._prepareFrame();
  27471. // Backgrounds
  27472. var layerIndex;
  27473. var layer;
  27474. if (this.layers.length) {
  27475. engine.setDepthBuffer(false);
  27476. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27477. layer = this.layers[layerIndex];
  27478. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27479. layer.render();
  27480. }
  27481. }
  27482. engine.setDepthBuffer(true);
  27483. }
  27484. // Activate effect Layer stencil
  27485. if (needStencil) {
  27486. this._engine.setStencilBuffer(true);
  27487. }
  27488. // Render
  27489. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27490. this._renderingManager.render(null, null, true, true);
  27491. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27492. // Restore effect Layer stencil
  27493. if (needStencil) {
  27494. this._engine.setStencilBuffer(stencilState);
  27495. }
  27496. // Bounding boxes
  27497. if (this._boundingBoxRenderer) {
  27498. this._boundingBoxRenderer.render();
  27499. }
  27500. // Lens flares
  27501. if (this.lensFlaresEnabled) {
  27502. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27503. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27504. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27505. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27506. lensFlareSystem.render();
  27507. }
  27508. }
  27509. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27510. }
  27511. // Effect Layer
  27512. if (renderEffects) {
  27513. engine.setDepthBuffer(false);
  27514. for (var i = 0; i < this.effectLayers.length; i++) {
  27515. if (this.effectLayers[i].shouldRender()) {
  27516. this.effectLayers[i].render();
  27517. }
  27518. }
  27519. engine.setDepthBuffer(true);
  27520. }
  27521. // Foregrounds
  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. // Finalize frame
  27533. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27534. // Reset some special arrays
  27535. this._renderTargets.reset();
  27536. this._alternateRendering = false;
  27537. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27538. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + this.activeCamera.name);
  27539. };
  27540. Scene.prototype._processSubCameras = function (camera) {
  27541. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27542. this._renderForCamera(camera);
  27543. return;
  27544. }
  27545. // rig cameras
  27546. for (var index = 0; index < camera._rigCameras.length; index++) {
  27547. this._renderForCamera(camera._rigCameras[index], camera);
  27548. }
  27549. this.activeCamera = camera;
  27550. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27551. };
  27552. Scene.prototype._checkIntersections = function () {
  27553. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27554. var sourceMesh = this._meshesForIntersections.data[index];
  27555. if (!sourceMesh.actionManager) {
  27556. continue;
  27557. }
  27558. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27559. var action = sourceMesh.actionManager.actions[actionIndex];
  27560. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27561. var parameters = action.getTriggerParameter();
  27562. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27563. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27564. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27565. if (areIntersecting && currentIntersectionInProgress === -1) {
  27566. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27567. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27568. sourceMesh._intersectionsInProgress.push(otherMesh);
  27569. }
  27570. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27571. sourceMesh._intersectionsInProgress.push(otherMesh);
  27572. }
  27573. }
  27574. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  27575. //They intersected, and now they don't.
  27576. //is this trigger an exit trigger? execute an event.
  27577. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27578. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27579. }
  27580. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  27581. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  27582. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  27583. return otherMesh === parameterMesh;
  27584. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27585. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  27586. }
  27587. }
  27588. }
  27589. }
  27590. }
  27591. };
  27592. /**
  27593. * Render the scene
  27594. */
  27595. Scene.prototype.render = function () {
  27596. if (this.isDisposed) {
  27597. return;
  27598. }
  27599. this._activeParticles.fetchNewFrame();
  27600. this._totalVertices.fetchNewFrame();
  27601. this._activeIndices.fetchNewFrame();
  27602. this._activeBones.fetchNewFrame();
  27603. this._meshesForIntersections.reset();
  27604. this.resetCachedMaterial();
  27605. this.onBeforeAnimationsObservable.notifyObservers(this);
  27606. // Actions
  27607. if (this.actionManager) {
  27608. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  27609. }
  27610. //Simplification Queue
  27611. if (this.simplificationQueue && !this.simplificationQueue.running) {
  27612. this.simplificationQueue.executeNext();
  27613. }
  27614. if (this._engine.isDeterministicLockStep()) {
  27615. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  27616. var defaultFPS = (60.0 / 1000.0);
  27617. var defaultFrameTime = 1000 / 60; // frame time in MS
  27618. if (this._physicsEngine) {
  27619. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  27620. }
  27621. var stepsTaken = 0;
  27622. var maxSubSteps = this._engine.getLockstepMaxSteps();
  27623. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  27624. internalSteps = Math.min(internalSteps, maxSubSteps);
  27625. do {
  27626. this.onBeforeStepObservable.notifyObservers(this);
  27627. // Animations
  27628. this._animationRatio = defaultFrameTime * defaultFPS;
  27629. this._animate();
  27630. this.onAfterAnimationsObservable.notifyObservers(this);
  27631. // Physics
  27632. if (this._physicsEngine) {
  27633. this.onBeforePhysicsObservable.notifyObservers(this);
  27634. this._physicsEngine._step(defaultFrameTime / 1000);
  27635. this.onAfterPhysicsObservable.notifyObservers(this);
  27636. }
  27637. this.onAfterStepObservable.notifyObservers(this);
  27638. this._currentStepId++;
  27639. stepsTaken++;
  27640. deltaTime -= defaultFrameTime;
  27641. } while (deltaTime > 0 && stepsTaken < internalSteps);
  27642. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  27643. }
  27644. else {
  27645. // Animations
  27646. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  27647. this._animationRatio = deltaTime * (60.0 / 1000.0);
  27648. this._animate();
  27649. this.onAfterAnimationsObservable.notifyObservers(this);
  27650. // Physics
  27651. if (this._physicsEngine) {
  27652. this.onBeforePhysicsObservable.notifyObservers(this);
  27653. this._physicsEngine._step(deltaTime / 1000.0);
  27654. this.onAfterPhysicsObservable.notifyObservers(this);
  27655. }
  27656. }
  27657. // update gamepad manager
  27658. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  27659. this._gamepadManager._checkGamepadsStatus();
  27660. }
  27661. // Update Cameras
  27662. if (this.activeCameras.length > 0) {
  27663. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27664. var camera = this.activeCameras[cameraIndex];
  27665. camera.update();
  27666. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27667. // rig cameras
  27668. for (var index = 0; index < camera._rigCameras.length; index++) {
  27669. camera._rigCameras[index].update();
  27670. }
  27671. }
  27672. }
  27673. }
  27674. else if (this.activeCamera) {
  27675. this.activeCamera.update();
  27676. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  27677. // rig cameras
  27678. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  27679. this.activeCamera._rigCameras[index].update();
  27680. }
  27681. }
  27682. }
  27683. // Before render
  27684. this.onBeforeRenderObservable.notifyObservers(this);
  27685. // Customs render targets
  27686. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27687. var engine = this.getEngine();
  27688. var currentActiveCamera = this.activeCamera;
  27689. if (this.renderTargetsEnabled) {
  27690. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27691. this._intermediateRendering = true;
  27692. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  27693. var renderTarget = this.customRenderTargets[customIndex];
  27694. if (renderTarget._shouldRender()) {
  27695. this._renderId++;
  27696. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  27697. if (!this.activeCamera)
  27698. throw new Error("Active camera not set");
  27699. // Viewport
  27700. engine.setViewport(this.activeCamera.viewport);
  27701. // Camera
  27702. this.updateTransformMatrix();
  27703. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  27704. }
  27705. }
  27706. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  27707. this._intermediateRendering = false;
  27708. this._renderId++;
  27709. }
  27710. // Restore back buffer
  27711. if (this.customRenderTargets.length > 0) {
  27712. engine.restoreDefaultFramebuffer();
  27713. }
  27714. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27715. this.activeCamera = currentActiveCamera;
  27716. // Procedural textures
  27717. if (this.proceduralTexturesEnabled) {
  27718. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27719. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  27720. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  27721. if (proceduralTexture._shouldRender()) {
  27722. proceduralTexture.render();
  27723. }
  27724. }
  27725. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  27726. }
  27727. // Clear
  27728. if (this.autoClearDepthAndStencil || this.autoClear) {
  27729. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  27730. }
  27731. // Shadows
  27732. if (this.shadowsEnabled) {
  27733. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  27734. var light = this.lights[lightIndex];
  27735. var shadowGenerator = light.getShadowGenerator();
  27736. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  27737. var shadowMap = (shadowGenerator.getShadowMap());
  27738. if (this.textures.indexOf(shadowMap) !== -1) {
  27739. this._renderTargets.push(shadowMap);
  27740. }
  27741. }
  27742. }
  27743. }
  27744. // Depth renderer
  27745. for (var key in this._depthRenderer) {
  27746. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  27747. }
  27748. // Geometry renderer
  27749. if (this._geometryBufferRenderer) {
  27750. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  27751. }
  27752. // RenderPipeline
  27753. if (this._postProcessRenderPipelineManager) {
  27754. this._postProcessRenderPipelineManager.update();
  27755. }
  27756. // Multi-cameras?
  27757. if (this.activeCameras.length > 0) {
  27758. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  27759. if (cameraIndex > 0) {
  27760. this._engine.clear(null, false, true, true);
  27761. }
  27762. this._processSubCameras(this.activeCameras[cameraIndex]);
  27763. }
  27764. }
  27765. else {
  27766. if (!this.activeCamera) {
  27767. throw new Error("No camera defined");
  27768. }
  27769. this._processSubCameras(this.activeCamera);
  27770. }
  27771. // Intersection checks
  27772. this._checkIntersections();
  27773. // Update the audio listener attached to the camera
  27774. if (BABYLON.AudioEngine) {
  27775. this._updateAudioParameters();
  27776. }
  27777. // After render
  27778. if (this.afterRender) {
  27779. this.afterRender();
  27780. }
  27781. this.onAfterRenderObservable.notifyObservers(this);
  27782. // Cleaning
  27783. for (var index = 0; index < this._toBeDisposed.length; index++) {
  27784. var data = this._toBeDisposed.data[index];
  27785. if (data) {
  27786. data.dispose();
  27787. }
  27788. this._toBeDisposed[index] = null;
  27789. }
  27790. this._toBeDisposed.reset();
  27791. if (this.dumpNextRenderTargets) {
  27792. this.dumpNextRenderTargets = false;
  27793. }
  27794. this._activeBones.addCount(0, true);
  27795. this._activeIndices.addCount(0, true);
  27796. this._activeParticles.addCount(0, true);
  27797. };
  27798. Scene.prototype._updateAudioParameters = function () {
  27799. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  27800. return;
  27801. }
  27802. var listeningCamera;
  27803. var audioEngine = BABYLON.Engine.audioEngine;
  27804. if (this.activeCameras.length > 0) {
  27805. listeningCamera = this.activeCameras[0];
  27806. }
  27807. else {
  27808. listeningCamera = this.activeCamera;
  27809. }
  27810. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  27811. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  27812. // for VR cameras
  27813. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  27814. listeningCamera = listeningCamera.rigCameras[0];
  27815. }
  27816. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  27817. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  27818. cameraDirection.normalize();
  27819. // To avoid some errors on GearVR
  27820. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  27821. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  27822. }
  27823. var i;
  27824. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27825. var sound = this.mainSoundTrack.soundCollection[i];
  27826. if (sound.useCustomAttenuation) {
  27827. sound.updateDistanceFromListener();
  27828. }
  27829. }
  27830. for (i = 0; i < this.soundTracks.length; i++) {
  27831. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27832. sound = this.soundTracks[i].soundCollection[j];
  27833. if (sound.useCustomAttenuation) {
  27834. sound.updateDistanceFromListener();
  27835. }
  27836. }
  27837. }
  27838. }
  27839. };
  27840. Object.defineProperty(Scene.prototype, "audioEnabled", {
  27841. // Audio
  27842. /**
  27843. * Gets or sets if audio support is enabled
  27844. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27845. */
  27846. get: function () {
  27847. return this._audioEnabled;
  27848. },
  27849. set: function (value) {
  27850. this._audioEnabled = value;
  27851. if (BABYLON.AudioEngine) {
  27852. if (this._audioEnabled) {
  27853. this._enableAudio();
  27854. }
  27855. else {
  27856. this._disableAudio();
  27857. }
  27858. }
  27859. },
  27860. enumerable: true,
  27861. configurable: true
  27862. });
  27863. Scene.prototype._disableAudio = function () {
  27864. var i;
  27865. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27866. this.mainSoundTrack.soundCollection[i].pause();
  27867. }
  27868. for (i = 0; i < this.soundTracks.length; i++) {
  27869. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27870. this.soundTracks[i].soundCollection[j].pause();
  27871. }
  27872. }
  27873. };
  27874. Scene.prototype._enableAudio = function () {
  27875. var i;
  27876. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  27877. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  27878. this.mainSoundTrack.soundCollection[i].play();
  27879. }
  27880. }
  27881. for (i = 0; i < this.soundTracks.length; i++) {
  27882. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  27883. if (this.soundTracks[i].soundCollection[j].isPaused) {
  27884. this.soundTracks[i].soundCollection[j].play();
  27885. }
  27886. }
  27887. }
  27888. };
  27889. Object.defineProperty(Scene.prototype, "headphone", {
  27890. /**
  27891. * Gets or sets if audio will be output to headphones
  27892. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  27893. */
  27894. get: function () {
  27895. return this._headphone;
  27896. },
  27897. set: function (value) {
  27898. this._headphone = value;
  27899. if (BABYLON.AudioEngine) {
  27900. if (this._headphone) {
  27901. this._switchAudioModeForHeadphones();
  27902. }
  27903. else {
  27904. this._switchAudioModeForNormalSpeakers();
  27905. }
  27906. }
  27907. },
  27908. enumerable: true,
  27909. configurable: true
  27910. });
  27911. Scene.prototype._switchAudioModeForHeadphones = function () {
  27912. this.mainSoundTrack.switchPanningModelToHRTF();
  27913. for (var i = 0; i < this.soundTracks.length; i++) {
  27914. this.soundTracks[i].switchPanningModelToHRTF();
  27915. }
  27916. };
  27917. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  27918. this.mainSoundTrack.switchPanningModelToEqualPower();
  27919. for (var i = 0; i < this.soundTracks.length; i++) {
  27920. this.soundTracks[i].switchPanningModelToEqualPower();
  27921. }
  27922. };
  27923. /**
  27924. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  27925. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  27926. * @returns the created depth renderer
  27927. */
  27928. Scene.prototype.enableDepthRenderer = function (camera) {
  27929. camera = camera || this.activeCamera;
  27930. if (!camera) {
  27931. throw "No camera available to enable depth renderer";
  27932. }
  27933. if (!this._depthRenderer[camera.id]) {
  27934. var textureType = 0;
  27935. if (this._engine.getCaps().textureHalfFloatRender) {
  27936. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  27937. }
  27938. else if (this._engine.getCaps().textureFloatRender) {
  27939. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  27940. }
  27941. else {
  27942. throw "Depth renderer does not support int texture type";
  27943. }
  27944. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  27945. }
  27946. return this._depthRenderer[camera.id];
  27947. };
  27948. /**
  27949. * Disables a depth renderer for a given camera
  27950. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  27951. */
  27952. Scene.prototype.disableDepthRenderer = function (camera) {
  27953. camera = camera || this.activeCamera;
  27954. if (!camera || !this._depthRenderer[camera.id]) {
  27955. return;
  27956. }
  27957. this._depthRenderer[camera.id].dispose();
  27958. delete this._depthRenderer[camera.id];
  27959. };
  27960. /**
  27961. * Enables a GeometryBufferRender and associates it with the scene
  27962. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  27963. * @returns the GeometryBufferRenderer
  27964. */
  27965. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  27966. if (ratio === void 0) { ratio = 1; }
  27967. if (this._geometryBufferRenderer) {
  27968. return this._geometryBufferRenderer;
  27969. }
  27970. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  27971. if (!this._geometryBufferRenderer.isSupported) {
  27972. this._geometryBufferRenderer = null;
  27973. }
  27974. return this._geometryBufferRenderer;
  27975. };
  27976. /**
  27977. * Disables the GeometryBufferRender associated with the scene
  27978. */
  27979. Scene.prototype.disableGeometryBufferRenderer = function () {
  27980. if (!this._geometryBufferRenderer) {
  27981. return;
  27982. }
  27983. this._geometryBufferRenderer.dispose();
  27984. this._geometryBufferRenderer = null;
  27985. };
  27986. /**
  27987. * Freeze all materials
  27988. * A frozen material will not be updatable but should be faster to render
  27989. */
  27990. Scene.prototype.freezeMaterials = function () {
  27991. for (var i = 0; i < this.materials.length; i++) {
  27992. this.materials[i].freeze();
  27993. }
  27994. };
  27995. /**
  27996. * Unfreeze all materials
  27997. * A frozen material will not be updatable but should be faster to render
  27998. */
  27999. Scene.prototype.unfreezeMaterials = function () {
  28000. for (var i = 0; i < this.materials.length; i++) {
  28001. this.materials[i].unfreeze();
  28002. }
  28003. };
  28004. /**
  28005. * Releases all held ressources
  28006. */
  28007. Scene.prototype.dispose = function () {
  28008. this.beforeRender = null;
  28009. this.afterRender = null;
  28010. this.skeletons = [];
  28011. this.morphTargetManagers = [];
  28012. this.importedMeshesFiles = new Array();
  28013. this.stopAllAnimations();
  28014. this.resetCachedMaterial();
  28015. for (var key in this._depthRenderer) {
  28016. this._depthRenderer[key].dispose();
  28017. }
  28018. if (this._gamepadManager) {
  28019. this._gamepadManager.dispose();
  28020. this._gamepadManager = null;
  28021. }
  28022. // Smart arrays
  28023. if (this.activeCamera) {
  28024. this.activeCamera._activeMeshes.dispose();
  28025. this.activeCamera = null;
  28026. }
  28027. this._activeMeshes.dispose();
  28028. this._renderingManager.dispose();
  28029. this._processedMaterials.dispose();
  28030. this._activeParticleSystems.dispose();
  28031. this._activeSkeletons.dispose();
  28032. this._softwareSkinnedMeshes.dispose();
  28033. this._renderTargets.dispose();
  28034. this._registeredForLateAnimationBindings.dispose();
  28035. if (this._boundingBoxRenderer) {
  28036. this._boundingBoxRenderer.dispose();
  28037. }
  28038. this._meshesForIntersections.dispose();
  28039. this._toBeDisposed.dispose();
  28040. // Abort active requests
  28041. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28042. var request = _a[_i];
  28043. request.abort();
  28044. }
  28045. // Debug layer
  28046. if (this._debugLayer) {
  28047. this._debugLayer.hide();
  28048. }
  28049. // Events
  28050. this.onDisposeObservable.notifyObservers(this);
  28051. this.onDisposeObservable.clear();
  28052. this.onBeforeRenderObservable.clear();
  28053. this.onAfterRenderObservable.clear();
  28054. this.onBeforeRenderTargetsRenderObservable.clear();
  28055. this.onAfterRenderTargetsRenderObservable.clear();
  28056. this.onAfterStepObservable.clear();
  28057. this.onBeforeStepObservable.clear();
  28058. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28059. this.onAfterActiveMeshesEvaluationObservable.clear();
  28060. this.onBeforeParticlesRenderingObservable.clear();
  28061. this.onAfterParticlesRenderingObservable.clear();
  28062. this.onBeforeSpritesRenderingObservable.clear();
  28063. this.onAfterSpritesRenderingObservable.clear();
  28064. this.onBeforeDrawPhaseObservable.clear();
  28065. this.onAfterDrawPhaseObservable.clear();
  28066. this.onBeforePhysicsObservable.clear();
  28067. this.onAfterPhysicsObservable.clear();
  28068. this.onBeforeAnimationsObservable.clear();
  28069. this.onAfterAnimationsObservable.clear();
  28070. this.onDataLoadedObservable.clear();
  28071. this.detachControl();
  28072. // Release sounds & sounds tracks
  28073. if (BABYLON.AudioEngine) {
  28074. this.disposeSounds();
  28075. }
  28076. // VR Helper
  28077. if (this.VRHelper) {
  28078. this.VRHelper.dispose();
  28079. }
  28080. // Detach cameras
  28081. var canvas = this._engine.getRenderingCanvas();
  28082. if (canvas) {
  28083. var index;
  28084. for (index = 0; index < this.cameras.length; index++) {
  28085. this.cameras[index].detachControl(canvas);
  28086. }
  28087. }
  28088. // Release animation groups
  28089. while (this.animationGroups.length) {
  28090. this.animationGroups[0].dispose();
  28091. }
  28092. // Release lights
  28093. while (this.lights.length) {
  28094. this.lights[0].dispose();
  28095. }
  28096. // Release meshes
  28097. while (this.meshes.length) {
  28098. this.meshes[0].dispose(true);
  28099. }
  28100. while (this.transformNodes.length) {
  28101. this.removeTransformNode(this.transformNodes[0]);
  28102. }
  28103. // Release cameras
  28104. while (this.cameras.length) {
  28105. this.cameras[0].dispose();
  28106. }
  28107. // Release materials
  28108. if (this.defaultMaterial) {
  28109. this.defaultMaterial.dispose();
  28110. }
  28111. while (this.multiMaterials.length) {
  28112. this.multiMaterials[0].dispose();
  28113. }
  28114. while (this.materials.length) {
  28115. this.materials[0].dispose();
  28116. }
  28117. // Release particles
  28118. while (this.particleSystems.length) {
  28119. this.particleSystems[0].dispose();
  28120. }
  28121. // Release sprites
  28122. while (this.spriteManagers.length) {
  28123. this.spriteManagers[0].dispose();
  28124. }
  28125. // Release postProcesses
  28126. while (this.postProcesses.length) {
  28127. this.postProcesses[0].dispose();
  28128. }
  28129. // Release layers
  28130. while (this.layers.length) {
  28131. this.layers[0].dispose();
  28132. }
  28133. while (this.effectLayers.length) {
  28134. this.effectLayers[0].dispose();
  28135. }
  28136. // Release textures
  28137. while (this.textures.length) {
  28138. this.textures[0].dispose();
  28139. }
  28140. // Release UBO
  28141. this._sceneUbo.dispose();
  28142. if (this._alternateSceneUbo) {
  28143. this._alternateSceneUbo.dispose();
  28144. }
  28145. // Post-processes
  28146. this.postProcessManager.dispose();
  28147. if (this._postProcessRenderPipelineManager) {
  28148. this._postProcessRenderPipelineManager.dispose();
  28149. }
  28150. // Physics
  28151. if (this._physicsEngine) {
  28152. this.disablePhysicsEngine();
  28153. }
  28154. // Remove from engine
  28155. index = this._engine.scenes.indexOf(this);
  28156. if (index > -1) {
  28157. this._engine.scenes.splice(index, 1);
  28158. }
  28159. this._engine.wipeCaches(true);
  28160. this._isDisposed = true;
  28161. };
  28162. Object.defineProperty(Scene.prototype, "isDisposed", {
  28163. /**
  28164. * Gets if the scene is already disposed
  28165. */
  28166. get: function () {
  28167. return this._isDisposed;
  28168. },
  28169. enumerable: true,
  28170. configurable: true
  28171. });
  28172. /**
  28173. * Releases sounds & soundtracks
  28174. */
  28175. Scene.prototype.disposeSounds = function () {
  28176. if (!this._mainSoundTrack) {
  28177. return;
  28178. }
  28179. this.mainSoundTrack.dispose();
  28180. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28181. this.soundTracks[scIndex].dispose();
  28182. }
  28183. };
  28184. // Octrees
  28185. /**
  28186. * Get the world extend vectors with an optional filter
  28187. *
  28188. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28189. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28190. */
  28191. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28192. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28193. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28194. filterPredicate = filterPredicate || (function () { return true; });
  28195. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28196. mesh.computeWorldMatrix(true);
  28197. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28198. return;
  28199. }
  28200. var boundingInfo = mesh.getBoundingInfo();
  28201. var minBox = boundingInfo.boundingBox.minimumWorld;
  28202. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28203. BABYLON.Tools.CheckExtends(minBox, min, max);
  28204. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28205. });
  28206. return {
  28207. min: min,
  28208. max: max
  28209. };
  28210. };
  28211. /**
  28212. * Creates or updates the octree used to boost selection (picking)
  28213. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28214. * @param maxCapacity defines the maximum capacity per leaf
  28215. * @param maxDepth defines the maximum depth of the octree
  28216. * @returns an octree of AbstractMesh
  28217. */
  28218. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28219. if (maxCapacity === void 0) { maxCapacity = 64; }
  28220. if (maxDepth === void 0) { maxDepth = 2; }
  28221. if (!this._selectionOctree) {
  28222. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28223. }
  28224. var worldExtends = this.getWorldExtends();
  28225. // Update octree
  28226. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28227. return this._selectionOctree;
  28228. };
  28229. // Picking
  28230. /**
  28231. * Creates a ray that can be used to pick in the scene
  28232. * @param x defines the x coordinate of the origin (on-screen)
  28233. * @param y defines the y coordinate of the origin (on-screen)
  28234. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28235. * @param camera defines the camera to use for the picking
  28236. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28237. * @returns a Ray
  28238. */
  28239. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28240. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28241. var result = BABYLON.Ray.Zero();
  28242. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28243. return result;
  28244. };
  28245. /**
  28246. * Creates a ray that can be used to pick in the scene
  28247. * @param x defines the x coordinate of the origin (on-screen)
  28248. * @param y defines the y coordinate of the origin (on-screen)
  28249. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28250. * @param result defines the ray where to store the picking ray
  28251. * @param camera defines the camera to use for the picking
  28252. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28253. * @returns the current scene
  28254. */
  28255. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28256. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28257. var engine = this._engine;
  28258. if (!camera) {
  28259. if (!this.activeCamera)
  28260. throw new Error("Active camera not set");
  28261. camera = this.activeCamera;
  28262. }
  28263. var cameraViewport = camera.viewport;
  28264. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28265. // Moving coordinates to local viewport world
  28266. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28267. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28268. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28269. return this;
  28270. };
  28271. /**
  28272. * Creates a ray that can be used to pick in the scene
  28273. * @param x defines the x coordinate of the origin (on-screen)
  28274. * @param y defines the y coordinate of the origin (on-screen)
  28275. * @param camera defines the camera to use for the picking
  28276. * @returns a Ray
  28277. */
  28278. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28279. var result = BABYLON.Ray.Zero();
  28280. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28281. return result;
  28282. };
  28283. /**
  28284. * Creates a ray that can be used to pick in the scene
  28285. * @param x defines the x coordinate of the origin (on-screen)
  28286. * @param y defines the y coordinate of the origin (on-screen)
  28287. * @param result defines the ray where to store the picking ray
  28288. * @param camera defines the camera to use for the picking
  28289. * @returns the current scene
  28290. */
  28291. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28292. if (!BABYLON.PickingInfo) {
  28293. return this;
  28294. }
  28295. var engine = this._engine;
  28296. if (!camera) {
  28297. if (!this.activeCamera)
  28298. throw new Error("Active camera not set");
  28299. camera = this.activeCamera;
  28300. }
  28301. var cameraViewport = camera.viewport;
  28302. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28303. var identity = BABYLON.Matrix.Identity();
  28304. // Moving coordinates to local viewport world
  28305. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28306. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28307. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28308. return this;
  28309. };
  28310. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28311. if (!BABYLON.PickingInfo) {
  28312. return null;
  28313. }
  28314. var pickingInfo = null;
  28315. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28316. var mesh = this.meshes[meshIndex];
  28317. if (predicate) {
  28318. if (!predicate(mesh)) {
  28319. continue;
  28320. }
  28321. }
  28322. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28323. continue;
  28324. }
  28325. var world = mesh.getWorldMatrix();
  28326. var ray = rayFunction(world);
  28327. var result = mesh.intersects(ray, fastCheck);
  28328. if (!result || !result.hit)
  28329. continue;
  28330. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28331. continue;
  28332. pickingInfo = result;
  28333. if (fastCheck) {
  28334. break;
  28335. }
  28336. }
  28337. return pickingInfo || new BABYLON.PickingInfo();
  28338. };
  28339. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28340. if (!BABYLON.PickingInfo) {
  28341. return null;
  28342. }
  28343. var pickingInfos = new Array();
  28344. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28345. var mesh = this.meshes[meshIndex];
  28346. if (predicate) {
  28347. if (!predicate(mesh)) {
  28348. continue;
  28349. }
  28350. }
  28351. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28352. continue;
  28353. }
  28354. var world = mesh.getWorldMatrix();
  28355. var ray = rayFunction(world);
  28356. var result = mesh.intersects(ray, false);
  28357. if (!result || !result.hit)
  28358. continue;
  28359. pickingInfos.push(result);
  28360. }
  28361. return pickingInfos;
  28362. };
  28363. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28364. if (!BABYLON.PickingInfo) {
  28365. return null;
  28366. }
  28367. var pickingInfo = null;
  28368. if (!camera) {
  28369. if (!this.activeCamera) {
  28370. return null;
  28371. }
  28372. camera = this.activeCamera;
  28373. }
  28374. if (this.spriteManagers.length > 0) {
  28375. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28376. var spriteManager = this.spriteManagers[spriteIndex];
  28377. if (!spriteManager.isPickable) {
  28378. continue;
  28379. }
  28380. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28381. if (!result || !result.hit)
  28382. continue;
  28383. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28384. continue;
  28385. pickingInfo = result;
  28386. if (fastCheck) {
  28387. break;
  28388. }
  28389. }
  28390. }
  28391. return pickingInfo || new BABYLON.PickingInfo();
  28392. };
  28393. /** Launch a ray to try to pick a mesh in the scene
  28394. * @param x position on screen
  28395. * @param y position on screen
  28396. * @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
  28397. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28398. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28399. * @returns a PickingInfo
  28400. */
  28401. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28402. var _this = this;
  28403. if (!BABYLON.PickingInfo) {
  28404. return null;
  28405. }
  28406. return this._internalPick(function (world) {
  28407. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28408. return _this._tempPickingRay;
  28409. }, predicate, fastCheck);
  28410. };
  28411. /** Launch a ray to try to pick a sprite in the scene
  28412. * @param x position on screen
  28413. * @param y position on screen
  28414. * @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
  28415. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28416. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28417. * @returns a PickingInfo
  28418. */
  28419. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28420. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28421. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28422. };
  28423. /** Use the given ray to pick a mesh in the scene
  28424. * @param ray The ray to use to pick meshes
  28425. * @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
  28426. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28427. * @returns a PickingInfo
  28428. */
  28429. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28430. var _this = this;
  28431. return this._internalPick(function (world) {
  28432. if (!_this._pickWithRayInverseMatrix) {
  28433. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28434. }
  28435. world.invertToRef(_this._pickWithRayInverseMatrix);
  28436. if (!_this._cachedRayForTransform) {
  28437. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28438. }
  28439. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28440. return _this._cachedRayForTransform;
  28441. }, predicate, fastCheck);
  28442. };
  28443. /**
  28444. * Launch a ray to try to pick a mesh in the scene
  28445. * @param x X position on screen
  28446. * @param y Y position on screen
  28447. * @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
  28448. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28449. * @returns an array of PickingInfo
  28450. */
  28451. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28452. var _this = this;
  28453. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28454. };
  28455. /**
  28456. * Launch a ray to try to pick a mesh in the scene
  28457. * @param ray Ray to use
  28458. * @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
  28459. * @returns an array of PickingInfo
  28460. */
  28461. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28462. var _this = this;
  28463. return this._internalMultiPick(function (world) {
  28464. if (!_this._pickWithRayInverseMatrix) {
  28465. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28466. }
  28467. world.invertToRef(_this._pickWithRayInverseMatrix);
  28468. if (!_this._cachedRayForTransform) {
  28469. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28470. }
  28471. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28472. return _this._cachedRayForTransform;
  28473. }, predicate);
  28474. };
  28475. /**
  28476. * Force the value of meshUnderPointer
  28477. * @param mesh defines the mesh to use
  28478. */
  28479. Scene.prototype.setPointerOverMesh = function (mesh) {
  28480. if (this._pointerOverMesh === mesh) {
  28481. return;
  28482. }
  28483. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28484. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28485. }
  28486. this._pointerOverMesh = mesh;
  28487. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28488. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28489. }
  28490. };
  28491. /**
  28492. * Gets the mesh under the pointer
  28493. * @returns a Mesh or null if no mesh is under the pointer
  28494. */
  28495. Scene.prototype.getPointerOverMesh = function () {
  28496. return this._pointerOverMesh;
  28497. };
  28498. /**
  28499. * Force the sprite under the pointer
  28500. * @param sprite defines the sprite to use
  28501. */
  28502. Scene.prototype.setPointerOverSprite = function (sprite) {
  28503. if (this._pointerOverSprite === sprite) {
  28504. return;
  28505. }
  28506. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28507. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28508. }
  28509. this._pointerOverSprite = sprite;
  28510. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28511. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28512. }
  28513. };
  28514. /**
  28515. * Gets the sprite under the pointer
  28516. * @returns a Sprite or null if no sprite is under the pointer
  28517. */
  28518. Scene.prototype.getPointerOverSprite = function () {
  28519. return this._pointerOverSprite;
  28520. };
  28521. // Physics
  28522. /**
  28523. * Gets the current physics engine
  28524. * @returns a PhysicsEngine or null if none attached
  28525. */
  28526. Scene.prototype.getPhysicsEngine = function () {
  28527. return this._physicsEngine;
  28528. };
  28529. /**
  28530. * Enables physics to the current scene
  28531. * @param gravity defines the scene's gravity for the physics engine
  28532. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  28533. * @return a boolean indicating if the physics engine was initialized
  28534. */
  28535. Scene.prototype.enablePhysics = function (gravity, plugin) {
  28536. if (gravity === void 0) { gravity = null; }
  28537. if (this._physicsEngine) {
  28538. return true;
  28539. }
  28540. try {
  28541. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  28542. return true;
  28543. }
  28544. catch (e) {
  28545. BABYLON.Tools.Error(e.message);
  28546. return false;
  28547. }
  28548. };
  28549. /**
  28550. * Disables and disposes the physics engine associated with the scene
  28551. */
  28552. Scene.prototype.disablePhysicsEngine = function () {
  28553. if (!this._physicsEngine) {
  28554. return;
  28555. }
  28556. this._physicsEngine.dispose();
  28557. this._physicsEngine = null;
  28558. };
  28559. /**
  28560. * Gets a boolean indicating if there is an active physics engine
  28561. * @returns a boolean indicating if there is an active physics engine
  28562. */
  28563. Scene.prototype.isPhysicsEnabled = function () {
  28564. return this._physicsEngine !== undefined;
  28565. };
  28566. /**
  28567. * Deletes a physics compound impostor
  28568. * @param compound defines the compound to delete
  28569. */
  28570. Scene.prototype.deleteCompoundImpostor = function (compound) {
  28571. var mesh = compound.parts[0].mesh;
  28572. if (mesh.physicsImpostor) {
  28573. mesh.physicsImpostor.dispose( /*true*/);
  28574. mesh.physicsImpostor = null;
  28575. }
  28576. };
  28577. // Misc.
  28578. /** @hidden */
  28579. Scene.prototype._rebuildGeometries = function () {
  28580. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  28581. var geometry = _a[_i];
  28582. geometry._rebuild();
  28583. }
  28584. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  28585. var mesh = _c[_b];
  28586. mesh._rebuild();
  28587. }
  28588. if (this.postProcessManager) {
  28589. this.postProcessManager._rebuild();
  28590. }
  28591. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  28592. var layer = _e[_d];
  28593. layer._rebuild();
  28594. }
  28595. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  28596. var effectLayer = _g[_f];
  28597. effectLayer._rebuild();
  28598. }
  28599. if (this._boundingBoxRenderer) {
  28600. this._boundingBoxRenderer._rebuild();
  28601. }
  28602. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  28603. var system = _j[_h];
  28604. system.rebuild();
  28605. }
  28606. if (this._postProcessRenderPipelineManager) {
  28607. this._postProcessRenderPipelineManager._rebuild();
  28608. }
  28609. };
  28610. /** @hidden */
  28611. Scene.prototype._rebuildTextures = function () {
  28612. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28613. var texture = _a[_i];
  28614. texture._rebuild();
  28615. }
  28616. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  28617. };
  28618. /**
  28619. * Creates a default light for the scene.
  28620. * @param replace Whether to replace the existing lights in the scene.
  28621. */
  28622. Scene.prototype.createDefaultLight = function (replace) {
  28623. if (replace === void 0) { replace = false; }
  28624. // Dispose existing light in replace mode.
  28625. if (replace) {
  28626. if (this.lights) {
  28627. for (var i = 0; i < this.lights.length; i++) {
  28628. this.lights[i].dispose();
  28629. }
  28630. }
  28631. }
  28632. // Light
  28633. if (this.lights.length === 0) {
  28634. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  28635. }
  28636. };
  28637. /**
  28638. * Creates a default camera for the scene.
  28639. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  28640. * @param replace Whether to replace the existing active camera in the scene.
  28641. * @param attachCameraControls Whether to attach camera controls to the canvas.
  28642. */
  28643. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  28644. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28645. if (replace === void 0) { replace = false; }
  28646. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28647. // Dispose existing camera in replace mode.
  28648. if (replace) {
  28649. if (this.activeCamera) {
  28650. this.activeCamera.dispose();
  28651. this.activeCamera = null;
  28652. }
  28653. }
  28654. // Camera
  28655. if (!this.activeCamera) {
  28656. var worldExtends = this.getWorldExtends();
  28657. var worldSize = worldExtends.max.subtract(worldExtends.min);
  28658. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  28659. var camera;
  28660. var radius = worldSize.length() * 1.5;
  28661. // empty scene scenario!
  28662. if (!isFinite(radius)) {
  28663. radius = 1;
  28664. worldCenter.copyFromFloats(0, 0, 0);
  28665. }
  28666. if (createArcRotateCamera) {
  28667. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  28668. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  28669. arcRotateCamera.wheelPrecision = 100 / radius;
  28670. camera = arcRotateCamera;
  28671. }
  28672. else {
  28673. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  28674. freeCamera.setTarget(worldCenter);
  28675. camera = freeCamera;
  28676. }
  28677. camera.minZ = radius * 0.01;
  28678. camera.maxZ = radius * 1000;
  28679. camera.speed = radius * 0.2;
  28680. this.activeCamera = camera;
  28681. var canvas = this.getEngine().getRenderingCanvas();
  28682. if (attachCameraControls && canvas) {
  28683. camera.attachControl(canvas);
  28684. }
  28685. }
  28686. };
  28687. /**
  28688. * Creates a default camera and a default light
  28689. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  28690. * @param replace defines if the camera and/or light will replace the existing ones
  28691. * @param attachCameraControls defines if attachControl will be called on the new camera
  28692. */
  28693. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  28694. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  28695. if (replace === void 0) { replace = false; }
  28696. if (attachCameraControls === void 0) { attachCameraControls = false; }
  28697. this.createDefaultLight(replace);
  28698. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  28699. };
  28700. /**
  28701. * Creates a new sky box
  28702. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28703. * @param environmentTexture defines the texture to use as environment texture
  28704. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  28705. * @param scale defines the overall scale of the skybox
  28706. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  28707. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  28708. * @returns a new mesh holding the sky box
  28709. */
  28710. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  28711. if (pbr === void 0) { pbr = false; }
  28712. if (scale === void 0) { scale = 1000; }
  28713. if (blur === void 0) { blur = 0; }
  28714. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  28715. if (!environmentTexture) {
  28716. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  28717. return null;
  28718. }
  28719. if (setGlobalEnvTexture) {
  28720. if (environmentTexture) {
  28721. this.environmentTexture = environmentTexture;
  28722. }
  28723. }
  28724. // Skybox
  28725. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  28726. if (pbr) {
  28727. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  28728. hdrSkyboxMaterial.backFaceCulling = false;
  28729. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  28730. if (hdrSkyboxMaterial.reflectionTexture) {
  28731. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28732. }
  28733. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  28734. hdrSkyboxMaterial.disableLighting = true;
  28735. hdrSkyboxMaterial.twoSidedLighting = true;
  28736. hdrSkybox.infiniteDistance = true;
  28737. hdrSkybox.material = hdrSkyboxMaterial;
  28738. }
  28739. else {
  28740. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  28741. skyboxMaterial.backFaceCulling = false;
  28742. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  28743. if (skyboxMaterial.reflectionTexture) {
  28744. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  28745. }
  28746. skyboxMaterial.disableLighting = true;
  28747. hdrSkybox.infiniteDistance = true;
  28748. hdrSkybox.material = skyboxMaterial;
  28749. }
  28750. return hdrSkybox;
  28751. };
  28752. /**
  28753. * Creates a new environment
  28754. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  28755. * @param options defines the options you can use to configure the environment
  28756. * @returns the new EnvironmentHelper
  28757. */
  28758. Scene.prototype.createDefaultEnvironment = function (options) {
  28759. if (BABYLON.EnvironmentHelper) {
  28760. return new BABYLON.EnvironmentHelper(options, this);
  28761. }
  28762. return null;
  28763. };
  28764. /**
  28765. * Creates a new VREXperienceHelper
  28766. * @see http://doc.babylonjs.com/how_to/webvr_helper
  28767. * @param webVROptions defines the options used to create the new VREXperienceHelper
  28768. * @returns a new VREXperienceHelper
  28769. */
  28770. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  28771. if (webVROptions === void 0) { webVROptions = {}; }
  28772. return new BABYLON.VRExperienceHelper(this, webVROptions);
  28773. };
  28774. // Tags
  28775. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  28776. if (tagsQuery === undefined) {
  28777. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  28778. return list;
  28779. }
  28780. var listByTags = [];
  28781. forEach = forEach || (function (item) { return; });
  28782. for (var i in list) {
  28783. var item = list[i];
  28784. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  28785. listByTags.push(item);
  28786. forEach(item);
  28787. }
  28788. }
  28789. return listByTags;
  28790. };
  28791. /**
  28792. * Get a list of meshes by tags
  28793. * @param tagsQuery defines the tags query to use
  28794. * @param forEach defines a predicate used to filter results
  28795. * @returns an array of Mesh
  28796. */
  28797. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  28798. return this._getByTags(this.meshes, tagsQuery, forEach);
  28799. };
  28800. /**
  28801. * Get a list of cameras by tags
  28802. * @param tagsQuery defines the tags query to use
  28803. * @param forEach defines a predicate used to filter results
  28804. * @returns an array of Camera
  28805. */
  28806. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  28807. return this._getByTags(this.cameras, tagsQuery, forEach);
  28808. };
  28809. /**
  28810. * Get a list of lights by tags
  28811. * @param tagsQuery defines the tags query to use
  28812. * @param forEach defines a predicate used to filter results
  28813. * @returns an array of Light
  28814. */
  28815. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  28816. return this._getByTags(this.lights, tagsQuery, forEach);
  28817. };
  28818. /**
  28819. * Get a list of materials by tags
  28820. * @param tagsQuery defines the tags query to use
  28821. * @param forEach defines a predicate used to filter results
  28822. * @returns an array of Material
  28823. */
  28824. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  28825. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  28826. };
  28827. /**
  28828. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  28829. * This allowed control for front to back rendering or reversly depending of the special needs.
  28830. *
  28831. * @param renderingGroupId The rendering group id corresponding to its index
  28832. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  28833. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  28834. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  28835. */
  28836. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  28837. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  28838. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  28839. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  28840. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  28841. };
  28842. /**
  28843. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  28844. *
  28845. * @param renderingGroupId The rendering group id corresponding to its index
  28846. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  28847. * @param depth Automatically clears depth between groups if true and autoClear is true.
  28848. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  28849. */
  28850. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  28851. if (depth === void 0) { depth = true; }
  28852. if (stencil === void 0) { stencil = true; }
  28853. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  28854. };
  28855. /**
  28856. * Will flag all materials as dirty to trigger new shader compilation
  28857. * @param flag defines the flag used to specify which material part must be marked as dirty
  28858. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  28859. */
  28860. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  28861. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  28862. var material = _a[_i];
  28863. if (predicate && !predicate(material)) {
  28864. continue;
  28865. }
  28866. material.markAsDirty(flag);
  28867. }
  28868. };
  28869. /** @hidden */
  28870. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  28871. var _this = this;
  28872. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  28873. this._activeRequests.push(request);
  28874. request.onCompleteObservable.add(function (request) {
  28875. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  28876. });
  28877. return request;
  28878. };
  28879. /** @hidden */
  28880. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  28881. var _this = this;
  28882. return new Promise(function (resolve, reject) {
  28883. _this._loadFile(url, function (data) {
  28884. resolve(data);
  28885. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  28886. reject(exception);
  28887. });
  28888. });
  28889. };
  28890. // Statics
  28891. Scene._FOGMODE_NONE = 0;
  28892. Scene._FOGMODE_EXP = 1;
  28893. Scene._FOGMODE_EXP2 = 2;
  28894. Scene._FOGMODE_LINEAR = 3;
  28895. Scene._uniqueIdCounter = 0;
  28896. /**
  28897. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  28898. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28899. */
  28900. Scene.MinDeltaTime = 1.0;
  28901. /**
  28902. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  28903. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  28904. */
  28905. Scene.MaxDeltaTime = 1000.0;
  28906. /** The distance in pixel that you have to move to prevent some events */
  28907. Scene.DragMovementThreshold = 10; // in pixels
  28908. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  28909. Scene.LongPressDelay = 500; // in milliseconds
  28910. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  28911. Scene.DoubleClickDelay = 300; // in milliseconds
  28912. /** If you need to check double click without raising a single click at first click, enable this flag */
  28913. Scene.ExclusiveDoubleClickMode = false;
  28914. return Scene;
  28915. }());
  28916. BABYLON.Scene = Scene;
  28917. })(BABYLON || (BABYLON = {}));
  28918. //# sourceMappingURL=babylon.scene.js.map
  28919. var BABYLON;
  28920. (function (BABYLON) {
  28921. /**
  28922. * Set of assets to keep when moving a scene into an asset container.
  28923. */
  28924. var KeepAssets = /** @class */ (function () {
  28925. function KeepAssets() {
  28926. /**
  28927. * Cameras to keep.
  28928. */
  28929. this.cameras = new Array();
  28930. /**
  28931. * Lights to keep.
  28932. */
  28933. this.lights = new Array();
  28934. /**
  28935. * Meshes to keep.
  28936. */
  28937. this.meshes = new Array();
  28938. /**
  28939. * Skeletons to keep.
  28940. */
  28941. this.skeletons = new Array();
  28942. /**
  28943. * ParticleSystems to keep.
  28944. */
  28945. this.particleSystems = new Array();
  28946. /**
  28947. * Animations to keep.
  28948. */
  28949. this.animations = new Array();
  28950. /**
  28951. * AnimationGroups to keep.
  28952. */
  28953. this.animationGroups = new Array();
  28954. /**
  28955. * MultiMaterials to keep.
  28956. */
  28957. this.multiMaterials = new Array();
  28958. /**
  28959. * Materials to keep.
  28960. */
  28961. this.materials = new Array();
  28962. /**
  28963. * MorphTargetManagers to keep.
  28964. */
  28965. this.morphTargetManagers = new Array();
  28966. /**
  28967. * Geometries to keep.
  28968. */
  28969. this.geometries = new Array();
  28970. /**
  28971. * TransformNodes to keep.
  28972. */
  28973. this.transformNodes = new Array();
  28974. /**
  28975. * LensFlareSystems to keep.
  28976. */
  28977. this.lensFlareSystems = new Array();
  28978. /**
  28979. * ShadowGenerators to keep.
  28980. */
  28981. this.shadowGenerators = new Array();
  28982. /**
  28983. * ActionManagers to keep.
  28984. */
  28985. this.actionManagers = new Array();
  28986. /**
  28987. * Sounds to keep.
  28988. */
  28989. this.sounds = new Array();
  28990. /**
  28991. * Textures to keep.
  28992. */
  28993. this.textures = new Array();
  28994. /**
  28995. * Effect layers to keep.
  28996. */
  28997. this.effectLayers = new Array();
  28998. }
  28999. return KeepAssets;
  29000. }());
  29001. BABYLON.KeepAssets = KeepAssets;
  29002. /**
  29003. * Container with a set of assets that can be added or removed from a scene.
  29004. */
  29005. var AssetContainer = /** @class */ (function () {
  29006. /**
  29007. * Instantiates an AssetContainer.
  29008. * @param scene The scene the AssetContainer belongs to.
  29009. */
  29010. function AssetContainer(scene) {
  29011. // Objects
  29012. /**
  29013. * Cameras populated in the container.
  29014. */
  29015. this.cameras = new Array();
  29016. /**
  29017. * Lights populated in the container.
  29018. */
  29019. this.lights = new Array();
  29020. /**
  29021. * Meshes populated in the container.
  29022. */
  29023. this.meshes = new Array();
  29024. /**
  29025. * Skeletons populated in the container.
  29026. */
  29027. this.skeletons = new Array();
  29028. /**
  29029. * ParticleSystems populated in the container.
  29030. */
  29031. this.particleSystems = new Array();
  29032. /**
  29033. * Animations populated in the container.
  29034. */
  29035. this.animations = new Array();
  29036. /**
  29037. * AnimationGroups populated in the container.
  29038. */
  29039. this.animationGroups = new Array();
  29040. /**
  29041. * MultiMaterials populated in the container.
  29042. */
  29043. this.multiMaterials = new Array();
  29044. /**
  29045. * Materials populated in the container.
  29046. */
  29047. this.materials = new Array();
  29048. /**
  29049. * MorphTargetManagers populated in the container.
  29050. */
  29051. this.morphTargetManagers = new Array();
  29052. /**
  29053. * Geometries populated in the container.
  29054. */
  29055. this.geometries = new Array();
  29056. /**
  29057. * TransformNodes populated in the container.
  29058. */
  29059. this.transformNodes = new Array();
  29060. /**
  29061. * LensFlareSystems populated in the container.
  29062. */
  29063. this.lensFlareSystems = new Array();
  29064. /**
  29065. * ShadowGenerators populated in the container.
  29066. */
  29067. this.shadowGenerators = new Array();
  29068. /**
  29069. * ActionManagers populated in the container.
  29070. */
  29071. this.actionManagers = new Array();
  29072. /**
  29073. * Sounds populated in the container.
  29074. */
  29075. this.sounds = new Array();
  29076. /**
  29077. * Textures populated in the container.
  29078. */
  29079. this.textures = new Array();
  29080. /**
  29081. * Effect layers populated in the container.
  29082. */
  29083. this.effectLayers = new Array();
  29084. this.scene = scene;
  29085. }
  29086. /**
  29087. * Adds all the assets from the container to the scene.
  29088. */
  29089. AssetContainer.prototype.addAllToScene = function () {
  29090. var _this = this;
  29091. this.cameras.forEach(function (o) {
  29092. _this.scene.addCamera(o);
  29093. });
  29094. this.lights.forEach(function (o) {
  29095. _this.scene.addLight(o);
  29096. });
  29097. this.meshes.forEach(function (o) {
  29098. _this.scene.addMesh(o);
  29099. });
  29100. this.skeletons.forEach(function (o) {
  29101. _this.scene.addSkeleton(o);
  29102. });
  29103. this.particleSystems.forEach(function (o) {
  29104. _this.scene.addParticleSystem(o);
  29105. });
  29106. this.animations.forEach(function (o) {
  29107. _this.scene.addAnimation(o);
  29108. });
  29109. this.animationGroups.forEach(function (o) {
  29110. _this.scene.addAnimationGroup(o);
  29111. });
  29112. this.multiMaterials.forEach(function (o) {
  29113. _this.scene.addMultiMaterial(o);
  29114. });
  29115. this.materials.forEach(function (o) {
  29116. _this.scene.addMaterial(o);
  29117. });
  29118. this.morphTargetManagers.forEach(function (o) {
  29119. _this.scene.addMorphTargetManager(o);
  29120. });
  29121. this.geometries.forEach(function (o) {
  29122. _this.scene.addGeometry(o);
  29123. });
  29124. this.transformNodes.forEach(function (o) {
  29125. _this.scene.addTransformNode(o);
  29126. });
  29127. this.lensFlareSystems.forEach(function (o) {
  29128. _this.scene.addLensFlareSystem(o);
  29129. });
  29130. this.actionManagers.forEach(function (o) {
  29131. _this.scene.addActionManager(o);
  29132. });
  29133. this.sounds.forEach(function (o) {
  29134. o.play();
  29135. o.autoplay = true;
  29136. _this.scene.mainSoundTrack.AddSound(o);
  29137. });
  29138. this.textures.forEach(function (o) {
  29139. _this.scene.addTexture(o);
  29140. });
  29141. this.effectLayers.forEach(function (o) {
  29142. _this.scene.addEffectLayer(o);
  29143. });
  29144. };
  29145. /**
  29146. * Removes all the assets in the container from the scene
  29147. */
  29148. AssetContainer.prototype.removeAllFromScene = function () {
  29149. var _this = this;
  29150. this.cameras.forEach(function (o) {
  29151. _this.scene.removeCamera(o);
  29152. });
  29153. this.lights.forEach(function (o) {
  29154. _this.scene.removeLight(o);
  29155. });
  29156. this.meshes.forEach(function (o) {
  29157. _this.scene.removeMesh(o);
  29158. });
  29159. this.skeletons.forEach(function (o) {
  29160. _this.scene.removeSkeleton(o);
  29161. });
  29162. this.particleSystems.forEach(function (o) {
  29163. _this.scene.removeParticleSystem(o);
  29164. });
  29165. this.animations.forEach(function (o) {
  29166. _this.scene.removeAnimation(o);
  29167. });
  29168. this.animationGroups.forEach(function (o) {
  29169. _this.scene.removeAnimationGroup(o);
  29170. });
  29171. this.multiMaterials.forEach(function (o) {
  29172. _this.scene.removeMultiMaterial(o);
  29173. });
  29174. this.materials.forEach(function (o) {
  29175. _this.scene.removeMaterial(o);
  29176. });
  29177. this.morphTargetManagers.forEach(function (o) {
  29178. _this.scene.removeMorphTargetManager(o);
  29179. });
  29180. this.geometries.forEach(function (o) {
  29181. _this.scene.removeGeometry(o);
  29182. });
  29183. this.transformNodes.forEach(function (o) {
  29184. _this.scene.removeTransformNode(o);
  29185. });
  29186. this.lensFlareSystems.forEach(function (o) {
  29187. _this.scene.removeLensFlareSystem(o);
  29188. });
  29189. this.actionManagers.forEach(function (o) {
  29190. _this.scene.removeActionManager(o);
  29191. });
  29192. this.sounds.forEach(function (o) {
  29193. o.stop();
  29194. o.autoplay = false;
  29195. _this.scene.mainSoundTrack.RemoveSound(o);
  29196. });
  29197. this.textures.forEach(function (o) {
  29198. _this.scene.removeTexture(o);
  29199. });
  29200. this.effectLayers.forEach(function (o) {
  29201. _this.scene.removeEffectLayer(o);
  29202. });
  29203. };
  29204. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29205. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29206. var asset = sourceAssets_1[_i];
  29207. var move = true;
  29208. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29209. var keepAsset = keepAssets_1[_a];
  29210. if (asset === keepAsset) {
  29211. move = false;
  29212. break;
  29213. }
  29214. }
  29215. if (move) {
  29216. targetAssets.push(asset);
  29217. }
  29218. }
  29219. };
  29220. /**
  29221. * Removes all the assets contained in the scene and adds them to the container.
  29222. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29223. */
  29224. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29225. if (keepAssets === undefined) {
  29226. keepAssets = new KeepAssets();
  29227. }
  29228. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29229. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29230. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29231. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29232. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29233. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29234. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29235. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29236. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29237. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29238. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29239. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29240. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29241. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29242. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29243. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29244. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29245. this.removeAllFromScene();
  29246. };
  29247. return AssetContainer;
  29248. }());
  29249. BABYLON.AssetContainer = AssetContainer;
  29250. })(BABYLON || (BABYLON = {}));
  29251. //# sourceMappingURL=babylon.assetContainer.js.map
  29252. var BABYLON;
  29253. (function (BABYLON) {
  29254. var Buffer = /** @class */ (function () {
  29255. /**
  29256. * Constructor
  29257. * @param engine the engine
  29258. * @param data the data to use for this buffer
  29259. * @param updatable whether the data is updatable
  29260. * @param stride the stride (optional)
  29261. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29262. * @param instanced whether the buffer is instanced (optional)
  29263. * @param useBytes set to true if the stride in in bytes (optional)
  29264. */
  29265. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29266. if (stride === void 0) { stride = 0; }
  29267. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29268. if (instanced === void 0) { instanced = false; }
  29269. if (useBytes === void 0) { useBytes = false; }
  29270. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29271. this._engine = engine.getScene().getEngine();
  29272. }
  29273. else {
  29274. this._engine = engine;
  29275. }
  29276. this._updatable = updatable;
  29277. this._instanced = instanced;
  29278. this._data = data;
  29279. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29280. if (!postponeInternalCreation) { // by default
  29281. this.create();
  29282. }
  29283. }
  29284. /**
  29285. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29286. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29287. * @param offset defines offset in the buffer (0 by default)
  29288. * @param size defines the size in floats of attributes (position is 3 for instance)
  29289. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29290. * @param instanced defines if the vertex buffer contains indexed data
  29291. * @param useBytes defines if the offset and stride are in bytes
  29292. * @returns the new vertex buffer
  29293. */
  29294. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29295. if (useBytes === void 0) { useBytes = false; }
  29296. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29297. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29298. // a lot of these parameters are ignored as they are overriden by the buffer
  29299. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29300. };
  29301. // Properties
  29302. Buffer.prototype.isUpdatable = function () {
  29303. return this._updatable;
  29304. };
  29305. Buffer.prototype.getData = function () {
  29306. return this._data;
  29307. };
  29308. Buffer.prototype.getBuffer = function () {
  29309. return this._buffer;
  29310. };
  29311. /**
  29312. * Gets the stride in float32 units (i.e. byte stride / 4).
  29313. * May not be an integer if the byte stride is not divisible by 4.
  29314. * DEPRECATED. Use byteStride instead.
  29315. * @returns the stride in float32 units
  29316. */
  29317. Buffer.prototype.getStrideSize = function () {
  29318. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29319. };
  29320. // Methods
  29321. Buffer.prototype.create = function (data) {
  29322. if (data === void 0) { data = null; }
  29323. if (!data && this._buffer) {
  29324. return; // nothing to do
  29325. }
  29326. data = data || this._data;
  29327. if (!data) {
  29328. return;
  29329. }
  29330. if (!this._buffer) { // create buffer
  29331. if (this._updatable) {
  29332. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29333. this._data = data;
  29334. }
  29335. else {
  29336. this._buffer = this._engine.createVertexBuffer(data);
  29337. }
  29338. }
  29339. else if (this._updatable) { // update buffer
  29340. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29341. this._data = data;
  29342. }
  29343. };
  29344. Buffer.prototype._rebuild = function () {
  29345. this._buffer = null;
  29346. this.create(this._data);
  29347. };
  29348. Buffer.prototype.update = function (data) {
  29349. this.create(data);
  29350. };
  29351. /**
  29352. * Updates the data directly.
  29353. * @param data the new data
  29354. * @param offset the new offset
  29355. * @param vertexCount the vertex count (optional)
  29356. * @param useBytes set to true if the offset is in bytes
  29357. */
  29358. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29359. if (useBytes === void 0) { useBytes = false; }
  29360. if (!this._buffer) {
  29361. return;
  29362. }
  29363. if (this._updatable) { // update buffer
  29364. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29365. this._data = null;
  29366. }
  29367. };
  29368. Buffer.prototype.dispose = function () {
  29369. if (!this._buffer) {
  29370. return;
  29371. }
  29372. if (this._engine._releaseBuffer(this._buffer)) {
  29373. this._buffer = null;
  29374. }
  29375. };
  29376. return Buffer;
  29377. }());
  29378. BABYLON.Buffer = Buffer;
  29379. })(BABYLON || (BABYLON = {}));
  29380. //# sourceMappingURL=babylon.buffer.js.map
  29381. var BABYLON;
  29382. (function (BABYLON) {
  29383. var VertexBuffer = /** @class */ (function () {
  29384. /**
  29385. * Constructor
  29386. * @param engine the engine
  29387. * @param data the data to use for this vertex buffer
  29388. * @param kind the vertex buffer kind
  29389. * @param updatable whether the data is updatable
  29390. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29391. * @param stride the stride (optional)
  29392. * @param instanced whether the buffer is instanced (optional)
  29393. * @param offset the offset of the data (optional)
  29394. * @param size the number of components (optional)
  29395. * @param type the type of the component (optional)
  29396. * @param normalized whether the data contains normalized data (optional)
  29397. * @param useBytes set to true if stride and offset are in bytes (optional)
  29398. */
  29399. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29400. if (normalized === void 0) { normalized = false; }
  29401. if (useBytes === void 0) { useBytes = false; }
  29402. if (data instanceof BABYLON.Buffer) {
  29403. this._buffer = data;
  29404. this._ownsBuffer = false;
  29405. }
  29406. else {
  29407. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29408. this._ownsBuffer = true;
  29409. }
  29410. this._kind = kind;
  29411. if (type == undefined) {
  29412. var data_1 = this.getData();
  29413. this.type = VertexBuffer.FLOAT;
  29414. if (data_1 instanceof Int8Array)
  29415. this.type = VertexBuffer.BYTE;
  29416. else if (data_1 instanceof Uint8Array)
  29417. this.type = VertexBuffer.UNSIGNED_BYTE;
  29418. else if (data_1 instanceof Int16Array)
  29419. this.type = VertexBuffer.SHORT;
  29420. else if (data_1 instanceof Uint16Array)
  29421. this.type = VertexBuffer.UNSIGNED_SHORT;
  29422. else if (data_1 instanceof Int32Array)
  29423. this.type = VertexBuffer.INT;
  29424. else if (data_1 instanceof Uint32Array)
  29425. this.type = VertexBuffer.UNSIGNED_INT;
  29426. }
  29427. else {
  29428. this.type = type;
  29429. }
  29430. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29431. if (useBytes) {
  29432. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29433. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29434. this.byteOffset = offset || 0;
  29435. }
  29436. else {
  29437. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29438. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29439. this.byteOffset = (offset || 0) * typeByteLength;
  29440. }
  29441. this.normalized = normalized;
  29442. this._instanced = instanced !== undefined ? instanced : false;
  29443. this._instanceDivisor = instanced ? 1 : 0;
  29444. }
  29445. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29446. /**
  29447. * Gets or sets the instance divisor when in instanced mode
  29448. */
  29449. get: function () {
  29450. return this._instanceDivisor;
  29451. },
  29452. set: function (value) {
  29453. this._instanceDivisor = value;
  29454. if (value == 0) {
  29455. this._instanced = false;
  29456. }
  29457. else {
  29458. this._instanced = true;
  29459. }
  29460. },
  29461. enumerable: true,
  29462. configurable: true
  29463. });
  29464. VertexBuffer.prototype._rebuild = function () {
  29465. if (!this._buffer) {
  29466. return;
  29467. }
  29468. this._buffer._rebuild();
  29469. };
  29470. /**
  29471. * Returns the kind of the VertexBuffer (string).
  29472. */
  29473. VertexBuffer.prototype.getKind = function () {
  29474. return this._kind;
  29475. };
  29476. // Properties
  29477. /**
  29478. * Boolean : is the VertexBuffer updatable ?
  29479. */
  29480. VertexBuffer.prototype.isUpdatable = function () {
  29481. return this._buffer.isUpdatable();
  29482. };
  29483. /**
  29484. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29485. */
  29486. VertexBuffer.prototype.getData = function () {
  29487. return this._buffer.getData();
  29488. };
  29489. /**
  29490. * Returns the WebGLBuffer associated to the VertexBuffer.
  29491. */
  29492. VertexBuffer.prototype.getBuffer = function () {
  29493. return this._buffer.getBuffer();
  29494. };
  29495. /**
  29496. * Returns the stride as a multiple of the type byte length.
  29497. * DEPRECATED. Use byteStride instead.
  29498. */
  29499. VertexBuffer.prototype.getStrideSize = function () {
  29500. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29501. };
  29502. /**
  29503. * Returns the offset as a multiple of the type byte length.
  29504. * DEPRECATED. Use byteOffset instead.
  29505. */
  29506. VertexBuffer.prototype.getOffset = function () {
  29507. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29508. };
  29509. /**
  29510. * Returns the number of components per vertex attribute (integer).
  29511. */
  29512. VertexBuffer.prototype.getSize = function () {
  29513. return this._size;
  29514. };
  29515. /**
  29516. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  29517. */
  29518. VertexBuffer.prototype.getIsInstanced = function () {
  29519. return this._instanced;
  29520. };
  29521. /**
  29522. * Returns the instancing divisor, zero for non-instanced (integer).
  29523. */
  29524. VertexBuffer.prototype.getInstanceDivisor = function () {
  29525. return this._instanceDivisor;
  29526. };
  29527. // Methods
  29528. /**
  29529. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  29530. * Returns the created WebGLBuffer.
  29531. */
  29532. VertexBuffer.prototype.create = function (data) {
  29533. return this._buffer.create(data);
  29534. };
  29535. /**
  29536. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29537. * This function will create a new buffer if the current one is not updatable
  29538. * Returns the updated WebGLBuffer.
  29539. */
  29540. VertexBuffer.prototype.update = function (data) {
  29541. return this._buffer.update(data);
  29542. };
  29543. /**
  29544. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  29545. * Returns the directly updated WebGLBuffer.
  29546. * @param data the new data
  29547. * @param offset the new offset
  29548. * @param useBytes set to true if the offset is in bytes
  29549. */
  29550. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  29551. if (useBytes === void 0) { useBytes = false; }
  29552. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  29553. };
  29554. /**
  29555. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  29556. */
  29557. VertexBuffer.prototype.dispose = function () {
  29558. if (this._ownsBuffer) {
  29559. this._buffer.dispose();
  29560. }
  29561. };
  29562. /**
  29563. * Enumerates each value of this vertex buffer as numbers.
  29564. * @param count the number of values to enumerate
  29565. * @param callback the callback function called for each value
  29566. */
  29567. VertexBuffer.prototype.forEach = function (count, callback) {
  29568. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  29569. };
  29570. Object.defineProperty(VertexBuffer, "PositionKind", {
  29571. get: function () {
  29572. return VertexBuffer._PositionKind;
  29573. },
  29574. enumerable: true,
  29575. configurable: true
  29576. });
  29577. Object.defineProperty(VertexBuffer, "NormalKind", {
  29578. get: function () {
  29579. return VertexBuffer._NormalKind;
  29580. },
  29581. enumerable: true,
  29582. configurable: true
  29583. });
  29584. Object.defineProperty(VertexBuffer, "TangentKind", {
  29585. get: function () {
  29586. return VertexBuffer._TangentKind;
  29587. },
  29588. enumerable: true,
  29589. configurable: true
  29590. });
  29591. Object.defineProperty(VertexBuffer, "UVKind", {
  29592. get: function () {
  29593. return VertexBuffer._UVKind;
  29594. },
  29595. enumerable: true,
  29596. configurable: true
  29597. });
  29598. Object.defineProperty(VertexBuffer, "UV2Kind", {
  29599. get: function () {
  29600. return VertexBuffer._UV2Kind;
  29601. },
  29602. enumerable: true,
  29603. configurable: true
  29604. });
  29605. Object.defineProperty(VertexBuffer, "UV3Kind", {
  29606. get: function () {
  29607. return VertexBuffer._UV3Kind;
  29608. },
  29609. enumerable: true,
  29610. configurable: true
  29611. });
  29612. Object.defineProperty(VertexBuffer, "UV4Kind", {
  29613. get: function () {
  29614. return VertexBuffer._UV4Kind;
  29615. },
  29616. enumerable: true,
  29617. configurable: true
  29618. });
  29619. Object.defineProperty(VertexBuffer, "UV5Kind", {
  29620. get: function () {
  29621. return VertexBuffer._UV5Kind;
  29622. },
  29623. enumerable: true,
  29624. configurable: true
  29625. });
  29626. Object.defineProperty(VertexBuffer, "UV6Kind", {
  29627. get: function () {
  29628. return VertexBuffer._UV6Kind;
  29629. },
  29630. enumerable: true,
  29631. configurable: true
  29632. });
  29633. Object.defineProperty(VertexBuffer, "ColorKind", {
  29634. get: function () {
  29635. return VertexBuffer._ColorKind;
  29636. },
  29637. enumerable: true,
  29638. configurable: true
  29639. });
  29640. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  29641. get: function () {
  29642. return VertexBuffer._MatricesIndicesKind;
  29643. },
  29644. enumerable: true,
  29645. configurable: true
  29646. });
  29647. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  29648. get: function () {
  29649. return VertexBuffer._MatricesWeightsKind;
  29650. },
  29651. enumerable: true,
  29652. configurable: true
  29653. });
  29654. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  29655. get: function () {
  29656. return VertexBuffer._MatricesIndicesExtraKind;
  29657. },
  29658. enumerable: true,
  29659. configurable: true
  29660. });
  29661. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  29662. get: function () {
  29663. return VertexBuffer._MatricesWeightsExtraKind;
  29664. },
  29665. enumerable: true,
  29666. configurable: true
  29667. });
  29668. /**
  29669. * Deduces the stride given a kind.
  29670. * @param kind The kind string to deduce
  29671. * @returns The deduced stride
  29672. */
  29673. VertexBuffer.DeduceStride = function (kind) {
  29674. switch (kind) {
  29675. case VertexBuffer.UVKind:
  29676. case VertexBuffer.UV2Kind:
  29677. case VertexBuffer.UV3Kind:
  29678. case VertexBuffer.UV4Kind:
  29679. case VertexBuffer.UV5Kind:
  29680. case VertexBuffer.UV6Kind:
  29681. return 2;
  29682. case VertexBuffer.NormalKind:
  29683. case VertexBuffer.PositionKind:
  29684. return 3;
  29685. case VertexBuffer.ColorKind:
  29686. case VertexBuffer.MatricesIndicesKind:
  29687. case VertexBuffer.MatricesIndicesExtraKind:
  29688. case VertexBuffer.MatricesWeightsKind:
  29689. case VertexBuffer.MatricesWeightsExtraKind:
  29690. case VertexBuffer.TangentKind:
  29691. return 4;
  29692. default:
  29693. throw new Error("Invalid kind '" + kind + "'");
  29694. }
  29695. };
  29696. /**
  29697. * Gets the byte length of the given type.
  29698. * @param type the type
  29699. * @returns the number of bytes
  29700. */
  29701. VertexBuffer.GetTypeByteLength = function (type) {
  29702. switch (type) {
  29703. case VertexBuffer.BYTE:
  29704. case VertexBuffer.UNSIGNED_BYTE:
  29705. return 1;
  29706. case VertexBuffer.SHORT:
  29707. case VertexBuffer.UNSIGNED_SHORT:
  29708. return 2;
  29709. case VertexBuffer.INT:
  29710. case VertexBuffer.FLOAT:
  29711. return 4;
  29712. default:
  29713. throw new Error("Invalid type '" + type + "'");
  29714. }
  29715. };
  29716. /**
  29717. * Enumerates each value of the given parameters as numbers.
  29718. * @param data the data to enumerate
  29719. * @param byteOffset the byte offset of the data
  29720. * @param byteStride the byte stride of the data
  29721. * @param componentCount the number of components per element
  29722. * @param componentType the type of the component
  29723. * @param count the total number of components
  29724. * @param normalized whether the data is normalized
  29725. * @param callback the callback function called for each value
  29726. */
  29727. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  29728. if (data instanceof Array) {
  29729. var offset = byteOffset / 4;
  29730. var stride = byteStride / 4;
  29731. for (var index = 0; index < count; index += componentCount) {
  29732. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29733. callback(data[offset + componentIndex], index + componentIndex);
  29734. }
  29735. offset += stride;
  29736. }
  29737. }
  29738. else {
  29739. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  29740. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  29741. for (var index = 0; index < count; index += componentCount) {
  29742. var componentByteOffset = byteOffset;
  29743. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  29744. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  29745. callback(value, index + componentIndex);
  29746. componentByteOffset += componentByteLength;
  29747. }
  29748. byteOffset += byteStride;
  29749. }
  29750. }
  29751. };
  29752. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  29753. switch (type) {
  29754. case VertexBuffer.BYTE: {
  29755. var value = dataView.getInt8(byteOffset);
  29756. if (normalized) {
  29757. value = Math.max(value / 127, -1);
  29758. }
  29759. return value;
  29760. }
  29761. case VertexBuffer.UNSIGNED_BYTE: {
  29762. var value = dataView.getUint8(byteOffset);
  29763. if (normalized) {
  29764. value = value / 255;
  29765. }
  29766. return value;
  29767. }
  29768. case VertexBuffer.SHORT: {
  29769. var value = dataView.getInt16(byteOffset, true);
  29770. if (normalized) {
  29771. value = Math.max(value / 16383, -1);
  29772. }
  29773. return value;
  29774. }
  29775. case VertexBuffer.UNSIGNED_SHORT: {
  29776. var value = dataView.getUint16(byteOffset, true);
  29777. if (normalized) {
  29778. value = value / 65535;
  29779. }
  29780. return value;
  29781. }
  29782. case VertexBuffer.FLOAT: {
  29783. return dataView.getFloat32(byteOffset, true);
  29784. }
  29785. default: {
  29786. throw new Error("Invalid component type " + type);
  29787. }
  29788. }
  29789. };
  29790. /**
  29791. * The byte type.
  29792. */
  29793. VertexBuffer.BYTE = 5120;
  29794. /**
  29795. * The unsigned byte type.
  29796. */
  29797. VertexBuffer.UNSIGNED_BYTE = 5121;
  29798. /**
  29799. * The short type.
  29800. */
  29801. VertexBuffer.SHORT = 5122;
  29802. /**
  29803. * The unsigned short type.
  29804. */
  29805. VertexBuffer.UNSIGNED_SHORT = 5123;
  29806. /**
  29807. * The integer type.
  29808. */
  29809. VertexBuffer.INT = 5124;
  29810. /**
  29811. * The unsigned integer type.
  29812. */
  29813. VertexBuffer.UNSIGNED_INT = 5125;
  29814. /**
  29815. * The float type.
  29816. */
  29817. VertexBuffer.FLOAT = 5126;
  29818. // Enums
  29819. VertexBuffer._PositionKind = "position";
  29820. VertexBuffer._NormalKind = "normal";
  29821. VertexBuffer._TangentKind = "tangent";
  29822. VertexBuffer._UVKind = "uv";
  29823. VertexBuffer._UV2Kind = "uv2";
  29824. VertexBuffer._UV3Kind = "uv3";
  29825. VertexBuffer._UV4Kind = "uv4";
  29826. VertexBuffer._UV5Kind = "uv5";
  29827. VertexBuffer._UV6Kind = "uv6";
  29828. VertexBuffer._ColorKind = "color";
  29829. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  29830. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  29831. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  29832. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  29833. return VertexBuffer;
  29834. }());
  29835. BABYLON.VertexBuffer = VertexBuffer;
  29836. })(BABYLON || (BABYLON = {}));
  29837. //# sourceMappingURL=babylon.vertexBuffer.js.map
  29838. var BABYLON;
  29839. (function (BABYLON) {
  29840. /**
  29841. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  29842. */
  29843. var DummyInternalTextureTracker = /** @class */ (function () {
  29844. function DummyInternalTextureTracker() {
  29845. /**
  29846. * Gets or set the previous tracker in the list
  29847. */
  29848. this.previous = null;
  29849. /**
  29850. * Gets or set the next tracker in the list
  29851. */
  29852. this.next = null;
  29853. }
  29854. return DummyInternalTextureTracker;
  29855. }());
  29856. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  29857. })(BABYLON || (BABYLON = {}));
  29858. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  29859. var BABYLON;
  29860. (function (BABYLON) {
  29861. /**
  29862. * Class used to store data associated with WebGL texture data for the engine
  29863. * This class should not be used directly
  29864. */
  29865. var InternalTexture = /** @class */ (function () {
  29866. /**
  29867. * Creates a new InternalTexture
  29868. * @param engine defines the engine to use
  29869. * @param dataSource defines the type of data that will be used
  29870. */
  29871. function InternalTexture(engine, dataSource) {
  29872. /**
  29873. * Observable called when the texture is loaded
  29874. */
  29875. this.onLoadedObservable = new BABYLON.Observable();
  29876. /**
  29877. * Gets or set the previous tracker in the list
  29878. */
  29879. this.previous = null;
  29880. /**
  29881. * Gets or set the next tracker in the list
  29882. */
  29883. this.next = null;
  29884. // Private
  29885. /** @hidden */
  29886. this._initialSlot = -1;
  29887. /** @hidden */
  29888. this._designatedSlot = -1;
  29889. /** @hidden */
  29890. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  29891. /** @hidden */
  29892. this._comparisonFunction = 0;
  29893. /** @hidden */
  29894. this._references = 1;
  29895. this._engine = engine;
  29896. this._dataSource = dataSource;
  29897. this._webGLTexture = engine._createTexture();
  29898. }
  29899. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  29900. /**
  29901. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  29902. */
  29903. get: function () {
  29904. return this._dataSource;
  29905. },
  29906. enumerable: true,
  29907. configurable: true
  29908. });
  29909. /**
  29910. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  29911. */
  29912. InternalTexture.prototype.incrementReferences = function () {
  29913. this._references++;
  29914. };
  29915. /**
  29916. * Change the size of the texture (not the size of the content)
  29917. * @param width defines the new width
  29918. * @param height defines the new height
  29919. * @param depth defines the new depth (1 by default)
  29920. */
  29921. InternalTexture.prototype.updateSize = function (width, height, depth) {
  29922. if (depth === void 0) { depth = 1; }
  29923. this.width = width;
  29924. this.height = height;
  29925. this.depth = depth;
  29926. this.baseWidth = width;
  29927. this.baseHeight = height;
  29928. this.baseDepth = depth;
  29929. this._size = width * height * depth;
  29930. };
  29931. /** @hidden */
  29932. InternalTexture.prototype._rebuild = function () {
  29933. var _this = this;
  29934. var proxy;
  29935. this.isReady = false;
  29936. this._cachedCoordinatesMode = null;
  29937. this._cachedWrapU = null;
  29938. this._cachedWrapV = null;
  29939. this._cachedAnisotropicFilteringLevel = null;
  29940. switch (this._dataSource) {
  29941. case InternalTexture.DATASOURCE_TEMP:
  29942. return;
  29943. case InternalTexture.DATASOURCE_URL:
  29944. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  29945. _this.isReady = true;
  29946. }, null, this._buffer, undefined, this.format);
  29947. proxy._swapAndDie(this);
  29948. return;
  29949. case InternalTexture.DATASOURCE_RAW:
  29950. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29951. proxy._swapAndDie(this);
  29952. this.isReady = true;
  29953. return;
  29954. case InternalTexture.DATASOURCE_RAW3D:
  29955. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  29956. proxy._swapAndDie(this);
  29957. this.isReady = true;
  29958. return;
  29959. case InternalTexture.DATASOURCE_DYNAMIC:
  29960. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  29961. proxy._swapAndDie(this);
  29962. // The engine will make sure to update content so no need to flag it as isReady = true
  29963. return;
  29964. case InternalTexture.DATASOURCE_RENDERTARGET:
  29965. var options = new BABYLON.RenderTargetCreationOptions();
  29966. options.generateDepthBuffer = this._generateDepthBuffer;
  29967. options.generateMipMaps = this.generateMipMaps;
  29968. options.generateStencilBuffer = this._generateStencilBuffer;
  29969. options.samplingMode = this.samplingMode;
  29970. options.type = this.type;
  29971. if (this.isCube) {
  29972. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  29973. }
  29974. else {
  29975. var size = {
  29976. width: this.width,
  29977. height: this.height
  29978. };
  29979. proxy = this._engine.createRenderTargetTexture(size, options);
  29980. }
  29981. proxy._swapAndDie(this);
  29982. this.isReady = true;
  29983. return;
  29984. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  29985. var depthTextureOptions = {
  29986. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  29987. comparisonFunction: this._comparisonFunction,
  29988. generateStencil: this._generateStencilBuffer,
  29989. isCube: this.isCube
  29990. };
  29991. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  29992. proxy._swapAndDie(this);
  29993. this.isReady = true;
  29994. return;
  29995. case InternalTexture.DATASOURCE_CUBE:
  29996. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  29997. _this.isReady = true;
  29998. }, null, this.format, this._extension);
  29999. proxy._swapAndDie(this);
  30000. return;
  30001. case InternalTexture.DATASOURCE_CUBERAW:
  30002. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30003. proxy._swapAndDie(this);
  30004. this.isReady = true;
  30005. return;
  30006. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30007. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30008. if (proxy) {
  30009. proxy._swapAndDie(_this);
  30010. }
  30011. _this.isReady = true;
  30012. }, null, this.format, this._extension);
  30013. return;
  30014. }
  30015. };
  30016. InternalTexture.prototype._swapAndDie = function (target) {
  30017. target._webGLTexture = this._webGLTexture;
  30018. if (this._framebuffer) {
  30019. target._framebuffer = this._framebuffer;
  30020. }
  30021. if (this._depthStencilBuffer) {
  30022. target._depthStencilBuffer = this._depthStencilBuffer;
  30023. }
  30024. if (this._lodTextureHigh) {
  30025. if (target._lodTextureHigh) {
  30026. target._lodTextureHigh.dispose();
  30027. }
  30028. target._lodTextureHigh = this._lodTextureHigh;
  30029. }
  30030. if (this._lodTextureMid) {
  30031. if (target._lodTextureMid) {
  30032. target._lodTextureMid.dispose();
  30033. }
  30034. target._lodTextureMid = this._lodTextureMid;
  30035. }
  30036. if (this._lodTextureLow) {
  30037. if (target._lodTextureLow) {
  30038. target._lodTextureLow.dispose();
  30039. }
  30040. target._lodTextureLow = this._lodTextureLow;
  30041. }
  30042. var cache = this._engine.getLoadedTexturesCache();
  30043. var index = cache.indexOf(this);
  30044. if (index !== -1) {
  30045. cache.splice(index, 1);
  30046. }
  30047. };
  30048. /**
  30049. * Dispose the current allocated resources
  30050. */
  30051. InternalTexture.prototype.dispose = function () {
  30052. if (!this._webGLTexture) {
  30053. return;
  30054. }
  30055. this._references--;
  30056. if (this._references === 0) {
  30057. this._engine._releaseTexture(this);
  30058. this._webGLTexture = null;
  30059. this.previous = null;
  30060. this.next = null;
  30061. }
  30062. };
  30063. /**
  30064. * The source of the texture data is unknown
  30065. */
  30066. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30067. /**
  30068. * Texture data comes from an URL
  30069. */
  30070. InternalTexture.DATASOURCE_URL = 1;
  30071. /**
  30072. * Texture data is only used for temporary storage
  30073. */
  30074. InternalTexture.DATASOURCE_TEMP = 2;
  30075. /**
  30076. * Texture data comes from raw data (ArrayBuffer)
  30077. */
  30078. InternalTexture.DATASOURCE_RAW = 3;
  30079. /**
  30080. * Texture content is dynamic (video or dynamic texture)
  30081. */
  30082. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30083. /**
  30084. * Texture content is generated by rendering to it
  30085. */
  30086. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30087. /**
  30088. * Texture content is part of a multi render target process
  30089. */
  30090. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30091. /**
  30092. * Texture data comes from a cube data file
  30093. */
  30094. InternalTexture.DATASOURCE_CUBE = 7;
  30095. /**
  30096. * Texture data comes from a raw cube data
  30097. */
  30098. InternalTexture.DATASOURCE_CUBERAW = 8;
  30099. /**
  30100. * Texture data come from a prefiltered cube data file
  30101. */
  30102. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30103. /**
  30104. * Texture content is raw 3D data
  30105. */
  30106. InternalTexture.DATASOURCE_RAW3D = 10;
  30107. /**
  30108. * Texture content is a depth texture
  30109. */
  30110. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30111. return InternalTexture;
  30112. }());
  30113. BABYLON.InternalTexture = InternalTexture;
  30114. })(BABYLON || (BABYLON = {}));
  30115. //# sourceMappingURL=babylon.internalTexture.js.map
  30116. var BABYLON;
  30117. (function (BABYLON) {
  30118. var BaseTexture = /** @class */ (function () {
  30119. function BaseTexture(scene) {
  30120. this._hasAlpha = false;
  30121. this.getAlphaFromRGB = false;
  30122. this.level = 1;
  30123. this.coordinatesIndex = 0;
  30124. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30125. /**
  30126. * | Value | Type | Description |
  30127. * | ----- | ------------------ | ----------- |
  30128. * | 0 | CLAMP_ADDRESSMODE | |
  30129. * | 1 | WRAP_ADDRESSMODE | |
  30130. * | 2 | MIRROR_ADDRESSMODE | |
  30131. */
  30132. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30133. /**
  30134. * | Value | Type | Description |
  30135. * | ----- | ------------------ | ----------- |
  30136. * | 0 | CLAMP_ADDRESSMODE | |
  30137. * | 1 | WRAP_ADDRESSMODE | |
  30138. * | 2 | MIRROR_ADDRESSMODE | |
  30139. */
  30140. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30141. /**
  30142. * | Value | Type | Description |
  30143. * | ----- | ------------------ | ----------- |
  30144. * | 0 | CLAMP_ADDRESSMODE | |
  30145. * | 1 | WRAP_ADDRESSMODE | |
  30146. * | 2 | MIRROR_ADDRESSMODE | |
  30147. */
  30148. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30149. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30150. this.isCube = false;
  30151. this.is3D = false;
  30152. this.gammaSpace = true;
  30153. this.invertZ = false;
  30154. this.lodLevelInAlpha = false;
  30155. this.lodGenerationOffset = 0.0;
  30156. this.lodGenerationScale = 0.8;
  30157. this.isRenderTarget = false;
  30158. this.animations = new Array();
  30159. /**
  30160. * An event triggered when the texture is disposed.
  30161. */
  30162. this.onDisposeObservable = new BABYLON.Observable();
  30163. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30164. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30165. if (this._scene) {
  30166. this._scene.textures.push(this);
  30167. }
  30168. this._uid = null;
  30169. }
  30170. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30171. get: function () {
  30172. return this._hasAlpha;
  30173. },
  30174. set: function (value) {
  30175. if (this._hasAlpha === value) {
  30176. return;
  30177. }
  30178. this._hasAlpha = value;
  30179. if (this._scene) {
  30180. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30181. }
  30182. },
  30183. enumerable: true,
  30184. configurable: true
  30185. });
  30186. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30187. get: function () {
  30188. return this._coordinatesMode;
  30189. },
  30190. /**
  30191. * How a texture is mapped.
  30192. *
  30193. * | Value | Type | Description |
  30194. * | ----- | ----------------------------------- | ----------- |
  30195. * | 0 | EXPLICIT_MODE | |
  30196. * | 1 | SPHERICAL_MODE | |
  30197. * | 2 | PLANAR_MODE | |
  30198. * | 3 | CUBIC_MODE | |
  30199. * | 4 | PROJECTION_MODE | |
  30200. * | 5 | SKYBOX_MODE | |
  30201. * | 6 | INVCUBIC_MODE | |
  30202. * | 7 | EQUIRECTANGULAR_MODE | |
  30203. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30204. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30205. */
  30206. set: function (value) {
  30207. if (this._coordinatesMode === value) {
  30208. return;
  30209. }
  30210. this._coordinatesMode = value;
  30211. if (this._scene) {
  30212. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30213. }
  30214. },
  30215. enumerable: true,
  30216. configurable: true
  30217. });
  30218. Object.defineProperty(BaseTexture.prototype, "uid", {
  30219. get: function () {
  30220. if (!this._uid) {
  30221. this._uid = BABYLON.Tools.RandomId();
  30222. }
  30223. return this._uid;
  30224. },
  30225. enumerable: true,
  30226. configurable: true
  30227. });
  30228. BaseTexture.prototype.toString = function () {
  30229. return this.name;
  30230. };
  30231. BaseTexture.prototype.getClassName = function () {
  30232. return "BaseTexture";
  30233. };
  30234. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30235. set: function (callback) {
  30236. if (this._onDisposeObserver) {
  30237. this.onDisposeObservable.remove(this._onDisposeObserver);
  30238. }
  30239. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30240. },
  30241. enumerable: true,
  30242. configurable: true
  30243. });
  30244. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30245. get: function () {
  30246. return true;
  30247. },
  30248. enumerable: true,
  30249. configurable: true
  30250. });
  30251. BaseTexture.prototype.getScene = function () {
  30252. return this._scene;
  30253. };
  30254. BaseTexture.prototype.getTextureMatrix = function () {
  30255. return BABYLON.Matrix.IdentityReadOnly;
  30256. };
  30257. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30258. return BABYLON.Matrix.IdentityReadOnly;
  30259. };
  30260. BaseTexture.prototype.getInternalTexture = function () {
  30261. return this._texture;
  30262. };
  30263. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30264. return !this.isBlocking || this.isReady();
  30265. };
  30266. BaseTexture.prototype.isReady = function () {
  30267. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30268. this.delayLoad();
  30269. return false;
  30270. }
  30271. if (this._texture) {
  30272. return this._texture.isReady;
  30273. }
  30274. return false;
  30275. };
  30276. BaseTexture.prototype.getSize = function () {
  30277. if (this._texture && this._texture.width) {
  30278. return new BABYLON.Size(this._texture.width, this._texture.height);
  30279. }
  30280. if (this._texture && this._texture._size) {
  30281. return new BABYLON.Size(this._texture._size, this._texture._size);
  30282. }
  30283. return BABYLON.Size.Zero();
  30284. };
  30285. BaseTexture.prototype.getBaseSize = function () {
  30286. if (!this.isReady() || !this._texture)
  30287. return BABYLON.Size.Zero();
  30288. if (this._texture._size) {
  30289. return new BABYLON.Size(this._texture._size, this._texture._size);
  30290. }
  30291. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30292. };
  30293. BaseTexture.prototype.scale = function (ratio) {
  30294. };
  30295. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30296. get: function () {
  30297. return false;
  30298. },
  30299. enumerable: true,
  30300. configurable: true
  30301. });
  30302. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30303. if (!this._scene) {
  30304. return null;
  30305. }
  30306. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30307. for (var index = 0; index < texturesCache.length; index++) {
  30308. var texturesCacheEntry = texturesCache[index];
  30309. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30310. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30311. texturesCacheEntry.incrementReferences();
  30312. return texturesCacheEntry;
  30313. }
  30314. }
  30315. }
  30316. return null;
  30317. };
  30318. BaseTexture.prototype._rebuild = function () {
  30319. };
  30320. BaseTexture.prototype.delayLoad = function () {
  30321. };
  30322. BaseTexture.prototype.clone = function () {
  30323. return null;
  30324. };
  30325. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30326. get: function () {
  30327. if (!this._texture) {
  30328. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30329. }
  30330. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30331. },
  30332. enumerable: true,
  30333. configurable: true
  30334. });
  30335. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30336. get: function () {
  30337. if (!this._texture) {
  30338. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30339. }
  30340. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30341. },
  30342. enumerable: true,
  30343. configurable: true
  30344. });
  30345. BaseTexture.prototype.readPixels = function (faceIndex) {
  30346. if (faceIndex === void 0) { faceIndex = 0; }
  30347. if (!this._texture) {
  30348. return null;
  30349. }
  30350. var size = this.getSize();
  30351. var scene = this.getScene();
  30352. if (!scene) {
  30353. return null;
  30354. }
  30355. var engine = scene.getEngine();
  30356. if (this._texture.isCube) {
  30357. return engine._readTexturePixels(this._texture, size.width, size.height, faceIndex);
  30358. }
  30359. return engine._readTexturePixels(this._texture, size.width, size.height, -1);
  30360. };
  30361. BaseTexture.prototype.releaseInternalTexture = function () {
  30362. if (this._texture) {
  30363. this._texture.dispose();
  30364. this._texture = null;
  30365. }
  30366. };
  30367. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30368. get: function () {
  30369. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30370. return null;
  30371. }
  30372. if (!this._texture._sphericalPolynomial) {
  30373. this._texture._sphericalPolynomial =
  30374. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30375. }
  30376. return this._texture._sphericalPolynomial;
  30377. },
  30378. set: function (value) {
  30379. if (this._texture) {
  30380. this._texture._sphericalPolynomial = value;
  30381. }
  30382. },
  30383. enumerable: true,
  30384. configurable: true
  30385. });
  30386. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30387. get: function () {
  30388. if (this._texture) {
  30389. return this._texture._lodTextureHigh;
  30390. }
  30391. return null;
  30392. },
  30393. enumerable: true,
  30394. configurable: true
  30395. });
  30396. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30397. get: function () {
  30398. if (this._texture) {
  30399. return this._texture._lodTextureMid;
  30400. }
  30401. return null;
  30402. },
  30403. enumerable: true,
  30404. configurable: true
  30405. });
  30406. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30407. get: function () {
  30408. if (this._texture) {
  30409. return this._texture._lodTextureLow;
  30410. }
  30411. return null;
  30412. },
  30413. enumerable: true,
  30414. configurable: true
  30415. });
  30416. BaseTexture.prototype.dispose = function () {
  30417. if (!this._scene) {
  30418. return;
  30419. }
  30420. // Animations
  30421. this._scene.stopAnimation(this);
  30422. // Remove from scene
  30423. this._scene._removePendingData(this);
  30424. var index = this._scene.textures.indexOf(this);
  30425. if (index >= 0) {
  30426. this._scene.textures.splice(index, 1);
  30427. }
  30428. if (this._texture === undefined) {
  30429. return;
  30430. }
  30431. // Release
  30432. this.releaseInternalTexture();
  30433. // Callback
  30434. this.onDisposeObservable.notifyObservers(this);
  30435. this.onDisposeObservable.clear();
  30436. };
  30437. BaseTexture.prototype.serialize = function () {
  30438. if (!this.name) {
  30439. return null;
  30440. }
  30441. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30442. // Animations
  30443. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  30444. return serializationObject;
  30445. };
  30446. BaseTexture.WhenAllReady = function (textures, callback) {
  30447. var numRemaining = textures.length;
  30448. if (numRemaining === 0) {
  30449. callback();
  30450. return;
  30451. }
  30452. var _loop_1 = function () {
  30453. texture = textures[i];
  30454. if (texture.isReady()) {
  30455. if (--numRemaining === 0) {
  30456. callback();
  30457. }
  30458. }
  30459. else {
  30460. onLoadObservable = texture.onLoadObservable;
  30461. var onLoadCallback_1 = function () {
  30462. onLoadObservable.removeCallback(onLoadCallback_1);
  30463. if (--numRemaining === 0) {
  30464. callback();
  30465. }
  30466. };
  30467. onLoadObservable.add(onLoadCallback_1);
  30468. }
  30469. };
  30470. var texture, onLoadObservable;
  30471. for (var i = 0; i < textures.length; i++) {
  30472. _loop_1();
  30473. }
  30474. };
  30475. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  30476. __decorate([
  30477. BABYLON.serialize()
  30478. ], BaseTexture.prototype, "name", void 0);
  30479. __decorate([
  30480. BABYLON.serialize("hasAlpha")
  30481. ], BaseTexture.prototype, "_hasAlpha", void 0);
  30482. __decorate([
  30483. BABYLON.serialize()
  30484. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  30485. __decorate([
  30486. BABYLON.serialize()
  30487. ], BaseTexture.prototype, "level", void 0);
  30488. __decorate([
  30489. BABYLON.serialize()
  30490. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  30491. __decorate([
  30492. BABYLON.serialize("coordinatesMode")
  30493. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  30494. __decorate([
  30495. BABYLON.serialize()
  30496. ], BaseTexture.prototype, "wrapU", void 0);
  30497. __decorate([
  30498. BABYLON.serialize()
  30499. ], BaseTexture.prototype, "wrapV", void 0);
  30500. __decorate([
  30501. BABYLON.serialize()
  30502. ], BaseTexture.prototype, "wrapR", void 0);
  30503. __decorate([
  30504. BABYLON.serialize()
  30505. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  30506. __decorate([
  30507. BABYLON.serialize()
  30508. ], BaseTexture.prototype, "isCube", void 0);
  30509. __decorate([
  30510. BABYLON.serialize()
  30511. ], BaseTexture.prototype, "is3D", void 0);
  30512. __decorate([
  30513. BABYLON.serialize()
  30514. ], BaseTexture.prototype, "gammaSpace", void 0);
  30515. __decorate([
  30516. BABYLON.serialize()
  30517. ], BaseTexture.prototype, "invertZ", void 0);
  30518. __decorate([
  30519. BABYLON.serialize()
  30520. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  30521. __decorate([
  30522. BABYLON.serialize()
  30523. ], BaseTexture.prototype, "lodGenerationOffset", void 0);
  30524. __decorate([
  30525. BABYLON.serialize()
  30526. ], BaseTexture.prototype, "lodGenerationScale", void 0);
  30527. __decorate([
  30528. BABYLON.serialize()
  30529. ], BaseTexture.prototype, "isRenderTarget", void 0);
  30530. return BaseTexture;
  30531. }());
  30532. BABYLON.BaseTexture = BaseTexture;
  30533. })(BABYLON || (BABYLON = {}));
  30534. //# sourceMappingURL=babylon.baseTexture.js.map
  30535. var BABYLON;
  30536. (function (BABYLON) {
  30537. var Texture = /** @class */ (function (_super) {
  30538. __extends(Texture, _super);
  30539. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  30540. if (noMipmap === void 0) { noMipmap = false; }
  30541. if (invertY === void 0) { invertY = true; }
  30542. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30543. if (onLoad === void 0) { onLoad = null; }
  30544. if (onError === void 0) { onError = null; }
  30545. if (buffer === void 0) { buffer = null; }
  30546. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30547. var _this = _super.call(this, scene) || this;
  30548. _this.uOffset = 0;
  30549. _this.vOffset = 0;
  30550. _this.uScale = 1.0;
  30551. _this.vScale = 1.0;
  30552. _this.uAng = 0;
  30553. _this.vAng = 0;
  30554. _this.wAng = 0;
  30555. _this._isBlocking = true;
  30556. _this.name = url || "";
  30557. _this.url = url;
  30558. _this._noMipmap = noMipmap;
  30559. _this._invertY = invertY;
  30560. _this._samplingMode = samplingMode;
  30561. _this._buffer = buffer;
  30562. _this._deleteBuffer = deleteBuffer;
  30563. if (format) {
  30564. _this._format = format;
  30565. }
  30566. scene = _this.getScene();
  30567. if (!scene) {
  30568. return _this;
  30569. }
  30570. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  30571. var load = function () {
  30572. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  30573. _this.onLoadObservable.notifyObservers(_this);
  30574. }
  30575. if (onLoad) {
  30576. onLoad();
  30577. }
  30578. if (!_this.isBlocking && scene) {
  30579. scene.resetCachedMaterial();
  30580. }
  30581. };
  30582. if (!_this.url) {
  30583. _this._delayedOnLoad = load;
  30584. _this._delayedOnError = onError;
  30585. return _this;
  30586. }
  30587. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  30588. if (!_this._texture) {
  30589. if (!scene.useDelayedTextureLoading) {
  30590. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  30591. if (deleteBuffer) {
  30592. delete _this._buffer;
  30593. }
  30594. }
  30595. else {
  30596. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30597. _this._delayedOnLoad = load;
  30598. _this._delayedOnError = onError;
  30599. }
  30600. }
  30601. else {
  30602. if (_this._texture.isReady) {
  30603. BABYLON.Tools.SetImmediate(function () { return load(); });
  30604. }
  30605. else {
  30606. _this._texture.onLoadedObservable.add(load);
  30607. }
  30608. }
  30609. return _this;
  30610. }
  30611. Object.defineProperty(Texture.prototype, "noMipmap", {
  30612. get: function () {
  30613. return this._noMipmap;
  30614. },
  30615. enumerable: true,
  30616. configurable: true
  30617. });
  30618. Object.defineProperty(Texture.prototype, "isBlocking", {
  30619. get: function () {
  30620. return this._isBlocking;
  30621. },
  30622. set: function (value) {
  30623. this._isBlocking = value;
  30624. },
  30625. enumerable: true,
  30626. configurable: true
  30627. });
  30628. Object.defineProperty(Texture.prototype, "samplingMode", {
  30629. get: function () {
  30630. return this._samplingMode;
  30631. },
  30632. enumerable: true,
  30633. configurable: true
  30634. });
  30635. Texture.prototype.updateURL = function (url) {
  30636. this.url = url;
  30637. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  30638. this.delayLoad();
  30639. };
  30640. Texture.prototype.delayLoad = function () {
  30641. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30642. return;
  30643. }
  30644. var scene = this.getScene();
  30645. if (!scene) {
  30646. return;
  30647. }
  30648. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  30649. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  30650. if (!this._texture) {
  30651. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  30652. if (this._deleteBuffer) {
  30653. delete this._buffer;
  30654. }
  30655. }
  30656. else {
  30657. if (this._delayedOnLoad) {
  30658. if (this._texture.isReady) {
  30659. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  30660. }
  30661. else {
  30662. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  30663. }
  30664. }
  30665. }
  30666. this._delayedOnLoad = null;
  30667. this._delayedOnError = null;
  30668. };
  30669. Texture.prototype.updateSamplingMode = function (samplingMode) {
  30670. if (!this._texture) {
  30671. return;
  30672. }
  30673. var scene = this.getScene();
  30674. if (!scene) {
  30675. return;
  30676. }
  30677. this._samplingMode = samplingMode;
  30678. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  30679. };
  30680. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  30681. x *= this.uScale;
  30682. y *= this.vScale;
  30683. x -= 0.5 * this.uScale;
  30684. y -= 0.5 * this.vScale;
  30685. z -= 0.5;
  30686. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  30687. t.x += 0.5 * this.uScale + this.uOffset;
  30688. t.y += 0.5 * this.vScale + this.vOffset;
  30689. t.z += 0.5;
  30690. };
  30691. Texture.prototype.getTextureMatrix = function () {
  30692. var _this = this;
  30693. if (this.uOffset === this._cachedUOffset &&
  30694. this.vOffset === this._cachedVOffset &&
  30695. this.uScale === this._cachedUScale &&
  30696. this.vScale === this._cachedVScale &&
  30697. this.uAng === this._cachedUAng &&
  30698. this.vAng === this._cachedVAng &&
  30699. this.wAng === this._cachedWAng) {
  30700. return this._cachedTextureMatrix;
  30701. }
  30702. this._cachedUOffset = this.uOffset;
  30703. this._cachedVOffset = this.vOffset;
  30704. this._cachedUScale = this.uScale;
  30705. this._cachedVScale = this.vScale;
  30706. this._cachedUAng = this.uAng;
  30707. this._cachedVAng = this.vAng;
  30708. this._cachedWAng = this.wAng;
  30709. if (!this._cachedTextureMatrix) {
  30710. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30711. this._rowGenerationMatrix = new BABYLON.Matrix();
  30712. this._t0 = BABYLON.Vector3.Zero();
  30713. this._t1 = BABYLON.Vector3.Zero();
  30714. this._t2 = BABYLON.Vector3.Zero();
  30715. }
  30716. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  30717. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  30718. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  30719. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  30720. this._t1.subtractInPlace(this._t0);
  30721. this._t2.subtractInPlace(this._t0);
  30722. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30723. this._cachedTextureMatrix.m[0] = this._t1.x;
  30724. this._cachedTextureMatrix.m[1] = this._t1.y;
  30725. this._cachedTextureMatrix.m[2] = this._t1.z;
  30726. this._cachedTextureMatrix.m[4] = this._t2.x;
  30727. this._cachedTextureMatrix.m[5] = this._t2.y;
  30728. this._cachedTextureMatrix.m[6] = this._t2.z;
  30729. this._cachedTextureMatrix.m[8] = this._t0.x;
  30730. this._cachedTextureMatrix.m[9] = this._t0.y;
  30731. this._cachedTextureMatrix.m[10] = this._t0.z;
  30732. var scene = this.getScene();
  30733. if (!scene) {
  30734. return this._cachedTextureMatrix;
  30735. }
  30736. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30737. return mat.hasTexture(_this);
  30738. });
  30739. return this._cachedTextureMatrix;
  30740. };
  30741. Texture.prototype.getReflectionTextureMatrix = function () {
  30742. var _this = this;
  30743. var scene = this.getScene();
  30744. if (!scene) {
  30745. return this._cachedTextureMatrix;
  30746. }
  30747. if (this.uOffset === this._cachedUOffset &&
  30748. this.vOffset === this._cachedVOffset &&
  30749. this.uScale === this._cachedUScale &&
  30750. this.vScale === this._cachedVScale &&
  30751. this.coordinatesMode === this._cachedCoordinatesMode) {
  30752. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  30753. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  30754. return this._cachedTextureMatrix;
  30755. }
  30756. }
  30757. else {
  30758. return this._cachedTextureMatrix;
  30759. }
  30760. }
  30761. if (!this._cachedTextureMatrix) {
  30762. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  30763. }
  30764. if (!this._projectionModeMatrix) {
  30765. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  30766. }
  30767. this._cachedUOffset = this.uOffset;
  30768. this._cachedVOffset = this.vOffset;
  30769. this._cachedUScale = this.uScale;
  30770. this._cachedVScale = this.vScale;
  30771. this._cachedCoordinatesMode = this.coordinatesMode;
  30772. switch (this.coordinatesMode) {
  30773. case Texture.PLANAR_MODE:
  30774. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30775. this._cachedTextureMatrix[0] = this.uScale;
  30776. this._cachedTextureMatrix[5] = this.vScale;
  30777. this._cachedTextureMatrix[12] = this.uOffset;
  30778. this._cachedTextureMatrix[13] = this.vOffset;
  30779. break;
  30780. case Texture.PROJECTION_MODE:
  30781. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  30782. this._projectionModeMatrix.m[0] = 0.5;
  30783. this._projectionModeMatrix.m[5] = -0.5;
  30784. this._projectionModeMatrix.m[10] = 0.0;
  30785. this._projectionModeMatrix.m[12] = 0.5;
  30786. this._projectionModeMatrix.m[13] = 0.5;
  30787. this._projectionModeMatrix.m[14] = 1.0;
  30788. this._projectionModeMatrix.m[15] = 1.0;
  30789. var projectionMatrix = scene.getProjectionMatrix();
  30790. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  30791. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  30792. break;
  30793. default:
  30794. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  30795. break;
  30796. }
  30797. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  30798. return (mat.getActiveTextures().indexOf(_this) !== -1);
  30799. });
  30800. return this._cachedTextureMatrix;
  30801. };
  30802. Texture.prototype.clone = function () {
  30803. var _this = this;
  30804. return BABYLON.SerializationHelper.Clone(function () {
  30805. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  30806. }, this);
  30807. };
  30808. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  30809. get: function () {
  30810. if (!this._onLoadObservable) {
  30811. this._onLoadObservable = new BABYLON.Observable();
  30812. }
  30813. return this._onLoadObservable;
  30814. },
  30815. enumerable: true,
  30816. configurable: true
  30817. });
  30818. Texture.prototype.serialize = function () {
  30819. var serializationObject = _super.prototype.serialize.call(this);
  30820. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  30821. serializationObject.base64String = this._buffer;
  30822. serializationObject.name = serializationObject.name.replace("data:", "");
  30823. }
  30824. serializationObject.invertY = this._invertY;
  30825. serializationObject.samplingMode = this.samplingMode;
  30826. return serializationObject;
  30827. };
  30828. Texture.prototype.getClassName = function () {
  30829. return "Texture";
  30830. };
  30831. Texture.prototype.dispose = function () {
  30832. _super.prototype.dispose.call(this);
  30833. if (this.onLoadObservable) {
  30834. this.onLoadObservable.clear();
  30835. this._onLoadObservable = null;
  30836. }
  30837. this._delayedOnLoad = null;
  30838. this._delayedOnError = null;
  30839. };
  30840. // Statics
  30841. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30842. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30843. if (onLoad === void 0) { onLoad = null; }
  30844. if (onError === void 0) { onError = null; }
  30845. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30846. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  30847. };
  30848. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  30849. if (parsedTexture.customType) {
  30850. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  30851. // Update Sampling Mode
  30852. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  30853. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  30854. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  30855. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  30856. }
  30857. }
  30858. return parsedCustomTexture;
  30859. }
  30860. if (parsedTexture.isCube) {
  30861. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  30862. }
  30863. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  30864. return null;
  30865. }
  30866. var texture = BABYLON.SerializationHelper.Parse(function () {
  30867. var generateMipMaps = true;
  30868. if (parsedTexture.noMipmap) {
  30869. generateMipMaps = false;
  30870. }
  30871. if (parsedTexture.mirrorPlane) {
  30872. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30873. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  30874. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  30875. return mirrorTexture;
  30876. }
  30877. else if (parsedTexture.isRenderTarget) {
  30878. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  30879. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  30880. return renderTargetTexture;
  30881. }
  30882. else {
  30883. var texture;
  30884. if (parsedTexture.base64String) {
  30885. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  30886. }
  30887. else {
  30888. var url = rootUrl + parsedTexture.name;
  30889. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  30890. url = parsedTexture.url;
  30891. }
  30892. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  30893. }
  30894. return texture;
  30895. }
  30896. }, parsedTexture, scene);
  30897. // Update Sampling Mode
  30898. if (parsedTexture.samplingMode) {
  30899. var sampling = parsedTexture.samplingMode;
  30900. if (texture._samplingMode !== sampling) {
  30901. texture.updateSamplingMode(sampling);
  30902. }
  30903. }
  30904. // Animations
  30905. if (parsedTexture.animations) {
  30906. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  30907. var parsedAnimation = parsedTexture.animations[animationIndex];
  30908. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  30909. }
  30910. }
  30911. return texture;
  30912. };
  30913. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  30914. if (deleteBuffer === void 0) { deleteBuffer = false; }
  30915. if (noMipmap === void 0) { noMipmap = false; }
  30916. if (invertY === void 0) { invertY = true; }
  30917. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  30918. if (onLoad === void 0) { onLoad = null; }
  30919. if (onError === void 0) { onError = null; }
  30920. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  30921. if (name.substr(0, 5) !== "data:") {
  30922. name = "data:" + name;
  30923. }
  30924. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  30925. };
  30926. // Constants
  30927. Texture.NEAREST_SAMPLINGMODE = 1;
  30928. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  30929. Texture.BILINEAR_SAMPLINGMODE = 2;
  30930. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  30931. Texture.TRILINEAR_SAMPLINGMODE = 3;
  30932. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  30933. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  30934. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  30935. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  30936. Texture.NEAREST_LINEAR = 7;
  30937. Texture.NEAREST_NEAREST = 8;
  30938. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  30939. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  30940. Texture.LINEAR_LINEAR = 11;
  30941. Texture.LINEAR_NEAREST = 12;
  30942. Texture.EXPLICIT_MODE = 0;
  30943. Texture.SPHERICAL_MODE = 1;
  30944. Texture.PLANAR_MODE = 2;
  30945. Texture.CUBIC_MODE = 3;
  30946. Texture.PROJECTION_MODE = 4;
  30947. Texture.SKYBOX_MODE = 5;
  30948. Texture.INVCUBIC_MODE = 6;
  30949. Texture.EQUIRECTANGULAR_MODE = 7;
  30950. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  30951. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  30952. Texture.CLAMP_ADDRESSMODE = 0;
  30953. Texture.WRAP_ADDRESSMODE = 1;
  30954. Texture.MIRROR_ADDRESSMODE = 2;
  30955. /**
  30956. * 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
  30957. */
  30958. Texture.UseSerializedUrlIfAny = false;
  30959. __decorate([
  30960. BABYLON.serialize()
  30961. ], Texture.prototype, "url", void 0);
  30962. __decorate([
  30963. BABYLON.serialize()
  30964. ], Texture.prototype, "uOffset", void 0);
  30965. __decorate([
  30966. BABYLON.serialize()
  30967. ], Texture.prototype, "vOffset", void 0);
  30968. __decorate([
  30969. BABYLON.serialize()
  30970. ], Texture.prototype, "uScale", void 0);
  30971. __decorate([
  30972. BABYLON.serialize()
  30973. ], Texture.prototype, "vScale", void 0);
  30974. __decorate([
  30975. BABYLON.serialize()
  30976. ], Texture.prototype, "uAng", void 0);
  30977. __decorate([
  30978. BABYLON.serialize()
  30979. ], Texture.prototype, "vAng", void 0);
  30980. __decorate([
  30981. BABYLON.serialize()
  30982. ], Texture.prototype, "wAng", void 0);
  30983. __decorate([
  30984. BABYLON.serialize()
  30985. ], Texture.prototype, "isBlocking", null);
  30986. return Texture;
  30987. }(BABYLON.BaseTexture));
  30988. BABYLON.Texture = Texture;
  30989. })(BABYLON || (BABYLON = {}));
  30990. //# sourceMappingURL=babylon.texture.js.map
  30991. var BABYLON;
  30992. (function (BABYLON) {
  30993. /**
  30994. * @hidden
  30995. **/
  30996. var _InstancesBatch = /** @class */ (function () {
  30997. function _InstancesBatch() {
  30998. this.mustReturn = false;
  30999. this.visibleInstances = new Array();
  31000. this.renderSelf = new Array();
  31001. }
  31002. return _InstancesBatch;
  31003. }());
  31004. BABYLON._InstancesBatch = _InstancesBatch;
  31005. var Mesh = /** @class */ (function (_super) {
  31006. __extends(Mesh, _super);
  31007. /**
  31008. * @constructor
  31009. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31010. * @param {Scene} scene The scene to add this mesh to.
  31011. * @param {Node} parent The parent of this mesh, if it has one
  31012. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31013. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31014. * When false, achieved by calling a clone(), also passing False.
  31015. * This will make creation of children, recursive.
  31016. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31017. */
  31018. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31019. if (scene === void 0) { scene = null; }
  31020. if (parent === void 0) { parent = null; }
  31021. if (source === void 0) { source = null; }
  31022. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31023. var _this = _super.call(this, name, scene) || this;
  31024. // Events
  31025. /**
  31026. * An event triggered before rendering the mesh
  31027. */
  31028. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31029. /**
  31030. * An event triggered after rendering the mesh
  31031. */
  31032. _this.onAfterRenderObservable = new BABYLON.Observable();
  31033. /**
  31034. * An event triggered before drawing the mesh
  31035. */
  31036. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31037. // Members
  31038. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31039. _this.instances = new Array();
  31040. _this._LODLevels = new Array();
  31041. _this._visibleInstances = {};
  31042. _this._renderIdForInstances = new Array();
  31043. _this._batchCache = new _InstancesBatch();
  31044. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31045. // Use by builder only to know what orientation were the mesh build in.
  31046. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31047. _this.overrideMaterialSideOrientation = null;
  31048. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31049. // Will be used to save a source mesh reference, If any
  31050. _this._source = null;
  31051. scene = _this.getScene();
  31052. if (source) {
  31053. // Source mesh
  31054. _this._source = source;
  31055. // Geometry
  31056. if (source._geometry) {
  31057. source._geometry.applyToMesh(_this);
  31058. }
  31059. // Deep copy
  31060. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31061. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix", "_source"]);
  31062. // Metadata
  31063. if (source.metadata && source.metadata.clone) {
  31064. _this.metadata = source.metadata.clone();
  31065. }
  31066. else {
  31067. _this.metadata = source.metadata;
  31068. }
  31069. // Tags
  31070. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31071. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31072. }
  31073. // Parent
  31074. _this.parent = source.parent;
  31075. // Pivot
  31076. _this.setPivotMatrix(source.getPivotMatrix());
  31077. _this.id = name + "." + source.id;
  31078. // Material
  31079. _this.material = source.material;
  31080. var index;
  31081. if (!doNotCloneChildren) {
  31082. // Children
  31083. var directDescendants = source.getDescendants(true);
  31084. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31085. var child = directDescendants[index_1];
  31086. if (child.clone) {
  31087. child.clone(name + "." + child.name, _this);
  31088. }
  31089. }
  31090. }
  31091. // Physics clone
  31092. var physicsEngine = _this.getScene().getPhysicsEngine();
  31093. if (clonePhysicsImpostor && physicsEngine) {
  31094. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31095. if (impostor) {
  31096. _this.physicsImpostor = impostor.clone(_this);
  31097. }
  31098. }
  31099. // Particles
  31100. for (index = 0; index < scene.particleSystems.length; index++) {
  31101. var system = scene.particleSystems[index];
  31102. if (system.emitter === source) {
  31103. system.clone(system.name, _this);
  31104. }
  31105. }
  31106. _this.computeWorldMatrix(true);
  31107. }
  31108. // Parent
  31109. if (parent !== null) {
  31110. _this.parent = parent;
  31111. }
  31112. return _this;
  31113. }
  31114. Object.defineProperty(Mesh, "FRONTSIDE", {
  31115. /**
  31116. * Mesh side orientation : usually the external or front surface
  31117. */
  31118. get: function () {
  31119. return Mesh._FRONTSIDE;
  31120. },
  31121. enumerable: true,
  31122. configurable: true
  31123. });
  31124. Object.defineProperty(Mesh, "BACKSIDE", {
  31125. /**
  31126. * Mesh side orientation : usually the internal or back surface
  31127. */
  31128. get: function () {
  31129. return Mesh._BACKSIDE;
  31130. },
  31131. enumerable: true,
  31132. configurable: true
  31133. });
  31134. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31135. /**
  31136. * Mesh side orientation : both internal and external or front and back surfaces
  31137. */
  31138. get: function () {
  31139. return Mesh._DOUBLESIDE;
  31140. },
  31141. enumerable: true,
  31142. configurable: true
  31143. });
  31144. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31145. /**
  31146. * Mesh side orientation : by default, `FRONTSIDE`
  31147. */
  31148. get: function () {
  31149. return Mesh._DEFAULTSIDE;
  31150. },
  31151. enumerable: true,
  31152. configurable: true
  31153. });
  31154. Object.defineProperty(Mesh, "NO_CAP", {
  31155. /**
  31156. * Mesh cap setting : no cap
  31157. */
  31158. get: function () {
  31159. return Mesh._NO_CAP;
  31160. },
  31161. enumerable: true,
  31162. configurable: true
  31163. });
  31164. Object.defineProperty(Mesh, "CAP_START", {
  31165. /**
  31166. * Mesh cap setting : one cap at the beginning of the mesh
  31167. */
  31168. get: function () {
  31169. return Mesh._CAP_START;
  31170. },
  31171. enumerable: true,
  31172. configurable: true
  31173. });
  31174. Object.defineProperty(Mesh, "CAP_END", {
  31175. /**
  31176. * Mesh cap setting : one cap at the end of the mesh
  31177. */
  31178. get: function () {
  31179. return Mesh._CAP_END;
  31180. },
  31181. enumerable: true,
  31182. configurable: true
  31183. });
  31184. Object.defineProperty(Mesh, "CAP_ALL", {
  31185. /**
  31186. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31187. */
  31188. get: function () {
  31189. return Mesh._CAP_ALL;
  31190. },
  31191. enumerable: true,
  31192. configurable: true
  31193. });
  31194. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31195. set: function (callback) {
  31196. if (this._onBeforeDrawObserver) {
  31197. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31198. }
  31199. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31205. get: function () {
  31206. return this._morphTargetManager;
  31207. },
  31208. set: function (value) {
  31209. if (this._morphTargetManager === value) {
  31210. return;
  31211. }
  31212. this._morphTargetManager = value;
  31213. this._syncGeometryWithMorphTargetManager();
  31214. },
  31215. enumerable: true,
  31216. configurable: true
  31217. });
  31218. Object.defineProperty(Mesh.prototype, "source", {
  31219. get: function () {
  31220. return this._source;
  31221. },
  31222. enumerable: true,
  31223. configurable: true
  31224. });
  31225. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31226. get: function () {
  31227. return this._unIndexed;
  31228. },
  31229. set: function (value) {
  31230. if (this._unIndexed !== value) {
  31231. this._unIndexed = value;
  31232. this._markSubMeshesAsAttributesDirty();
  31233. }
  31234. },
  31235. enumerable: true,
  31236. configurable: true
  31237. });
  31238. // Methods
  31239. /**
  31240. * Returns the string "Mesh".
  31241. */
  31242. Mesh.prototype.getClassName = function () {
  31243. return "Mesh";
  31244. };
  31245. /**
  31246. * Returns a string.
  31247. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31248. */
  31249. Mesh.prototype.toString = function (fullDetails) {
  31250. var ret = _super.prototype.toString.call(this, fullDetails);
  31251. ret += ", n vertices: " + this.getTotalVertices();
  31252. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31253. if (this.animations) {
  31254. for (var i = 0; i < this.animations.length; i++) {
  31255. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31256. }
  31257. }
  31258. if (fullDetails) {
  31259. if (this._geometry) {
  31260. var ib = this.getIndices();
  31261. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31262. if (vb && ib) {
  31263. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31264. }
  31265. }
  31266. else {
  31267. ret += ", flat shading: UNKNOWN";
  31268. }
  31269. }
  31270. return ret;
  31271. };
  31272. Mesh.prototype._unBindEffect = function () {
  31273. _super.prototype._unBindEffect.call(this);
  31274. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31275. var instance = _a[_i];
  31276. instance._unBindEffect();
  31277. }
  31278. };
  31279. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31280. /**
  31281. * True if the mesh has some Levels Of Details (LOD).
  31282. * Returns a boolean.
  31283. */
  31284. get: function () {
  31285. return this._LODLevels.length > 0;
  31286. },
  31287. enumerable: true,
  31288. configurable: true
  31289. });
  31290. /**
  31291. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31292. * @returns an array of {BABYLON.MeshLODLevel}
  31293. */
  31294. Mesh.prototype.getLODLevels = function () {
  31295. return this._LODLevels;
  31296. };
  31297. Mesh.prototype._sortLODLevels = function () {
  31298. this._LODLevels.sort(function (a, b) {
  31299. if (a.distance < b.distance) {
  31300. return 1;
  31301. }
  31302. if (a.distance > b.distance) {
  31303. return -1;
  31304. }
  31305. return 0;
  31306. });
  31307. };
  31308. /**
  31309. * Add a mesh as LOD level triggered at the given distance.
  31310. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31311. * @param {number} distance The distance from the center of the object to show this level
  31312. * @param {Mesh} mesh The mesh to be added as LOD level
  31313. * @return {Mesh} This mesh (for chaining)
  31314. */
  31315. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31316. if (mesh && mesh._masterMesh) {
  31317. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31318. return this;
  31319. }
  31320. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31321. this._LODLevels.push(level);
  31322. if (mesh) {
  31323. mesh._masterMesh = this;
  31324. }
  31325. this._sortLODLevels();
  31326. return this;
  31327. };
  31328. /**
  31329. * Returns the LOD level mesh at the passed distance or null if not found.
  31330. * It is related to the method `addLODLevel(distance, mesh)`.
  31331. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31332. * Returns an object Mesh or `null`.
  31333. */
  31334. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31335. for (var index = 0; index < this._LODLevels.length; index++) {
  31336. var level = this._LODLevels[index];
  31337. if (level.distance === distance) {
  31338. return level.mesh;
  31339. }
  31340. }
  31341. return null;
  31342. };
  31343. /**
  31344. * Remove a mesh from the LOD array
  31345. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31346. * @param {Mesh} mesh The mesh to be removed.
  31347. * @return {Mesh} This mesh (for chaining)
  31348. */
  31349. Mesh.prototype.removeLODLevel = function (mesh) {
  31350. for (var index = 0; index < this._LODLevels.length; index++) {
  31351. if (this._LODLevels[index].mesh === mesh) {
  31352. this._LODLevels.splice(index, 1);
  31353. if (mesh) {
  31354. mesh._masterMesh = null;
  31355. }
  31356. }
  31357. }
  31358. this._sortLODLevels();
  31359. return this;
  31360. };
  31361. /**
  31362. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31363. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31364. */
  31365. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31366. if (!this._LODLevels || this._LODLevels.length === 0) {
  31367. return this;
  31368. }
  31369. var bSphere;
  31370. if (boundingSphere) {
  31371. bSphere = boundingSphere;
  31372. }
  31373. else {
  31374. var boundingInfo = this.getBoundingInfo();
  31375. bSphere = boundingInfo.boundingSphere;
  31376. }
  31377. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31378. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31379. if (this.onLODLevelSelection) {
  31380. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31381. }
  31382. return this;
  31383. }
  31384. for (var index = 0; index < this._LODLevels.length; index++) {
  31385. var level = this._LODLevels[index];
  31386. if (level.distance < distanceToCamera) {
  31387. if (level.mesh) {
  31388. level.mesh._preActivate();
  31389. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31390. }
  31391. if (this.onLODLevelSelection) {
  31392. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31393. }
  31394. return level.mesh;
  31395. }
  31396. }
  31397. if (this.onLODLevelSelection) {
  31398. this.onLODLevelSelection(distanceToCamera, this, this);
  31399. }
  31400. return this;
  31401. };
  31402. Object.defineProperty(Mesh.prototype, "geometry", {
  31403. /**
  31404. * Returns the mesh internal Geometry object.
  31405. */
  31406. get: function () {
  31407. return this._geometry;
  31408. },
  31409. enumerable: true,
  31410. configurable: true
  31411. });
  31412. /**
  31413. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  31414. */
  31415. Mesh.prototype.getTotalVertices = function () {
  31416. if (this._geometry === null || this._geometry === undefined) {
  31417. return 0;
  31418. }
  31419. return this._geometry.getTotalVertices();
  31420. };
  31421. /**
  31422. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  31423. * 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.
  31424. * You can force the copy with forceCopy === true
  31425. * Returns null if the mesh has no geometry or no vertex buffer.
  31426. * Possible `kind` values :
  31427. * - BABYLON.VertexBuffer.PositionKind
  31428. * - BABYLON.VertexBuffer.UVKind
  31429. * - BABYLON.VertexBuffer.UV2Kind
  31430. * - BABYLON.VertexBuffer.UV3Kind
  31431. * - BABYLON.VertexBuffer.UV4Kind
  31432. * - BABYLON.VertexBuffer.UV5Kind
  31433. * - BABYLON.VertexBuffer.UV6Kind
  31434. * - BABYLON.VertexBuffer.ColorKind
  31435. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31436. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31437. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31438. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31439. */
  31440. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  31441. if (!this._geometry) {
  31442. return null;
  31443. }
  31444. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  31445. };
  31446. /**
  31447. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  31448. * Returns `null` if the mesh has no geometry.
  31449. * Possible `kind` values :
  31450. * - BABYLON.VertexBuffer.PositionKind
  31451. * - BABYLON.VertexBuffer.UVKind
  31452. * - BABYLON.VertexBuffer.UV2Kind
  31453. * - BABYLON.VertexBuffer.UV3Kind
  31454. * - BABYLON.VertexBuffer.UV4Kind
  31455. * - BABYLON.VertexBuffer.UV5Kind
  31456. * - BABYLON.VertexBuffer.UV6Kind
  31457. * - BABYLON.VertexBuffer.ColorKind
  31458. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31459. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31460. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31461. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31462. */
  31463. Mesh.prototype.getVertexBuffer = function (kind) {
  31464. if (!this._geometry) {
  31465. return null;
  31466. }
  31467. return this._geometry.getVertexBuffer(kind);
  31468. };
  31469. Mesh.prototype.isVerticesDataPresent = function (kind) {
  31470. if (!this._geometry) {
  31471. if (this._delayInfo) {
  31472. return this._delayInfo.indexOf(kind) !== -1;
  31473. }
  31474. return false;
  31475. }
  31476. return this._geometry.isVerticesDataPresent(kind);
  31477. };
  31478. /**
  31479. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  31480. * Possible `kind` values :
  31481. * - BABYLON.VertexBuffer.PositionKind
  31482. * - BABYLON.VertexBuffer.UVKind
  31483. * - BABYLON.VertexBuffer.UV2Kind
  31484. * - BABYLON.VertexBuffer.UV3Kind
  31485. * - BABYLON.VertexBuffer.UV4Kind
  31486. * - BABYLON.VertexBuffer.UV5Kind
  31487. * - BABYLON.VertexBuffer.UV6Kind
  31488. * - BABYLON.VertexBuffer.ColorKind
  31489. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31490. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31491. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31492. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31493. */
  31494. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  31495. if (!this._geometry) {
  31496. if (this._delayInfo) {
  31497. return this._delayInfo.indexOf(kind) !== -1;
  31498. }
  31499. return false;
  31500. }
  31501. return this._geometry.isVertexBufferUpdatable(kind);
  31502. };
  31503. /**
  31504. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  31505. * Possible `kind` values :
  31506. * - BABYLON.VertexBuffer.PositionKind
  31507. * - BABYLON.VertexBuffer.UVKind
  31508. * - BABYLON.VertexBuffer.UV2Kind
  31509. * - BABYLON.VertexBuffer.UV3Kind
  31510. * - BABYLON.VertexBuffer.UV4Kind
  31511. * - BABYLON.VertexBuffer.UV5Kind
  31512. * - BABYLON.VertexBuffer.UV6Kind
  31513. * - BABYLON.VertexBuffer.ColorKind
  31514. * - BABYLON.VertexBuffer.MatricesIndicesKind
  31515. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  31516. * - BABYLON.VertexBuffer.MatricesWeightsKind
  31517. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  31518. */
  31519. Mesh.prototype.getVerticesDataKinds = function () {
  31520. if (!this._geometry) {
  31521. var result = new Array();
  31522. if (this._delayInfo) {
  31523. this._delayInfo.forEach(function (kind, index, array) {
  31524. result.push(kind);
  31525. });
  31526. }
  31527. return result;
  31528. }
  31529. return this._geometry.getVerticesDataKinds();
  31530. };
  31531. /**
  31532. * Returns a positive integer : the total number of indices in this mesh geometry.
  31533. * Returns zero if the mesh has no geometry.
  31534. */
  31535. Mesh.prototype.getTotalIndices = function () {
  31536. if (!this._geometry) {
  31537. return 0;
  31538. }
  31539. return this._geometry.getTotalIndices();
  31540. };
  31541. /**
  31542. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  31543. * 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.
  31544. * Returns an empty array if the mesh has no geometry.
  31545. */
  31546. Mesh.prototype.getIndices = function (copyWhenShared) {
  31547. if (!this._geometry) {
  31548. return [];
  31549. }
  31550. return this._geometry.getIndices(copyWhenShared);
  31551. };
  31552. Object.defineProperty(Mesh.prototype, "isBlocked", {
  31553. get: function () {
  31554. return this._masterMesh !== null && this._masterMesh !== undefined;
  31555. },
  31556. enumerable: true,
  31557. configurable: true
  31558. });
  31559. /**
  31560. * Determine if the current mesh is ready to be rendered
  31561. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  31562. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  31563. * @returns true if all associated assets are ready (material, textures, shaders)
  31564. */
  31565. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  31566. if (completeCheck === void 0) { completeCheck = false; }
  31567. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  31568. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  31569. return false;
  31570. }
  31571. if (!_super.prototype.isReady.call(this, completeCheck)) {
  31572. return false;
  31573. }
  31574. if (!this.subMeshes || this.subMeshes.length === 0) {
  31575. return true;
  31576. }
  31577. if (!completeCheck) {
  31578. return true;
  31579. }
  31580. var engine = this.getEngine();
  31581. var scene = this.getScene();
  31582. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  31583. this.computeWorldMatrix();
  31584. var mat = this.material || scene.defaultMaterial;
  31585. if (mat) {
  31586. if (mat.storeEffectOnSubMeshes) {
  31587. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31588. var subMesh = _a[_i];
  31589. var effectiveMaterial = subMesh.getMaterial();
  31590. if (effectiveMaterial) {
  31591. if (effectiveMaterial.storeEffectOnSubMeshes) {
  31592. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  31593. return false;
  31594. }
  31595. }
  31596. else {
  31597. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  31598. return false;
  31599. }
  31600. }
  31601. }
  31602. }
  31603. }
  31604. else {
  31605. if (!mat.isReady(this, hardwareInstancedRendering)) {
  31606. return false;
  31607. }
  31608. }
  31609. }
  31610. // Shadows
  31611. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  31612. var light = _c[_b];
  31613. var generator = light.getShadowGenerator();
  31614. if (generator) {
  31615. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  31616. var subMesh = _e[_d];
  31617. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  31618. return false;
  31619. }
  31620. }
  31621. }
  31622. }
  31623. // LOD
  31624. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  31625. var lod = _g[_f];
  31626. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  31627. return false;
  31628. }
  31629. }
  31630. return true;
  31631. };
  31632. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  31633. /**
  31634. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  31635. * This property is pertinent only for updatable parametric shapes.
  31636. */
  31637. get: function () {
  31638. return this._areNormalsFrozen;
  31639. },
  31640. enumerable: true,
  31641. configurable: true
  31642. });
  31643. /**
  31644. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31645. * It has no effect at all on other shapes.
  31646. * It prevents the mesh normals from being recomputed on next `positions` array update.
  31647. * Returns the Mesh.
  31648. */
  31649. Mesh.prototype.freezeNormals = function () {
  31650. this._areNormalsFrozen = true;
  31651. return this;
  31652. };
  31653. /**
  31654. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  31655. * It has no effect at all on other shapes.
  31656. * It reactivates the mesh normals computation if it was previously frozen.
  31657. * Returns the Mesh.
  31658. */
  31659. Mesh.prototype.unfreezeNormals = function () {
  31660. this._areNormalsFrozen = false;
  31661. return this;
  31662. };
  31663. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  31664. /**
  31665. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  31666. */
  31667. set: function (count) {
  31668. this._overridenInstanceCount = count;
  31669. },
  31670. enumerable: true,
  31671. configurable: true
  31672. });
  31673. // Methods
  31674. Mesh.prototype._preActivate = function () {
  31675. var sceneRenderId = this.getScene().getRenderId();
  31676. if (this._preActivateId === sceneRenderId) {
  31677. return this;
  31678. }
  31679. this._preActivateId = sceneRenderId;
  31680. this._visibleInstances = null;
  31681. return this;
  31682. };
  31683. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  31684. if (this._visibleInstances) {
  31685. this._visibleInstances.intermediateDefaultRenderId = renderId;
  31686. }
  31687. return this;
  31688. };
  31689. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  31690. if (!this._visibleInstances) {
  31691. this._visibleInstances = {};
  31692. this._visibleInstances.defaultRenderId = renderId;
  31693. this._visibleInstances.selfDefaultRenderId = this._renderId;
  31694. }
  31695. if (!this._visibleInstances[renderId]) {
  31696. this._visibleInstances[renderId] = new Array();
  31697. }
  31698. this._visibleInstances[renderId].push(instance);
  31699. return this;
  31700. };
  31701. /**
  31702. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  31703. * This means the mesh underlying bounding box and sphere are recomputed.
  31704. * Returns the Mesh.
  31705. */
  31706. Mesh.prototype.refreshBoundingInfo = function () {
  31707. return this._refreshBoundingInfo(false);
  31708. };
  31709. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  31710. if (this._boundingInfo && this._boundingInfo.isLocked) {
  31711. return this;
  31712. }
  31713. var data = this._getPositionData(applySkeleton);
  31714. if (data) {
  31715. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  31716. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  31717. }
  31718. if (this.subMeshes) {
  31719. for (var index = 0; index < this.subMeshes.length; index++) {
  31720. this.subMeshes[index].refreshBoundingInfo();
  31721. }
  31722. }
  31723. this._updateBoundingInfo();
  31724. return this;
  31725. };
  31726. Mesh.prototype._getPositionData = function (applySkeleton) {
  31727. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31728. if (data && applySkeleton && this.skeleton) {
  31729. data = BABYLON.Tools.Slice(data);
  31730. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  31731. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  31732. if (matricesWeightsData && matricesIndicesData) {
  31733. var needExtras = this.numBoneInfluencers > 4;
  31734. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  31735. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  31736. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  31737. var tempVector = BABYLON.Tmp.Vector3[0];
  31738. var finalMatrix = BABYLON.Tmp.Matrix[0];
  31739. var tempMatrix = BABYLON.Tmp.Matrix[1];
  31740. var matWeightIdx = 0;
  31741. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  31742. finalMatrix.reset();
  31743. var inf;
  31744. var weight;
  31745. for (inf = 0; inf < 4; inf++) {
  31746. weight = matricesWeightsData[matWeightIdx + inf];
  31747. if (weight <= 0)
  31748. break;
  31749. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31750. finalMatrix.addToSelf(tempMatrix);
  31751. }
  31752. if (needExtras) {
  31753. for (inf = 0; inf < 4; inf++) {
  31754. weight = matricesWeightsExtraData[matWeightIdx + inf];
  31755. if (weight <= 0)
  31756. break;
  31757. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  31758. finalMatrix.addToSelf(tempMatrix);
  31759. }
  31760. }
  31761. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  31762. tempVector.toArray(data, index);
  31763. }
  31764. }
  31765. }
  31766. return data;
  31767. };
  31768. Mesh.prototype._createGlobalSubMesh = function (force) {
  31769. var totalVertices = this.getTotalVertices();
  31770. if (!totalVertices || !this.getIndices()) {
  31771. return null;
  31772. }
  31773. // Check if we need to recreate the submeshes
  31774. if (this.subMeshes && this.subMeshes.length > 0) {
  31775. var ib = this.getIndices();
  31776. if (!ib) {
  31777. return null;
  31778. }
  31779. var totalIndices = ib.length;
  31780. var needToRecreate = false;
  31781. if (force) {
  31782. needToRecreate = true;
  31783. }
  31784. else {
  31785. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  31786. var submesh = _a[_i];
  31787. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  31788. needToRecreate = true;
  31789. break;
  31790. }
  31791. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  31792. needToRecreate = true;
  31793. break;
  31794. }
  31795. }
  31796. }
  31797. if (!needToRecreate) {
  31798. return this.subMeshes[0];
  31799. }
  31800. }
  31801. this.releaseSubMeshes();
  31802. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  31803. };
  31804. Mesh.prototype.subdivide = function (count) {
  31805. if (count < 1) {
  31806. return;
  31807. }
  31808. var totalIndices = this.getTotalIndices();
  31809. var subdivisionSize = (totalIndices / count) | 0;
  31810. var offset = 0;
  31811. // Ensure that subdivisionSize is a multiple of 3
  31812. while (subdivisionSize % 3 !== 0) {
  31813. subdivisionSize++;
  31814. }
  31815. this.releaseSubMeshes();
  31816. for (var index = 0; index < count; index++) {
  31817. if (offset >= totalIndices) {
  31818. break;
  31819. }
  31820. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  31821. offset += subdivisionSize;
  31822. }
  31823. this.synchronizeInstances();
  31824. };
  31825. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  31826. if (updatable === void 0) { updatable = false; }
  31827. if (!this._geometry) {
  31828. var vertexData = new BABYLON.VertexData();
  31829. vertexData.set(data, kind);
  31830. var scene = this.getScene();
  31831. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31832. }
  31833. else {
  31834. this._geometry.setVerticesData(kind, data, updatable, stride);
  31835. }
  31836. return this;
  31837. };
  31838. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  31839. if (updatable === void 0) { updatable = true; }
  31840. var vb = this.getVertexBuffer(kind);
  31841. if (!vb || vb.isUpdatable() === updatable) {
  31842. return;
  31843. }
  31844. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  31845. };
  31846. /**
  31847. * Sets the mesh VertexBuffer.
  31848. * Returns the Mesh.
  31849. */
  31850. Mesh.prototype.setVerticesBuffer = function (buffer) {
  31851. if (!this._geometry) {
  31852. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  31853. }
  31854. this._geometry.setVerticesBuffer(buffer);
  31855. return this;
  31856. };
  31857. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  31858. if (!this._geometry) {
  31859. return this;
  31860. }
  31861. if (!makeItUnique) {
  31862. this._geometry.updateVerticesData(kind, data, updateExtends);
  31863. }
  31864. else {
  31865. this.makeGeometryUnique();
  31866. this.updateVerticesData(kind, data, updateExtends, false);
  31867. }
  31868. return this;
  31869. };
  31870. /**
  31871. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  31872. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  31873. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  31874. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  31875. * Returns the Mesh.
  31876. */
  31877. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  31878. if (computeNormals === void 0) { computeNormals = true; }
  31879. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31880. if (!positions) {
  31881. return this;
  31882. }
  31883. positionFunction(positions);
  31884. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  31885. if (computeNormals) {
  31886. var indices = this.getIndices();
  31887. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  31888. if (!normals) {
  31889. return this;
  31890. }
  31891. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  31892. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  31893. }
  31894. return this;
  31895. };
  31896. /**
  31897. * Creates a un-shared specific occurence of the geometry for the mesh.
  31898. * Returns the Mesh.
  31899. */
  31900. Mesh.prototype.makeGeometryUnique = function () {
  31901. if (!this._geometry) {
  31902. return this;
  31903. }
  31904. var oldGeometry = this._geometry;
  31905. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  31906. oldGeometry.releaseForMesh(this, true);
  31907. geometry.applyToMesh(this);
  31908. return this;
  31909. };
  31910. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  31911. if (totalVertices === void 0) { totalVertices = null; }
  31912. if (updatable === void 0) { updatable = false; }
  31913. if (!this._geometry) {
  31914. var vertexData = new BABYLON.VertexData();
  31915. vertexData.indices = indices;
  31916. var scene = this.getScene();
  31917. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  31918. }
  31919. else {
  31920. this._geometry.setIndices(indices, totalVertices, updatable);
  31921. }
  31922. return this;
  31923. };
  31924. /**
  31925. * Update the current index buffer
  31926. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  31927. * Returns the Mesh.
  31928. */
  31929. Mesh.prototype.updateIndices = function (indices, offset) {
  31930. if (!this._geometry) {
  31931. return this;
  31932. }
  31933. this._geometry.updateIndices(indices, offset);
  31934. return this;
  31935. };
  31936. /**
  31937. * Invert the geometry to move from a right handed system to a left handed one.
  31938. * Returns the Mesh.
  31939. */
  31940. Mesh.prototype.toLeftHanded = function () {
  31941. if (!this._geometry) {
  31942. return this;
  31943. }
  31944. this._geometry.toLeftHanded();
  31945. return this;
  31946. };
  31947. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  31948. if (!this._geometry) {
  31949. return this;
  31950. }
  31951. var engine = this.getScene().getEngine();
  31952. // Wireframe
  31953. var indexToBind;
  31954. if (this._unIndexed) {
  31955. indexToBind = null;
  31956. }
  31957. else {
  31958. switch (fillMode) {
  31959. case BABYLON.Material.PointFillMode:
  31960. indexToBind = null;
  31961. break;
  31962. case BABYLON.Material.WireFrameFillMode:
  31963. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  31964. break;
  31965. default:
  31966. case BABYLON.Material.TriangleFillMode:
  31967. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  31968. break;
  31969. }
  31970. }
  31971. // VBOs
  31972. this._geometry._bind(effect, indexToBind);
  31973. return this;
  31974. };
  31975. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  31976. if (alternate === void 0) { alternate = false; }
  31977. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  31978. return this;
  31979. }
  31980. this.onBeforeDrawObservable.notifyObservers(this);
  31981. var scene = this.getScene();
  31982. var engine = scene.getEngine();
  31983. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  31984. // or triangles as points
  31985. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  31986. }
  31987. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  31988. // Triangles as wireframe
  31989. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  31990. }
  31991. else {
  31992. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  31993. }
  31994. if (scene._isAlternateRenderingEnabled && !alternate) {
  31995. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  31996. if (!effect || !scene.activeCamera) {
  31997. return this;
  31998. }
  31999. scene._switchToAlternateCameraConfiguration(true);
  32000. this._effectiveMaterial.bindView(effect);
  32001. this._effectiveMaterial.bindViewProjection(effect);
  32002. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32003. this._draw(subMesh, fillMode, instancesCount, true);
  32004. engine.setViewport(scene.activeCamera.viewport);
  32005. scene._switchToAlternateCameraConfiguration(false);
  32006. this._effectiveMaterial.bindView(effect);
  32007. this._effectiveMaterial.bindViewProjection(effect);
  32008. }
  32009. return this;
  32010. };
  32011. /**
  32012. * Registers for this mesh a javascript function called just before the rendering process.
  32013. * This function is passed the current mesh.
  32014. * Return the Mesh.
  32015. */
  32016. Mesh.prototype.registerBeforeRender = function (func) {
  32017. this.onBeforeRenderObservable.add(func);
  32018. return this;
  32019. };
  32020. /**
  32021. * Disposes a previously registered javascript function called before the rendering.
  32022. * This function is passed the current mesh.
  32023. * Returns the Mesh.
  32024. */
  32025. Mesh.prototype.unregisterBeforeRender = function (func) {
  32026. this.onBeforeRenderObservable.removeCallback(func);
  32027. return this;
  32028. };
  32029. /**
  32030. * Registers for this mesh a javascript function called just after the rendering is complete.
  32031. * This function is passed the current mesh.
  32032. * Returns the Mesh.
  32033. */
  32034. Mesh.prototype.registerAfterRender = function (func) {
  32035. this.onAfterRenderObservable.add(func);
  32036. return this;
  32037. };
  32038. /**
  32039. * Disposes a previously registered javascript function called after the rendering.
  32040. * This function is passed the current mesh.
  32041. * Return the Mesh.
  32042. */
  32043. Mesh.prototype.unregisterAfterRender = function (func) {
  32044. this.onAfterRenderObservable.removeCallback(func);
  32045. return this;
  32046. };
  32047. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32048. var scene = this.getScene();
  32049. this._batchCache.mustReturn = false;
  32050. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32051. this._batchCache.visibleInstances[subMeshId] = null;
  32052. if (this._visibleInstances) {
  32053. var currentRenderId = scene.getRenderId();
  32054. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32055. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32056. var selfRenderId = this._renderId;
  32057. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32058. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32059. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32060. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32061. }
  32062. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32063. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32064. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32065. this._batchCache.mustReturn = true;
  32066. return this._batchCache;
  32067. }
  32068. if (currentRenderId !== selfRenderId) {
  32069. this._batchCache.renderSelf[subMeshId] = false;
  32070. }
  32071. }
  32072. this._renderIdForInstances[subMeshId] = currentRenderId;
  32073. }
  32074. return this._batchCache;
  32075. };
  32076. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32077. var visibleInstances = batch.visibleInstances[subMesh._id];
  32078. if (!visibleInstances) {
  32079. return this;
  32080. }
  32081. var matricesCount = visibleInstances.length + 1;
  32082. var bufferSize = matricesCount * 16 * 4;
  32083. var currentInstancesBufferSize = this._instancesBufferSize;
  32084. var instancesBuffer = this._instancesBuffer;
  32085. while (this._instancesBufferSize < bufferSize) {
  32086. this._instancesBufferSize *= 2;
  32087. }
  32088. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32089. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32090. }
  32091. var offset = 0;
  32092. var instancesCount = 0;
  32093. var world = this.getWorldMatrix();
  32094. if (batch.renderSelf[subMesh._id]) {
  32095. world.copyToArray(this._instancesData, offset);
  32096. offset += 16;
  32097. instancesCount++;
  32098. }
  32099. if (visibleInstances) {
  32100. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32101. var instance = visibleInstances[instanceIndex];
  32102. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32103. offset += 16;
  32104. instancesCount++;
  32105. }
  32106. }
  32107. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32108. if (instancesBuffer) {
  32109. instancesBuffer.dispose();
  32110. }
  32111. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32112. this._instancesBuffer = instancesBuffer;
  32113. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32114. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32115. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32116. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32117. }
  32118. else {
  32119. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32120. }
  32121. this._bind(subMesh, effect, fillMode);
  32122. this._draw(subMesh, fillMode, instancesCount);
  32123. engine.unbindInstanceAttributes();
  32124. return this;
  32125. };
  32126. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32127. var scene = this.getScene();
  32128. var engine = scene.getEngine();
  32129. if (hardwareInstancedRendering) {
  32130. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32131. }
  32132. else {
  32133. if (batch.renderSelf[subMesh._id]) {
  32134. // Draw
  32135. if (onBeforeDraw) {
  32136. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32137. }
  32138. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32139. }
  32140. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32141. if (visibleInstancesForSubMesh) {
  32142. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32143. var instance = visibleInstancesForSubMesh[instanceIndex];
  32144. // World
  32145. var world = instance.getWorldMatrix();
  32146. if (onBeforeDraw) {
  32147. onBeforeDraw(true, world, effectiveMaterial);
  32148. }
  32149. // Draw
  32150. this._draw(subMesh, fillMode);
  32151. }
  32152. }
  32153. }
  32154. return this;
  32155. };
  32156. /**
  32157. * Triggers the draw call for the mesh.
  32158. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32159. * Returns the Mesh.
  32160. */
  32161. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32162. this._checkOcclusionQuery();
  32163. if (this._isOccluded) {
  32164. return this;
  32165. }
  32166. var scene = this.getScene();
  32167. // Managing instances
  32168. var batch = this._getInstancesRenderList(subMesh._id);
  32169. if (batch.mustReturn) {
  32170. return this;
  32171. }
  32172. // Checking geometry state
  32173. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32174. return this;
  32175. }
  32176. this.onBeforeRenderObservable.notifyObservers(this);
  32177. var engine = scene.getEngine();
  32178. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32179. // Material
  32180. var material = subMesh.getMaterial();
  32181. if (!material) {
  32182. return this;
  32183. }
  32184. this._effectiveMaterial = material;
  32185. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32186. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32187. return this;
  32188. }
  32189. }
  32190. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32191. return this;
  32192. }
  32193. // Alpha mode
  32194. if (enableAlphaMode) {
  32195. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32196. }
  32197. // Outline - step 1
  32198. var savedDepthWrite = engine.getDepthWrite();
  32199. if (this.renderOutline) {
  32200. engine.setDepthWrite(false);
  32201. scene.getOutlineRenderer().render(subMesh, batch);
  32202. engine.setDepthWrite(savedDepthWrite);
  32203. }
  32204. var effect;
  32205. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32206. effect = subMesh.effect;
  32207. }
  32208. else {
  32209. effect = this._effectiveMaterial.getEffect();
  32210. }
  32211. if (!effect) {
  32212. return this;
  32213. }
  32214. var sideOrientation = this.overrideMaterialSideOrientation;
  32215. if (sideOrientation == null) {
  32216. sideOrientation = this._effectiveMaterial.sideOrientation;
  32217. if (this._getWorldMatrixDeterminant() < 0) {
  32218. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32219. }
  32220. }
  32221. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32222. if (this._effectiveMaterial.forceDepthWrite) {
  32223. engine.setDepthWrite(true);
  32224. }
  32225. // Bind
  32226. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32227. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32228. this._bind(subMesh, effect, fillMode);
  32229. }
  32230. var world = this.getWorldMatrix();
  32231. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32232. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32233. }
  32234. else {
  32235. this._effectiveMaterial.bind(world, this);
  32236. }
  32237. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32238. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32239. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32240. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32241. }
  32242. // Draw
  32243. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32244. // Unbind
  32245. this._effectiveMaterial.unbind();
  32246. // Outline - step 2
  32247. if (this.renderOutline && savedDepthWrite) {
  32248. engine.setDepthWrite(true);
  32249. engine.setColorWrite(false);
  32250. scene.getOutlineRenderer().render(subMesh, batch);
  32251. engine.setColorWrite(true);
  32252. }
  32253. // Overlay
  32254. if (this.renderOverlay) {
  32255. var currentMode = engine.getAlphaMode();
  32256. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32257. scene.getOutlineRenderer().render(subMesh, batch, true);
  32258. engine.setAlphaMode(currentMode);
  32259. }
  32260. this.onAfterRenderObservable.notifyObservers(this);
  32261. return this;
  32262. };
  32263. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32264. if (isInstance && effectiveMaterial) {
  32265. effectiveMaterial.bindOnlyWorldMatrix(world);
  32266. }
  32267. };
  32268. /**
  32269. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32270. */
  32271. Mesh.prototype.getEmittedParticleSystems = function () {
  32272. var results = new Array();
  32273. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32274. var particleSystem = this.getScene().particleSystems[index];
  32275. if (particleSystem.emitter === this) {
  32276. results.push(particleSystem);
  32277. }
  32278. }
  32279. return results;
  32280. };
  32281. /**
  32282. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32283. */
  32284. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32285. var results = new Array();
  32286. var descendants = this.getDescendants();
  32287. descendants.push(this);
  32288. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32289. var particleSystem = this.getScene().particleSystems[index];
  32290. var emitter = particleSystem.emitter;
  32291. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32292. results.push(particleSystem);
  32293. }
  32294. }
  32295. return results;
  32296. };
  32297. /**
  32298. * Normalize matrix weights so that all vertices have a total weight set to 1
  32299. */
  32300. Mesh.prototype.cleanMatrixWeights = function () {
  32301. var epsilon = 1e-3;
  32302. var noInfluenceBoneIndex = 0.0;
  32303. if (this.skeleton) {
  32304. noInfluenceBoneIndex = this.skeleton.bones.length;
  32305. }
  32306. else {
  32307. return;
  32308. }
  32309. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32310. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32311. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32312. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32313. var influencers = this.numBoneInfluencers;
  32314. var size = matricesWeights.length;
  32315. for (var i = 0; i < size; i += 4) {
  32316. var weight = 0.0;
  32317. var firstZeroWeight = -1;
  32318. for (var j = 0; j < 4; j++) {
  32319. var w = matricesWeights[i + j];
  32320. weight += w;
  32321. if (w < epsilon && firstZeroWeight < 0) {
  32322. firstZeroWeight = j;
  32323. }
  32324. }
  32325. if (matricesWeightsExtra) {
  32326. for (var j = 0; j < 4; j++) {
  32327. var w = matricesWeightsExtra[i + j];
  32328. weight += w;
  32329. if (w < epsilon && firstZeroWeight < 0) {
  32330. firstZeroWeight = j + 4;
  32331. }
  32332. }
  32333. }
  32334. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32335. firstZeroWeight = influencers - 1;
  32336. }
  32337. if (weight > epsilon) {
  32338. var mweight = 1.0 / weight;
  32339. for (var j = 0; j < 4; j++) {
  32340. matricesWeights[i + j] *= mweight;
  32341. }
  32342. if (matricesWeightsExtra) {
  32343. for (var j = 0; j < 4; j++) {
  32344. matricesWeightsExtra[i + j] *= mweight;
  32345. }
  32346. }
  32347. }
  32348. else {
  32349. if (firstZeroWeight >= 4) {
  32350. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32351. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32352. }
  32353. else {
  32354. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32355. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32356. }
  32357. }
  32358. }
  32359. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32360. if (matricesIndicesExtra) {
  32361. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32362. }
  32363. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32364. if (matricesWeightsExtra) {
  32365. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32366. }
  32367. };
  32368. Mesh.prototype._checkDelayState = function () {
  32369. var scene = this.getScene();
  32370. if (this._geometry) {
  32371. this._geometry.load(scene);
  32372. }
  32373. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32374. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32375. this._queueLoad(scene);
  32376. }
  32377. return this;
  32378. };
  32379. Mesh.prototype._queueLoad = function (scene) {
  32380. var _this = this;
  32381. scene._addPendingData(this);
  32382. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32383. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32384. if (data instanceof ArrayBuffer) {
  32385. _this._delayLoadingFunction(data, _this);
  32386. }
  32387. else {
  32388. _this._delayLoadingFunction(JSON.parse(data), _this);
  32389. }
  32390. _this.instances.forEach(function (instance) {
  32391. instance._syncSubMeshes();
  32392. });
  32393. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32394. scene._removePendingData(_this);
  32395. }, function () { }, scene.database, getBinaryData);
  32396. return this;
  32397. };
  32398. /**
  32399. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32400. */
  32401. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32402. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32403. return false;
  32404. }
  32405. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32406. return false;
  32407. }
  32408. this._checkDelayState();
  32409. return true;
  32410. };
  32411. /**
  32412. * Sets the mesh material by the material or multiMaterial `id` property.
  32413. * The material `id` is a string identifying the material or the multiMaterial.
  32414. * This method returns the Mesh.
  32415. */
  32416. Mesh.prototype.setMaterialByID = function (id) {
  32417. var materials = this.getScene().materials;
  32418. var index;
  32419. for (index = materials.length - 1; index > -1; index--) {
  32420. if (materials[index].id === id) {
  32421. this.material = materials[index];
  32422. return this;
  32423. }
  32424. }
  32425. // Multi
  32426. var multiMaterials = this.getScene().multiMaterials;
  32427. for (index = multiMaterials.length - 1; index > -1; index--) {
  32428. if (multiMaterials[index].id === id) {
  32429. this.material = multiMaterials[index];
  32430. return this;
  32431. }
  32432. }
  32433. return this;
  32434. };
  32435. /**
  32436. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  32437. */
  32438. Mesh.prototype.getAnimatables = function () {
  32439. var results = new Array();
  32440. if (this.material) {
  32441. results.push(this.material);
  32442. }
  32443. if (this.skeleton) {
  32444. results.push(this.skeleton);
  32445. }
  32446. return results;
  32447. };
  32448. /**
  32449. * Modifies the mesh geometry according to the passed transformation matrix.
  32450. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  32451. * The mesh normals are modified accordingly the same transformation.
  32452. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  32453. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32454. * Returns the Mesh.
  32455. */
  32456. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  32457. // Position
  32458. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  32459. return this;
  32460. }
  32461. var submeshes = this.subMeshes.splice(0);
  32462. this._resetPointsArrayCache();
  32463. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32464. var temp = new Array();
  32465. var index;
  32466. for (index = 0; index < data.length; index += 3) {
  32467. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  32468. }
  32469. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  32470. // Normals
  32471. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  32472. return this;
  32473. }
  32474. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32475. temp = [];
  32476. for (index = 0; index < data.length; index += 3) {
  32477. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  32478. }
  32479. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  32480. // flip faces?
  32481. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  32482. this.flipFaces();
  32483. }
  32484. // Restore submeshes
  32485. this.releaseSubMeshes();
  32486. this.subMeshes = submeshes;
  32487. return this;
  32488. };
  32489. /**
  32490. * Modifies the mesh geometry according to its own current World Matrix.
  32491. * The mesh World Matrix is then reset.
  32492. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  32493. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  32494. * Note that, under the hood, this method sets a new VertexBuffer each call.
  32495. * Returns the Mesh.
  32496. */
  32497. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  32498. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  32499. this.scaling.copyFromFloats(1, 1, 1);
  32500. this.position.copyFromFloats(0, 0, 0);
  32501. this.rotation.copyFromFloats(0, 0, 0);
  32502. //only if quaternion is already set
  32503. if (this.rotationQuaternion) {
  32504. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  32505. }
  32506. this._worldMatrix = BABYLON.Matrix.Identity();
  32507. return this;
  32508. };
  32509. Object.defineProperty(Mesh.prototype, "_positions", {
  32510. // Cache
  32511. get: function () {
  32512. if (this._geometry) {
  32513. return this._geometry._positions;
  32514. }
  32515. return null;
  32516. },
  32517. enumerable: true,
  32518. configurable: true
  32519. });
  32520. Mesh.prototype._resetPointsArrayCache = function () {
  32521. if (this._geometry) {
  32522. this._geometry._resetPointsArrayCache();
  32523. }
  32524. return this;
  32525. };
  32526. Mesh.prototype._generatePointsArray = function () {
  32527. if (this._geometry) {
  32528. return this._geometry._generatePointsArray();
  32529. }
  32530. return false;
  32531. };
  32532. /**
  32533. * Returns a new Mesh object generated from the current mesh properties.
  32534. * This method must not get confused with createInstance().
  32535. * The parameter `name` is a string, the name given to the new mesh.
  32536. * The optional parameter `newParent` can be any Node object (default `null`).
  32537. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  32538. * 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.
  32539. */
  32540. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  32541. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  32542. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  32543. };
  32544. /**
  32545. * Releases resources associated with this mesh.
  32546. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  32547. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  32548. */
  32549. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  32550. var _this = this;
  32551. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  32552. this.morphTargetManager = null;
  32553. if (this._geometry) {
  32554. this._geometry.releaseForMesh(this, true);
  32555. }
  32556. // Sources
  32557. var meshes = this.getScene().meshes;
  32558. meshes.forEach(function (abstractMesh) {
  32559. var mesh = abstractMesh;
  32560. if (mesh._source && mesh._source === _this) {
  32561. mesh._source = null;
  32562. }
  32563. });
  32564. this._source = null;
  32565. // Instances
  32566. if (this._instancesBuffer) {
  32567. this._instancesBuffer.dispose();
  32568. this._instancesBuffer = null;
  32569. }
  32570. while (this.instances.length) {
  32571. this.instances[0].dispose();
  32572. }
  32573. // Effect layers.
  32574. var effectLayers = this.getScene().effectLayers;
  32575. for (var i = 0; i < effectLayers.length; i++) {
  32576. var effectLayer = effectLayers[i];
  32577. if (effectLayer) {
  32578. effectLayer._disposeMesh(this);
  32579. }
  32580. }
  32581. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  32582. };
  32583. /**
  32584. * Modifies the mesh geometry according to a displacement map.
  32585. * 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.
  32586. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32587. * This method returns nothing.
  32588. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  32589. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32590. * 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.
  32591. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32592. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32593. *
  32594. * Returns the Mesh.
  32595. */
  32596. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  32597. var _this = this;
  32598. var scene = this.getScene();
  32599. var onload = function (img) {
  32600. // Getting height map data
  32601. var canvas = document.createElement("canvas");
  32602. var context = canvas.getContext("2d");
  32603. var heightMapWidth = img.width;
  32604. var heightMapHeight = img.height;
  32605. canvas.width = heightMapWidth;
  32606. canvas.height = heightMapHeight;
  32607. context.drawImage(img, 0, 0);
  32608. // Create VertexData from map data
  32609. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  32610. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  32611. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  32612. //execute success callback, if set
  32613. if (onSuccess) {
  32614. onSuccess(_this);
  32615. }
  32616. };
  32617. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  32618. return this;
  32619. };
  32620. /**
  32621. * Modifies the mesh geometry according to a displacementMap buffer.
  32622. * 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.
  32623. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  32624. * This method returns nothing.
  32625. * 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.
  32626. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  32627. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  32628. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  32629. * The parameter `uvScale` is an optional vector2 used to scale UV.
  32630. *
  32631. * Returns the Mesh.
  32632. */
  32633. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  32634. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  32635. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  32636. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  32637. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  32638. return this;
  32639. }
  32640. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32641. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32642. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  32643. var position = BABYLON.Vector3.Zero();
  32644. var normal = BABYLON.Vector3.Zero();
  32645. var uv = BABYLON.Vector2.Zero();
  32646. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  32647. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  32648. for (var index = 0; index < positions.length; index += 3) {
  32649. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  32650. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  32651. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  32652. // Compute height
  32653. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  32654. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  32655. var pos = (u + v * heightMapWidth) * 4;
  32656. var r = buffer[pos] / 255.0;
  32657. var g = buffer[pos + 1] / 255.0;
  32658. var b = buffer[pos + 2] / 255.0;
  32659. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  32660. normal.normalize();
  32661. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  32662. position = position.add(normal);
  32663. position.toArray(positions, index);
  32664. }
  32665. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  32666. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  32667. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  32668. return this;
  32669. };
  32670. /**
  32671. * Modify the mesh to get a flat shading rendering.
  32672. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  32673. * This method returns the Mesh.
  32674. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  32675. */
  32676. Mesh.prototype.convertToFlatShadedMesh = function () {
  32677. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  32678. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32679. var kinds = this.getVerticesDataKinds();
  32680. var vbs = {};
  32681. var data = {};
  32682. var newdata = {};
  32683. var updatableNormals = false;
  32684. var kindIndex;
  32685. var kind;
  32686. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32687. kind = kinds[kindIndex];
  32688. var vertexBuffer = this.getVertexBuffer(kind);
  32689. if (kind === BABYLON.VertexBuffer.NormalKind) {
  32690. updatableNormals = vertexBuffer.isUpdatable();
  32691. kinds.splice(kindIndex, 1);
  32692. kindIndex--;
  32693. continue;
  32694. }
  32695. vbs[kind] = vertexBuffer;
  32696. data[kind] = vbs[kind].getData();
  32697. newdata[kind] = [];
  32698. }
  32699. // Save previous submeshes
  32700. var previousSubmeshes = this.subMeshes.slice(0);
  32701. var indices = this.getIndices();
  32702. var totalIndices = this.getTotalIndices();
  32703. // Generating unique vertices per face
  32704. var index;
  32705. for (index = 0; index < totalIndices; index++) {
  32706. var vertexIndex = indices[index];
  32707. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32708. kind = kinds[kindIndex];
  32709. var stride = vbs[kind].getStrideSize();
  32710. for (var offset = 0; offset < stride; offset++) {
  32711. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32712. }
  32713. }
  32714. }
  32715. // Updating faces & normal
  32716. var normals = [];
  32717. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  32718. for (index = 0; index < totalIndices; index += 3) {
  32719. indices[index] = index;
  32720. indices[index + 1] = index + 1;
  32721. indices[index + 2] = index + 2;
  32722. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  32723. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  32724. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  32725. var p1p2 = p1.subtract(p2);
  32726. var p3p2 = p3.subtract(p2);
  32727. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  32728. // Store same normals for every vertex
  32729. for (var localIndex = 0; localIndex < 3; localIndex++) {
  32730. normals.push(normal.x);
  32731. normals.push(normal.y);
  32732. normals.push(normal.z);
  32733. }
  32734. }
  32735. this.setIndices(indices);
  32736. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  32737. // Updating vertex buffers
  32738. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32739. kind = kinds[kindIndex];
  32740. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32741. }
  32742. // Updating submeshes
  32743. this.releaseSubMeshes();
  32744. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32745. var previousOne = previousSubmeshes[submeshIndex];
  32746. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32747. }
  32748. this.synchronizeInstances();
  32749. return this;
  32750. };
  32751. /**
  32752. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  32753. * In other words, more vertices, no more indices and a single bigger VBO.
  32754. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  32755. * Returns the Mesh.
  32756. */
  32757. Mesh.prototype.convertToUnIndexedMesh = function () {
  32758. /// <summary>Remove indices by unfolding faces into buffers</summary>
  32759. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  32760. var kinds = this.getVerticesDataKinds();
  32761. var vbs = {};
  32762. var data = {};
  32763. var newdata = {};
  32764. var kindIndex;
  32765. var kind;
  32766. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32767. kind = kinds[kindIndex];
  32768. var vertexBuffer = this.getVertexBuffer(kind);
  32769. vbs[kind] = vertexBuffer;
  32770. data[kind] = vbs[kind].getData();
  32771. newdata[kind] = [];
  32772. }
  32773. // Save previous submeshes
  32774. var previousSubmeshes = this.subMeshes.slice(0);
  32775. var indices = this.getIndices();
  32776. var totalIndices = this.getTotalIndices();
  32777. // Generating unique vertices per face
  32778. var index;
  32779. for (index = 0; index < totalIndices; index++) {
  32780. var vertexIndex = indices[index];
  32781. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32782. kind = kinds[kindIndex];
  32783. var stride = vbs[kind].getStrideSize();
  32784. for (var offset = 0; offset < stride; offset++) {
  32785. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  32786. }
  32787. }
  32788. }
  32789. // Updating indices
  32790. for (index = 0; index < totalIndices; index += 3) {
  32791. indices[index] = index;
  32792. indices[index + 1] = index + 1;
  32793. indices[index + 2] = index + 2;
  32794. }
  32795. this.setIndices(indices);
  32796. // Updating vertex buffers
  32797. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  32798. kind = kinds[kindIndex];
  32799. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  32800. }
  32801. // Updating submeshes
  32802. this.releaseSubMeshes();
  32803. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  32804. var previousOne = previousSubmeshes[submeshIndex];
  32805. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  32806. }
  32807. this._unIndexed = true;
  32808. this.synchronizeInstances();
  32809. return this;
  32810. };
  32811. /**
  32812. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  32813. * This method returns the Mesh.
  32814. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  32815. */
  32816. Mesh.prototype.flipFaces = function (flipNormals) {
  32817. if (flipNormals === void 0) { flipNormals = false; }
  32818. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  32819. var i;
  32820. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  32821. for (i = 0; i < vertex_data.normals.length; i++) {
  32822. vertex_data.normals[i] *= -1;
  32823. }
  32824. }
  32825. if (vertex_data.indices) {
  32826. var temp;
  32827. for (i = 0; i < vertex_data.indices.length; i += 3) {
  32828. // reassign indices
  32829. temp = vertex_data.indices[i + 1];
  32830. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  32831. vertex_data.indices[i + 2] = temp;
  32832. }
  32833. }
  32834. vertex_data.applyToMesh(this);
  32835. return this;
  32836. };
  32837. // Instances
  32838. /**
  32839. * Creates a new InstancedMesh object from the mesh model.
  32840. * An instance shares the same properties and the same material than its model.
  32841. * Only these properties of each instance can then be set individually :
  32842. * - position
  32843. * - rotation
  32844. * - rotationQuaternion
  32845. * - setPivotMatrix
  32846. * - scaling
  32847. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  32848. * Warning : this method is not supported for Line mesh and LineSystem
  32849. */
  32850. Mesh.prototype.createInstance = function (name) {
  32851. return new BABYLON.InstancedMesh(name, this);
  32852. };
  32853. /**
  32854. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  32855. * After this call, all the mesh instances have the same submeshes than the current mesh.
  32856. * This method returns the Mesh.
  32857. */
  32858. Mesh.prototype.synchronizeInstances = function () {
  32859. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  32860. var instance = this.instances[instanceIndex];
  32861. instance._syncSubMeshes();
  32862. }
  32863. return this;
  32864. };
  32865. /**
  32866. * Simplify the mesh according to the given array of settings.
  32867. * Function will return immediately and will simplify async. It returns the Mesh.
  32868. * @param settings a collection of simplification settings.
  32869. * @param parallelProcessing should all levels calculate parallel or one after the other.
  32870. * @param type the type of simplification to run.
  32871. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  32872. */
  32873. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  32874. if (parallelProcessing === void 0) { parallelProcessing = true; }
  32875. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  32876. this.getScene().simplificationQueue.addTask({
  32877. settings: settings,
  32878. parallelProcessing: parallelProcessing,
  32879. mesh: this,
  32880. simplificationType: simplificationType,
  32881. successCallback: successCallback
  32882. });
  32883. return this;
  32884. };
  32885. /**
  32886. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  32887. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  32888. * This should be used together with the simplification to avoid disappearing triangles.
  32889. * Returns the Mesh.
  32890. * @param successCallback an optional success callback to be called after the optimization finished.
  32891. */
  32892. Mesh.prototype.optimizeIndices = function (successCallback) {
  32893. var _this = this;
  32894. var indices = this.getIndices();
  32895. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32896. if (!positions || !indices) {
  32897. return this;
  32898. }
  32899. var vectorPositions = new Array();
  32900. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  32901. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  32902. }
  32903. var dupes = new Array();
  32904. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  32905. var realPos = vectorPositions.length - 1 - iteration;
  32906. var testedPosition = vectorPositions[realPos];
  32907. for (var j = 0; j < realPos; ++j) {
  32908. var againstPosition = vectorPositions[j];
  32909. if (testedPosition.equals(againstPosition)) {
  32910. dupes[realPos] = j;
  32911. break;
  32912. }
  32913. }
  32914. }, function () {
  32915. for (var i = 0; i < indices.length; ++i) {
  32916. indices[i] = dupes[indices[i]] || indices[i];
  32917. }
  32918. //indices are now reordered
  32919. var originalSubMeshes = _this.subMeshes.slice(0);
  32920. _this.setIndices(indices);
  32921. _this.subMeshes = originalSubMeshes;
  32922. if (successCallback) {
  32923. successCallback(_this);
  32924. }
  32925. });
  32926. return this;
  32927. };
  32928. Mesh.prototype.serialize = function (serializationObject) {
  32929. serializationObject.name = this.name;
  32930. serializationObject.id = this.id;
  32931. serializationObject.type = this.getClassName();
  32932. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  32933. serializationObject.tags = BABYLON.Tags.GetTags(this);
  32934. }
  32935. serializationObject.position = this.position.asArray();
  32936. if (this.rotationQuaternion) {
  32937. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  32938. }
  32939. else if (this.rotation) {
  32940. serializationObject.rotation = this.rotation.asArray();
  32941. }
  32942. serializationObject.scaling = this.scaling.asArray();
  32943. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  32944. serializationObject.isEnabled = this.isEnabled(false);
  32945. serializationObject.isVisible = this.isVisible;
  32946. serializationObject.infiniteDistance = this.infiniteDistance;
  32947. serializationObject.pickable = this.isPickable;
  32948. serializationObject.receiveShadows = this.receiveShadows;
  32949. serializationObject.billboardMode = this.billboardMode;
  32950. serializationObject.visibility = this.visibility;
  32951. serializationObject.checkCollisions = this.checkCollisions;
  32952. serializationObject.isBlocker = this.isBlocker;
  32953. // Parent
  32954. if (this.parent) {
  32955. serializationObject.parentId = this.parent.id;
  32956. }
  32957. // Geometry
  32958. serializationObject.isUnIndexed = this.isUnIndexed;
  32959. var geometry = this._geometry;
  32960. if (geometry) {
  32961. var geometryId = geometry.id;
  32962. serializationObject.geometryId = geometryId;
  32963. // SubMeshes
  32964. serializationObject.subMeshes = [];
  32965. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  32966. var subMesh = this.subMeshes[subIndex];
  32967. serializationObject.subMeshes.push({
  32968. materialIndex: subMesh.materialIndex,
  32969. verticesStart: subMesh.verticesStart,
  32970. verticesCount: subMesh.verticesCount,
  32971. indexStart: subMesh.indexStart,
  32972. indexCount: subMesh.indexCount
  32973. });
  32974. }
  32975. }
  32976. // Material
  32977. if (this.material) {
  32978. serializationObject.materialId = this.material.id;
  32979. }
  32980. else {
  32981. this.material = null;
  32982. }
  32983. // Morph targets
  32984. if (this.morphTargetManager) {
  32985. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  32986. }
  32987. // Skeleton
  32988. if (this.skeleton) {
  32989. serializationObject.skeletonId = this.skeleton.id;
  32990. }
  32991. // Physics
  32992. //TODO implement correct serialization for physics impostors.
  32993. var impostor = this.getPhysicsImpostor();
  32994. if (impostor) {
  32995. serializationObject.physicsMass = impostor.getParam("mass");
  32996. serializationObject.physicsFriction = impostor.getParam("friction");
  32997. serializationObject.physicsRestitution = impostor.getParam("mass");
  32998. serializationObject.physicsImpostor = impostor.type;
  32999. }
  33000. // Metadata
  33001. if (this.metadata) {
  33002. serializationObject.metadata = this.metadata;
  33003. }
  33004. // Instances
  33005. serializationObject.instances = [];
  33006. for (var index = 0; index < this.instances.length; index++) {
  33007. var instance = this.instances[index];
  33008. var serializationInstance = {
  33009. name: instance.name,
  33010. id: instance.id,
  33011. position: instance.position.asArray(),
  33012. scaling: instance.scaling.asArray()
  33013. };
  33014. if (instance.rotationQuaternion) {
  33015. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33016. }
  33017. else if (instance.rotation) {
  33018. serializationInstance.rotation = instance.rotation.asArray();
  33019. }
  33020. serializationObject.instances.push(serializationInstance);
  33021. // Animations
  33022. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33023. serializationInstance.ranges = instance.serializeAnimationRanges();
  33024. }
  33025. //
  33026. // Animations
  33027. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33028. serializationObject.ranges = this.serializeAnimationRanges();
  33029. // Layer mask
  33030. serializationObject.layerMask = this.layerMask;
  33031. // Alpha
  33032. serializationObject.alphaIndex = this.alphaIndex;
  33033. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33034. // Overlay
  33035. serializationObject.overlayAlpha = this.overlayAlpha;
  33036. serializationObject.overlayColor = this.overlayColor.asArray();
  33037. serializationObject.renderOverlay = this.renderOverlay;
  33038. // Fog
  33039. serializationObject.applyFog = this.applyFog;
  33040. // Action Manager
  33041. if (this.actionManager) {
  33042. serializationObject.actions = this.actionManager.serialize(this.name);
  33043. }
  33044. };
  33045. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33046. if (!this.geometry) {
  33047. return;
  33048. }
  33049. this._markSubMeshesAsAttributesDirty();
  33050. var morphTargetManager = this._morphTargetManager;
  33051. if (morphTargetManager && morphTargetManager.vertexCount) {
  33052. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33053. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33054. this.morphTargetManager = null;
  33055. return;
  33056. }
  33057. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33058. var morphTarget = morphTargetManager.getActiveTarget(index);
  33059. var positions = morphTarget.getPositions();
  33060. if (!positions) {
  33061. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33062. return;
  33063. }
  33064. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33065. var normals = morphTarget.getNormals();
  33066. if (normals) {
  33067. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33068. }
  33069. var tangents = morphTarget.getTangents();
  33070. if (tangents) {
  33071. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33072. }
  33073. }
  33074. }
  33075. else {
  33076. var index = 0;
  33077. // Positions
  33078. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33079. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33080. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33081. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33082. }
  33083. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33084. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33085. }
  33086. index++;
  33087. }
  33088. }
  33089. };
  33090. // Statics
  33091. /**
  33092. * Returns a new Mesh object parsed from the source provided.
  33093. * The parameter `parsedMesh` is the source.
  33094. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33095. */
  33096. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33097. var mesh;
  33098. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33099. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33100. }
  33101. else {
  33102. mesh = new Mesh(parsedMesh.name, scene);
  33103. }
  33104. mesh.id = parsedMesh.id;
  33105. if (BABYLON.Tags) {
  33106. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33107. }
  33108. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33109. if (parsedMesh.metadata !== undefined) {
  33110. mesh.metadata = parsedMesh.metadata;
  33111. }
  33112. if (parsedMesh.rotationQuaternion) {
  33113. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33114. }
  33115. else if (parsedMesh.rotation) {
  33116. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33117. }
  33118. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33119. if (parsedMesh.localMatrix) {
  33120. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33121. }
  33122. else if (parsedMesh.pivotMatrix) {
  33123. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33124. }
  33125. mesh.setEnabled(parsedMesh.isEnabled);
  33126. mesh.isVisible = parsedMesh.isVisible;
  33127. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33128. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33129. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33130. if (parsedMesh.applyFog !== undefined) {
  33131. mesh.applyFog = parsedMesh.applyFog;
  33132. }
  33133. if (parsedMesh.pickable !== undefined) {
  33134. mesh.isPickable = parsedMesh.pickable;
  33135. }
  33136. if (parsedMesh.alphaIndex !== undefined) {
  33137. mesh.alphaIndex = parsedMesh.alphaIndex;
  33138. }
  33139. mesh.receiveShadows = parsedMesh.receiveShadows;
  33140. mesh.billboardMode = parsedMesh.billboardMode;
  33141. if (parsedMesh.visibility !== undefined) {
  33142. mesh.visibility = parsedMesh.visibility;
  33143. }
  33144. mesh.checkCollisions = parsedMesh.checkCollisions;
  33145. if (parsedMesh.isBlocker !== undefined) {
  33146. mesh.isBlocker = parsedMesh.isBlocker;
  33147. }
  33148. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33149. // freezeWorldMatrix
  33150. if (parsedMesh.freezeWorldMatrix) {
  33151. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33152. }
  33153. // Parent
  33154. if (parsedMesh.parentId) {
  33155. mesh._waitingParentId = parsedMesh.parentId;
  33156. }
  33157. // Actions
  33158. if (parsedMesh.actions !== undefined) {
  33159. mesh._waitingActions = parsedMesh.actions;
  33160. }
  33161. // Overlay
  33162. if (parsedMesh.overlayAlpha !== undefined) {
  33163. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33164. }
  33165. if (parsedMesh.overlayColor !== undefined) {
  33166. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33167. }
  33168. if (parsedMesh.renderOverlay !== undefined) {
  33169. mesh.renderOverlay = parsedMesh.renderOverlay;
  33170. }
  33171. // Geometry
  33172. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33173. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33174. if (parsedMesh.delayLoadingFile) {
  33175. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33176. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33177. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33178. if (parsedMesh._binaryInfo) {
  33179. mesh._binaryInfo = parsedMesh._binaryInfo;
  33180. }
  33181. mesh._delayInfo = [];
  33182. if (parsedMesh.hasUVs) {
  33183. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33184. }
  33185. if (parsedMesh.hasUVs2) {
  33186. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33187. }
  33188. if (parsedMesh.hasUVs3) {
  33189. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33190. }
  33191. if (parsedMesh.hasUVs4) {
  33192. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33193. }
  33194. if (parsedMesh.hasUVs5) {
  33195. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33196. }
  33197. if (parsedMesh.hasUVs6) {
  33198. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33199. }
  33200. if (parsedMesh.hasColors) {
  33201. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33202. }
  33203. if (parsedMesh.hasMatricesIndices) {
  33204. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33205. }
  33206. if (parsedMesh.hasMatricesWeights) {
  33207. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33208. }
  33209. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33210. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33211. mesh._checkDelayState();
  33212. }
  33213. }
  33214. else {
  33215. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33216. }
  33217. // Material
  33218. if (parsedMesh.materialId) {
  33219. mesh.setMaterialByID(parsedMesh.materialId);
  33220. }
  33221. else {
  33222. mesh.material = null;
  33223. }
  33224. // Morph targets
  33225. if (parsedMesh.morphTargetManagerId > -1) {
  33226. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33227. }
  33228. // Skeleton
  33229. if (parsedMesh.skeletonId > -1) {
  33230. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33231. if (parsedMesh.numBoneInfluencers) {
  33232. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33233. }
  33234. }
  33235. // Animations
  33236. if (parsedMesh.animations) {
  33237. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33238. var parsedAnimation = parsedMesh.animations[animationIndex];
  33239. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33240. }
  33241. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33242. }
  33243. if (parsedMesh.autoAnimate) {
  33244. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33245. }
  33246. // Layer Mask
  33247. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33248. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33249. }
  33250. else {
  33251. mesh.layerMask = 0x0FFFFFFF;
  33252. }
  33253. // Physics
  33254. if (parsedMesh.physicsImpostor) {
  33255. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33256. mass: parsedMesh.physicsMass,
  33257. friction: parsedMesh.physicsFriction,
  33258. restitution: parsedMesh.physicsRestitution
  33259. }, scene);
  33260. }
  33261. // Instances
  33262. if (parsedMesh.instances) {
  33263. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33264. var parsedInstance = parsedMesh.instances[index];
  33265. var instance = mesh.createInstance(parsedInstance.name);
  33266. if (parsedInstance.id) {
  33267. instance.id = parsedInstance.id;
  33268. }
  33269. if (BABYLON.Tags) {
  33270. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33271. }
  33272. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33273. if (parsedInstance.parentId) {
  33274. instance._waitingParentId = parsedInstance.parentId;
  33275. }
  33276. if (parsedInstance.rotationQuaternion) {
  33277. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33278. }
  33279. else if (parsedInstance.rotation) {
  33280. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33281. }
  33282. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33283. instance.checkCollisions = mesh.checkCollisions;
  33284. if (parsedMesh.animations) {
  33285. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33286. parsedAnimation = parsedMesh.animations[animationIndex];
  33287. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33288. }
  33289. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33290. }
  33291. }
  33292. }
  33293. return mesh;
  33294. };
  33295. /**
  33296. * Creates a ribbon mesh.
  33297. * Please consider using the same method from the MeshBuilder class instead.
  33298. * 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.
  33299. *
  33300. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33301. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33302. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33303. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33304. * 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.
  33305. * 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.
  33306. * 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
  33307. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33308. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33309. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33310. */
  33311. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33312. if (closeArray === void 0) { closeArray = false; }
  33313. if (updatable === void 0) { updatable = false; }
  33314. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33315. pathArray: pathArray,
  33316. closeArray: closeArray,
  33317. closePath: closePath,
  33318. offset: offset,
  33319. updatable: updatable,
  33320. sideOrientation: sideOrientation,
  33321. instance: instance
  33322. }, scene);
  33323. };
  33324. /**
  33325. * Creates a plane polygonal mesh. By default, this is a disc.
  33326. * Please consider using the same method from the MeshBuilder class instead.
  33327. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33328. * 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.
  33329. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33330. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33331. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33332. */
  33333. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33334. if (scene === void 0) { scene = null; }
  33335. var options = {
  33336. radius: radius,
  33337. tessellation: tessellation,
  33338. sideOrientation: sideOrientation,
  33339. updatable: updatable
  33340. };
  33341. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33342. };
  33343. /**
  33344. * Creates a box mesh.
  33345. * Please consider using the same method from the MeshBuilder class instead.
  33346. * The parameter `size` sets the size (float) of each box side (default 1).
  33347. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33348. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33349. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33350. */
  33351. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33352. if (scene === void 0) { scene = null; }
  33353. var options = {
  33354. size: size,
  33355. sideOrientation: sideOrientation,
  33356. updatable: updatable
  33357. };
  33358. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33359. };
  33360. /**
  33361. * Creates a sphere mesh.
  33362. * Please consider using the same method from the MeshBuilder class instead.
  33363. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33364. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33365. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33366. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33367. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33368. */
  33369. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33370. var options = {
  33371. segments: segments,
  33372. diameterX: diameter,
  33373. diameterY: diameter,
  33374. diameterZ: diameter,
  33375. sideOrientation: sideOrientation,
  33376. updatable: updatable
  33377. };
  33378. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33379. };
  33380. /**
  33381. * Creates a cylinder or a cone mesh.
  33382. * Please consider using the same method from the MeshBuilder class instead.
  33383. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33384. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33385. * 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.
  33386. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33387. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33388. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33389. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33390. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33391. */
  33392. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33393. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33394. if (scene !== undefined) {
  33395. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33396. updatable = scene;
  33397. }
  33398. scene = subdivisions;
  33399. subdivisions = 1;
  33400. }
  33401. var options = {
  33402. height: height,
  33403. diameterTop: diameterTop,
  33404. diameterBottom: diameterBottom,
  33405. tessellation: tessellation,
  33406. subdivisions: subdivisions,
  33407. sideOrientation: sideOrientation,
  33408. updatable: updatable
  33409. };
  33410. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  33411. };
  33412. // Torus (Code from SharpDX.org)
  33413. /**
  33414. * Creates a torus mesh.
  33415. * Please consider using the same method from the MeshBuilder class instead.
  33416. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  33417. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  33418. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  33419. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33420. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33421. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33422. */
  33423. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  33424. var options = {
  33425. diameter: diameter,
  33426. thickness: thickness,
  33427. tessellation: tessellation,
  33428. sideOrientation: sideOrientation,
  33429. updatable: updatable
  33430. };
  33431. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  33432. };
  33433. /**
  33434. * Creates a torus knot mesh.
  33435. * Please consider using the same method from the MeshBuilder class instead.
  33436. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  33437. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  33438. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  33439. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  33440. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33441. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33442. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33443. */
  33444. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  33445. var options = {
  33446. radius: radius,
  33447. tube: tube,
  33448. radialSegments: radialSegments,
  33449. tubularSegments: tubularSegments,
  33450. p: p,
  33451. q: q,
  33452. sideOrientation: sideOrientation,
  33453. updatable: updatable
  33454. };
  33455. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  33456. };
  33457. /**
  33458. * Creates a line mesh.
  33459. * Please consider using the same method from the MeshBuilder class instead.
  33460. * 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.
  33461. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33462. * The parameter `points` is an array successive Vector3.
  33463. * 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
  33464. * When updating an instance, remember that only point positions can change, not the number of points.
  33465. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33466. */
  33467. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  33468. if (scene === void 0) { scene = null; }
  33469. if (updatable === void 0) { updatable = false; }
  33470. if (instance === void 0) { instance = null; }
  33471. var options = {
  33472. points: points,
  33473. updatable: updatable,
  33474. instance: instance
  33475. };
  33476. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  33477. };
  33478. /**
  33479. * Creates a dashed line mesh.
  33480. * Please consider using the same method from the MeshBuilder class instead.
  33481. * 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.
  33482. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  33483. * The parameter `points` is an array successive Vector3.
  33484. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  33485. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  33486. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  33487. * 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
  33488. * When updating an instance, remember that only point positions can change, not the number of points.
  33489. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33490. */
  33491. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  33492. if (scene === void 0) { scene = null; }
  33493. var options = {
  33494. points: points,
  33495. dashSize: dashSize,
  33496. gapSize: gapSize,
  33497. dashNb: dashNb,
  33498. updatable: updatable,
  33499. instance: instance
  33500. };
  33501. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  33502. };
  33503. /**
  33504. * Creates a polygon mesh.
  33505. * Please consider using the same method from the MeshBuilder class instead.
  33506. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  33507. * 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.
  33508. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33509. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33510. * Remember you can only change the shape positions, not their number when updating a polygon.
  33511. */
  33512. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  33513. var options = {
  33514. shape: shape,
  33515. holes: holes,
  33516. updatable: updatable,
  33517. sideOrientation: sideOrientation
  33518. };
  33519. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  33520. };
  33521. /**
  33522. * Creates an extruded polygon mesh, with depth in the Y direction.
  33523. * Please consider using the same method from the MeshBuilder class instead.
  33524. */
  33525. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  33526. var options = {
  33527. shape: shape,
  33528. holes: holes,
  33529. depth: depth,
  33530. updatable: updatable,
  33531. sideOrientation: sideOrientation
  33532. };
  33533. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  33534. };
  33535. /**
  33536. * Creates an extruded shape mesh.
  33537. * 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.
  33538. * Please consider using the same method from the MeshBuilder class instead.
  33539. *
  33540. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33541. * 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
  33542. * extruded along the Z axis.
  33543. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33544. * 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.
  33545. * The parameter `scale` (float, default 1) is the value to scale the shape.
  33546. * 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
  33547. * 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
  33548. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33549. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33550. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33551. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33552. */
  33553. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  33554. if (scene === void 0) { scene = null; }
  33555. var options = {
  33556. shape: shape,
  33557. path: path,
  33558. scale: scale,
  33559. rotation: rotation,
  33560. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33561. sideOrientation: sideOrientation,
  33562. instance: instance,
  33563. updatable: updatable
  33564. };
  33565. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  33566. };
  33567. /**
  33568. * Creates an custom extruded shape mesh.
  33569. * 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.
  33570. * Please consider using the same method from the MeshBuilder class instead.
  33571. *
  33572. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  33573. * 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
  33574. * extruded along the Z axis.
  33575. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  33576. * 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
  33577. * and the distance of this point from the begining of the path :
  33578. * ```javascript
  33579. * var rotationFunction = function(i, distance) {
  33580. * // do things
  33581. * return rotationValue; }
  33582. * ```
  33583. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  33584. * 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
  33585. * and the distance of this point from the begining of the path :
  33586. * ```javascript
  33587. * var scaleFunction = function(i, distance) {
  33588. * // do things
  33589. * return scaleValue;}
  33590. * ```
  33591. * It must returns a float value that will be the scale value applied to the shape on each path point.
  33592. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  33593. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  33594. * 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
  33595. * 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
  33596. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  33597. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33598. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33599. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33600. */
  33601. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  33602. var options = {
  33603. shape: shape,
  33604. path: path,
  33605. scaleFunction: scaleFunction,
  33606. rotationFunction: rotationFunction,
  33607. ribbonCloseArray: ribbonCloseArray,
  33608. ribbonClosePath: ribbonClosePath,
  33609. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  33610. sideOrientation: sideOrientation,
  33611. instance: instance,
  33612. updatable: updatable
  33613. };
  33614. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  33615. };
  33616. /**
  33617. * Creates lathe mesh.
  33618. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  33619. * Please consider using the same method from the MeshBuilder class instead.
  33620. * 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
  33621. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  33622. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  33623. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  33624. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33625. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33626. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33627. */
  33628. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  33629. var options = {
  33630. shape: shape,
  33631. radius: radius,
  33632. tessellation: tessellation,
  33633. sideOrientation: sideOrientation,
  33634. updatable: updatable
  33635. };
  33636. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  33637. };
  33638. /**
  33639. * Creates a plane mesh.
  33640. * Please consider using the same method from the MeshBuilder class instead.
  33641. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  33642. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33643. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33644. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33645. */
  33646. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  33647. var options = {
  33648. size: size,
  33649. width: size,
  33650. height: size,
  33651. sideOrientation: sideOrientation,
  33652. updatable: updatable
  33653. };
  33654. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  33655. };
  33656. /**
  33657. * Creates a ground mesh.
  33658. * Please consider using the same method from the MeshBuilder class instead.
  33659. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  33660. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  33661. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33662. */
  33663. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  33664. var options = {
  33665. width: width,
  33666. height: height,
  33667. subdivisions: subdivisions,
  33668. updatable: updatable
  33669. };
  33670. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  33671. };
  33672. /**
  33673. * Creates a tiled ground mesh.
  33674. * Please consider using the same method from the MeshBuilder class instead.
  33675. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  33676. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  33677. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  33678. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  33679. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  33680. * numbers of subdivisions on the ground width and height of each tile.
  33681. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33682. */
  33683. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  33684. var options = {
  33685. xmin: xmin,
  33686. zmin: zmin,
  33687. xmax: xmax,
  33688. zmax: zmax,
  33689. subdivisions: subdivisions,
  33690. precision: precision,
  33691. updatable: updatable
  33692. };
  33693. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  33694. };
  33695. /**
  33696. * Creates a ground mesh from a height map.
  33697. * tuto : http://doc.babylonjs.com/babylon101/height_map
  33698. * Please consider using the same method from the MeshBuilder class instead.
  33699. * The parameter `url` sets the URL of the height map image resource.
  33700. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  33701. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  33702. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  33703. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  33704. * 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).
  33705. * This function is passed the newly built mesh :
  33706. * ```javascript
  33707. * function(mesh) { // do things
  33708. * return; }
  33709. * ```
  33710. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33711. */
  33712. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  33713. var options = {
  33714. width: width,
  33715. height: height,
  33716. subdivisions: subdivisions,
  33717. minHeight: minHeight,
  33718. maxHeight: maxHeight,
  33719. updatable: updatable,
  33720. onReady: onReady
  33721. };
  33722. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  33723. };
  33724. /**
  33725. * Creates a tube mesh.
  33726. * 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.
  33727. * Please consider using the same method from the MeshBuilder class instead.
  33728. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  33729. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  33730. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  33731. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  33732. * 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.
  33733. * It must return a radius value (positive float) :
  33734. * ```javascript
  33735. * var radiusFunction = function(i, distance) {
  33736. * // do things
  33737. * return radius; }
  33738. * ```
  33739. * 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
  33740. * 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
  33741. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33742. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33743. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33744. */
  33745. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  33746. var options = {
  33747. path: path,
  33748. radius: radius,
  33749. tessellation: tessellation,
  33750. radiusFunction: radiusFunction,
  33751. arc: 1,
  33752. cap: cap,
  33753. updatable: updatable,
  33754. sideOrientation: sideOrientation,
  33755. instance: instance
  33756. };
  33757. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  33758. };
  33759. /**
  33760. * Creates a polyhedron mesh.
  33761. * Please consider using the same method from the MeshBuilder class instead.
  33762. * 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
  33763. * to choose the wanted type.
  33764. * The parameter `size` (positive float, default 1) sets the polygon size.
  33765. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  33766. * 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`.
  33767. * 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
  33768. * 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)`).
  33769. * 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
  33770. * 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.
  33771. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33772. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33773. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33774. */
  33775. Mesh.CreatePolyhedron = function (name, options, scene) {
  33776. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  33777. };
  33778. /**
  33779. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  33780. * Please consider using the same method from the MeshBuilder class instead.
  33781. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  33782. * 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`).
  33783. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  33784. * 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.
  33785. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33786. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33787. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33788. */
  33789. Mesh.CreateIcoSphere = function (name, options, scene) {
  33790. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  33791. };
  33792. /**
  33793. * Creates a decal mesh.
  33794. * Please consider using the same method from the MeshBuilder class instead.
  33795. * 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.
  33796. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  33797. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  33798. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  33799. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  33800. */
  33801. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  33802. var options = {
  33803. position: position,
  33804. normal: normal,
  33805. size: size,
  33806. angle: angle
  33807. };
  33808. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  33809. };
  33810. // Skeletons
  33811. /**
  33812. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33813. */
  33814. Mesh.prototype.setPositionsForCPUSkinning = function () {
  33815. if (!this._sourcePositions) {
  33816. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33817. if (!source) {
  33818. return this._sourcePositions;
  33819. }
  33820. this._sourcePositions = new Float32Array(source);
  33821. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  33822. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  33823. }
  33824. }
  33825. return this._sourcePositions;
  33826. };
  33827. /**
  33828. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  33829. */
  33830. Mesh.prototype.setNormalsForCPUSkinning = function () {
  33831. if (!this._sourceNormals) {
  33832. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33833. if (!source) {
  33834. return this._sourceNormals;
  33835. }
  33836. this._sourceNormals = new Float32Array(source);
  33837. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  33838. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  33839. }
  33840. }
  33841. return this._sourceNormals;
  33842. };
  33843. /**
  33844. * Updates the vertex buffer by applying transformation from the bones.
  33845. * Returns the Mesh.
  33846. *
  33847. * @param {skeleton} skeleton to apply
  33848. */
  33849. Mesh.prototype.applySkeleton = function (skeleton) {
  33850. if (!this.geometry) {
  33851. return this;
  33852. }
  33853. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  33854. return this;
  33855. }
  33856. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  33857. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33858. return this;
  33859. }
  33860. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33861. return this;
  33862. }
  33863. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  33864. return this;
  33865. }
  33866. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  33867. return this;
  33868. }
  33869. if (!this._sourcePositions) {
  33870. var submeshes = this.subMeshes.slice();
  33871. this.setPositionsForCPUSkinning();
  33872. this.subMeshes = submeshes;
  33873. }
  33874. if (!this._sourceNormals) {
  33875. this.setNormalsForCPUSkinning();
  33876. }
  33877. // positionsData checks for not being Float32Array will only pass at most once
  33878. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33879. if (!positionsData) {
  33880. return this;
  33881. }
  33882. if (!(positionsData instanceof Float32Array)) {
  33883. positionsData = new Float32Array(positionsData);
  33884. }
  33885. // normalsData checks for not being Float32Array will only pass at most once
  33886. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33887. if (!normalsData) {
  33888. return this;
  33889. }
  33890. if (!(normalsData instanceof Float32Array)) {
  33891. normalsData = new Float32Array(normalsData);
  33892. }
  33893. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  33894. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  33895. if (!matricesWeightsData || !matricesIndicesData) {
  33896. return this;
  33897. }
  33898. var needExtras = this.numBoneInfluencers > 4;
  33899. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  33900. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  33901. var skeletonMatrices = skeleton.getTransformMatrices(this);
  33902. var tempVector3 = BABYLON.Vector3.Zero();
  33903. var finalMatrix = new BABYLON.Matrix();
  33904. var tempMatrix = new BABYLON.Matrix();
  33905. var matWeightIdx = 0;
  33906. var inf;
  33907. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  33908. var weight;
  33909. for (inf = 0; inf < 4; inf++) {
  33910. weight = matricesWeightsData[matWeightIdx + inf];
  33911. if (weight > 0) {
  33912. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33913. finalMatrix.addToSelf(tempMatrix);
  33914. }
  33915. else
  33916. break;
  33917. }
  33918. if (needExtras) {
  33919. for (inf = 0; inf < 4; inf++) {
  33920. weight = matricesWeightsExtraData[matWeightIdx + inf];
  33921. if (weight > 0) {
  33922. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  33923. finalMatrix.addToSelf(tempMatrix);
  33924. }
  33925. else
  33926. break;
  33927. }
  33928. }
  33929. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  33930. tempVector3.toArray(positionsData, index);
  33931. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  33932. tempVector3.toArray(normalsData, index);
  33933. finalMatrix.reset();
  33934. }
  33935. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  33936. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  33937. return this;
  33938. };
  33939. // Tools
  33940. /**
  33941. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  33942. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  33943. */
  33944. Mesh.MinMax = function (meshes) {
  33945. var minVector = null;
  33946. var maxVector = null;
  33947. meshes.forEach(function (mesh, index, array) {
  33948. var boundingInfo = mesh.getBoundingInfo();
  33949. var boundingBox = boundingInfo.boundingBox;
  33950. if (!minVector || !maxVector) {
  33951. minVector = boundingBox.minimumWorld;
  33952. maxVector = boundingBox.maximumWorld;
  33953. }
  33954. else {
  33955. minVector.minimizeInPlace(boundingBox.minimumWorld);
  33956. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  33957. }
  33958. });
  33959. if (!minVector || !maxVector) {
  33960. return {
  33961. min: BABYLON.Vector3.Zero(),
  33962. max: BABYLON.Vector3.Zero()
  33963. };
  33964. }
  33965. return {
  33966. min: minVector,
  33967. max: maxVector
  33968. };
  33969. };
  33970. /**
  33971. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  33972. */
  33973. Mesh.Center = function (meshesOrMinMaxVector) {
  33974. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  33975. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  33976. };
  33977. /**
  33978. * Merge the array of meshes into a single mesh for performance reasons.
  33979. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  33980. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  33981. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  33982. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  33983. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  33984. */
  33985. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  33986. if (disposeSource === void 0) { disposeSource = true; }
  33987. var index;
  33988. if (!allow32BitsIndices) {
  33989. var totalVertices = 0;
  33990. // Counting vertices
  33991. for (index = 0; index < meshes.length; index++) {
  33992. if (meshes[index]) {
  33993. totalVertices += meshes[index].getTotalVertices();
  33994. if (totalVertices > 65536) {
  33995. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  33996. return null;
  33997. }
  33998. }
  33999. }
  34000. }
  34001. // Merge
  34002. var vertexData = null;
  34003. var otherVertexData;
  34004. var indiceArray = new Array();
  34005. var source = null;
  34006. for (index = 0; index < meshes.length; index++) {
  34007. if (meshes[index]) {
  34008. meshes[index].computeWorldMatrix(true);
  34009. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true);
  34010. otherVertexData.transform(meshes[index].getWorldMatrix());
  34011. if (vertexData) {
  34012. vertexData.merge(otherVertexData);
  34013. }
  34014. else {
  34015. vertexData = otherVertexData;
  34016. source = meshes[index];
  34017. }
  34018. if (subdivideWithSubMeshes) {
  34019. indiceArray.push(meshes[index].getTotalIndices());
  34020. }
  34021. }
  34022. }
  34023. source = source;
  34024. if (!meshSubclass) {
  34025. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34026. }
  34027. vertexData.applyToMesh(meshSubclass);
  34028. // Setting properties
  34029. meshSubclass.material = source.material;
  34030. meshSubclass.checkCollisions = source.checkCollisions;
  34031. // Cleaning
  34032. if (disposeSource) {
  34033. for (index = 0; index < meshes.length; index++) {
  34034. if (meshes[index]) {
  34035. meshes[index].dispose();
  34036. }
  34037. }
  34038. }
  34039. // Subdivide
  34040. if (subdivideWithSubMeshes) {
  34041. //-- Suppresions du submesh global
  34042. meshSubclass.releaseSubMeshes();
  34043. index = 0;
  34044. var offset = 0;
  34045. //-- aplique la subdivision en fonction du tableau d'indices
  34046. while (index < indiceArray.length) {
  34047. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34048. offset += indiceArray[index];
  34049. index++;
  34050. }
  34051. }
  34052. return meshSubclass;
  34053. };
  34054. // Consts
  34055. Mesh._FRONTSIDE = 0;
  34056. Mesh._BACKSIDE = 1;
  34057. Mesh._DOUBLESIDE = 2;
  34058. Mesh._DEFAULTSIDE = 0;
  34059. Mesh._NO_CAP = 0;
  34060. Mesh._CAP_START = 1;
  34061. Mesh._CAP_END = 2;
  34062. Mesh._CAP_ALL = 3;
  34063. return Mesh;
  34064. }(BABYLON.AbstractMesh));
  34065. BABYLON.Mesh = Mesh;
  34066. })(BABYLON || (BABYLON = {}));
  34067. //# sourceMappingURL=babylon.mesh.js.map
  34068. var BABYLON;
  34069. (function (BABYLON) {
  34070. var BaseSubMesh = /** @class */ (function () {
  34071. function BaseSubMesh() {
  34072. }
  34073. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34074. get: function () {
  34075. return this._materialEffect;
  34076. },
  34077. enumerable: true,
  34078. configurable: true
  34079. });
  34080. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34081. if (defines === void 0) { defines = null; }
  34082. if (this._materialEffect === effect) {
  34083. if (!effect) {
  34084. this._materialDefines = null;
  34085. }
  34086. return;
  34087. }
  34088. this._materialDefines = defines;
  34089. this._materialEffect = effect;
  34090. };
  34091. return BaseSubMesh;
  34092. }());
  34093. BABYLON.BaseSubMesh = BaseSubMesh;
  34094. var SubMesh = /** @class */ (function (_super) {
  34095. __extends(SubMesh, _super);
  34096. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34097. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34098. var _this = _super.call(this) || this;
  34099. _this.materialIndex = materialIndex;
  34100. _this.verticesStart = verticesStart;
  34101. _this.verticesCount = verticesCount;
  34102. _this.indexStart = indexStart;
  34103. _this.indexCount = indexCount;
  34104. _this._renderId = 0;
  34105. _this._mesh = mesh;
  34106. _this._renderingMesh = renderingMesh || mesh;
  34107. mesh.subMeshes.push(_this);
  34108. _this._trianglePlanes = [];
  34109. _this._id = mesh.subMeshes.length - 1;
  34110. if (createBoundingBox) {
  34111. _this.refreshBoundingInfo();
  34112. mesh.computeWorldMatrix(true);
  34113. }
  34114. return _this;
  34115. }
  34116. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34117. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34118. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34119. };
  34120. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34121. get: function () {
  34122. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34123. },
  34124. enumerable: true,
  34125. configurable: true
  34126. });
  34127. /**
  34128. * Returns the submesh BoudingInfo object.
  34129. */
  34130. SubMesh.prototype.getBoundingInfo = function () {
  34131. if (this.IsGlobal) {
  34132. return this._mesh.getBoundingInfo();
  34133. }
  34134. return this._boundingInfo;
  34135. };
  34136. /**
  34137. * Sets the submesh BoundingInfo.
  34138. * Return the SubMesh.
  34139. */
  34140. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34141. this._boundingInfo = boundingInfo;
  34142. return this;
  34143. };
  34144. /**
  34145. * Returns the mesh of the current submesh.
  34146. */
  34147. SubMesh.prototype.getMesh = function () {
  34148. return this._mesh;
  34149. };
  34150. /**
  34151. * Returns the rendering mesh of the submesh.
  34152. */
  34153. SubMesh.prototype.getRenderingMesh = function () {
  34154. return this._renderingMesh;
  34155. };
  34156. /**
  34157. * Returns the submesh material.
  34158. */
  34159. SubMesh.prototype.getMaterial = function () {
  34160. var rootMaterial = this._renderingMesh.material;
  34161. if (rootMaterial === null || rootMaterial === undefined) {
  34162. return this._mesh.getScene().defaultMaterial;
  34163. }
  34164. else if (rootMaterial.getSubMaterial) {
  34165. var multiMaterial = rootMaterial;
  34166. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34167. if (this._currentMaterial !== effectiveMaterial) {
  34168. this._currentMaterial = effectiveMaterial;
  34169. this._materialDefines = null;
  34170. }
  34171. return effectiveMaterial;
  34172. }
  34173. return rootMaterial;
  34174. };
  34175. // Methods
  34176. /**
  34177. * Sets a new updated BoundingInfo object to the submesh.
  34178. * Returns the SubMesh.
  34179. */
  34180. SubMesh.prototype.refreshBoundingInfo = function () {
  34181. this._lastColliderWorldVertices = null;
  34182. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34183. return this;
  34184. }
  34185. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34186. if (!data) {
  34187. this._boundingInfo = this._mesh.getBoundingInfo();
  34188. return this;
  34189. }
  34190. var indices = this._renderingMesh.getIndices();
  34191. var extend;
  34192. //is this the only submesh?
  34193. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34194. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34195. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34196. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34197. }
  34198. else {
  34199. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34200. }
  34201. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34202. return this;
  34203. };
  34204. SubMesh.prototype._checkCollision = function (collider) {
  34205. var boundingInfo = this.getBoundingInfo();
  34206. return boundingInfo._checkCollision(collider);
  34207. };
  34208. /**
  34209. * Updates the submesh BoundingInfo.
  34210. * Returns the Submesh.
  34211. */
  34212. SubMesh.prototype.updateBoundingInfo = function (world) {
  34213. var boundingInfo = this.getBoundingInfo();
  34214. if (!boundingInfo) {
  34215. this.refreshBoundingInfo();
  34216. boundingInfo = this.getBoundingInfo();
  34217. }
  34218. boundingInfo.update(world);
  34219. return this;
  34220. };
  34221. /**
  34222. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34223. * Boolean returned.
  34224. */
  34225. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34226. var boundingInfo = this.getBoundingInfo();
  34227. if (!boundingInfo) {
  34228. return false;
  34229. }
  34230. return boundingInfo.isInFrustum(frustumPlanes);
  34231. };
  34232. /**
  34233. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34234. * Boolean returned.
  34235. */
  34236. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34237. var boundingInfo = this.getBoundingInfo();
  34238. if (!boundingInfo) {
  34239. return false;
  34240. }
  34241. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34242. };
  34243. /**
  34244. * Renders the submesh.
  34245. * Returns it.
  34246. */
  34247. SubMesh.prototype.render = function (enableAlphaMode) {
  34248. this._renderingMesh.render(this, enableAlphaMode);
  34249. return this;
  34250. };
  34251. /**
  34252. * Returns a new Index Buffer.
  34253. * Type returned : WebGLBuffer.
  34254. */
  34255. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34256. if (!this._linesIndexBuffer) {
  34257. var linesIndices = [];
  34258. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34259. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34260. }
  34261. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34262. this.linesIndexCount = linesIndices.length;
  34263. }
  34264. return this._linesIndexBuffer;
  34265. };
  34266. /**
  34267. * True is the passed Ray intersects the submesh bounding box.
  34268. * Boolean returned.
  34269. */
  34270. SubMesh.prototype.canIntersects = function (ray) {
  34271. var boundingInfo = this.getBoundingInfo();
  34272. if (!boundingInfo) {
  34273. return false;
  34274. }
  34275. return ray.intersectsBox(boundingInfo.boundingBox);
  34276. };
  34277. /**
  34278. * Returns an object IntersectionInfo.
  34279. */
  34280. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34281. var intersectInfo = null;
  34282. var material = this.getMaterial();
  34283. if (!material) {
  34284. return null;
  34285. }
  34286. switch (material.fillMode) {
  34287. case BABYLON.Material.PointListDrawMode:
  34288. case BABYLON.Material.LineListDrawMode:
  34289. case BABYLON.Material.LineLoopDrawMode:
  34290. case BABYLON.Material.LineStripDrawMode:
  34291. case BABYLON.Material.TriangleFanDrawMode:
  34292. case BABYLON.Material.TriangleStripDrawMode:
  34293. return null;
  34294. }
  34295. // LineMesh first as it's also a Mesh...
  34296. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34297. var lineMesh = this._mesh;
  34298. // Line test
  34299. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34300. var p0 = positions[indices[index]];
  34301. var p1 = positions[indices[index + 1]];
  34302. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34303. if (length < 0) {
  34304. continue;
  34305. }
  34306. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34307. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34308. if (fastCheck) {
  34309. break;
  34310. }
  34311. }
  34312. }
  34313. }
  34314. else {
  34315. // Triangles test
  34316. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34317. var p0 = positions[indices[index]];
  34318. var p1 = positions[indices[index + 1]];
  34319. var p2 = positions[indices[index + 2]];
  34320. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34321. if (currentIntersectInfo) {
  34322. if (currentIntersectInfo.distance < 0) {
  34323. continue;
  34324. }
  34325. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34326. intersectInfo = currentIntersectInfo;
  34327. intersectInfo.faceId = index / 3;
  34328. if (fastCheck) {
  34329. break;
  34330. }
  34331. }
  34332. }
  34333. }
  34334. }
  34335. return intersectInfo;
  34336. };
  34337. SubMesh.prototype._rebuild = function () {
  34338. if (this._linesIndexBuffer) {
  34339. this._linesIndexBuffer = null;
  34340. }
  34341. };
  34342. // Clone
  34343. /**
  34344. * Creates a new Submesh from the passed Mesh.
  34345. */
  34346. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34347. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34348. if (!this.IsGlobal) {
  34349. var boundingInfo = this.getBoundingInfo();
  34350. if (!boundingInfo) {
  34351. return result;
  34352. }
  34353. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34354. }
  34355. return result;
  34356. };
  34357. // Dispose
  34358. /**
  34359. * Disposes the Submesh.
  34360. * Returns nothing.
  34361. */
  34362. SubMesh.prototype.dispose = function () {
  34363. if (this._linesIndexBuffer) {
  34364. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34365. this._linesIndexBuffer = null;
  34366. }
  34367. // Remove from mesh
  34368. var index = this._mesh.subMeshes.indexOf(this);
  34369. this._mesh.subMeshes.splice(index, 1);
  34370. };
  34371. // Statics
  34372. /**
  34373. * Creates a new Submesh from the passed parameters :
  34374. * - materialIndex (integer) : the index of the main mesh material.
  34375. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34376. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34377. * - mesh (Mesh) : the main mesh to create the submesh from.
  34378. * - renderingMesh (optional Mesh) : rendering mesh.
  34379. */
  34380. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34381. var minVertexIndex = Number.MAX_VALUE;
  34382. var maxVertexIndex = -Number.MAX_VALUE;
  34383. renderingMesh = (renderingMesh || mesh);
  34384. var indices = renderingMesh.getIndices();
  34385. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34386. var vertexIndex = indices[index];
  34387. if (vertexIndex < minVertexIndex)
  34388. minVertexIndex = vertexIndex;
  34389. if (vertexIndex > maxVertexIndex)
  34390. maxVertexIndex = vertexIndex;
  34391. }
  34392. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34393. };
  34394. return SubMesh;
  34395. }(BaseSubMesh));
  34396. BABYLON.SubMesh = SubMesh;
  34397. })(BABYLON || (BABYLON = {}));
  34398. //# sourceMappingURL=babylon.subMesh.js.map
  34399. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34400. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34401. s = arguments[i];
  34402. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34403. t[p] = s[p];
  34404. }
  34405. return t;
  34406. };
  34407. var BABYLON;
  34408. (function (BABYLON) {
  34409. /**
  34410. * Manages the defines for the Material
  34411. */
  34412. var MaterialDefines = /** @class */ (function () {
  34413. function MaterialDefines() {
  34414. this._isDirty = true;
  34415. /** @hidden */
  34416. this._areLightsDirty = true;
  34417. /** @hidden */
  34418. this._areAttributesDirty = true;
  34419. /** @hidden */
  34420. this._areTexturesDirty = true;
  34421. /** @hidden */
  34422. this._areFresnelDirty = true;
  34423. /** @hidden */
  34424. this._areMiscDirty = true;
  34425. /** @hidden */
  34426. this._areImageProcessingDirty = true;
  34427. /** @hidden */
  34428. this._normals = false;
  34429. /** @hidden */
  34430. this._uvs = false;
  34431. /** @hidden */
  34432. this._needNormals = false;
  34433. /** @hidden */
  34434. this._needUVs = false;
  34435. }
  34436. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  34437. /**
  34438. * Specifies if the material needs to be re-calculated
  34439. */
  34440. get: function () {
  34441. return this._isDirty;
  34442. },
  34443. enumerable: true,
  34444. configurable: true
  34445. });
  34446. /**
  34447. * Marks the material to indicate that it has been re-calculated
  34448. */
  34449. MaterialDefines.prototype.markAsProcessed = function () {
  34450. this._isDirty = false;
  34451. this._areAttributesDirty = false;
  34452. this._areTexturesDirty = false;
  34453. this._areFresnelDirty = false;
  34454. this._areLightsDirty = false;
  34455. this._areMiscDirty = false;
  34456. this._areImageProcessingDirty = false;
  34457. };
  34458. /**
  34459. * Marks the material to indicate that it needs to be re-calculated
  34460. */
  34461. MaterialDefines.prototype.markAsUnprocessed = function () {
  34462. this._isDirty = true;
  34463. };
  34464. /**
  34465. * Marks the material to indicate all of its defines need to be re-calculated
  34466. */
  34467. MaterialDefines.prototype.markAllAsDirty = function () {
  34468. this._areTexturesDirty = true;
  34469. this._areAttributesDirty = true;
  34470. this._areLightsDirty = true;
  34471. this._areFresnelDirty = true;
  34472. this._areMiscDirty = true;
  34473. this._areImageProcessingDirty = true;
  34474. this._isDirty = true;
  34475. };
  34476. /**
  34477. * Marks the material to indicate that image processing needs to be re-calculated
  34478. */
  34479. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  34480. this._areImageProcessingDirty = true;
  34481. this._isDirty = true;
  34482. };
  34483. /**
  34484. * Marks the material to indicate the lights need to be re-calculated
  34485. */
  34486. MaterialDefines.prototype.markAsLightDirty = function () {
  34487. this._areLightsDirty = true;
  34488. this._isDirty = true;
  34489. };
  34490. /**
  34491. * Marks the attribute state as changed
  34492. */
  34493. MaterialDefines.prototype.markAsAttributesDirty = function () {
  34494. this._areAttributesDirty = true;
  34495. this._isDirty = true;
  34496. };
  34497. /**
  34498. * Marks the texture state as changed
  34499. */
  34500. MaterialDefines.prototype.markAsTexturesDirty = function () {
  34501. this._areTexturesDirty = true;
  34502. this._isDirty = true;
  34503. };
  34504. /**
  34505. * Marks the fresnel state as changed
  34506. */
  34507. MaterialDefines.prototype.markAsFresnelDirty = function () {
  34508. this._areFresnelDirty = true;
  34509. this._isDirty = true;
  34510. };
  34511. /**
  34512. * Marks the misc state as changed
  34513. */
  34514. MaterialDefines.prototype.markAsMiscDirty = function () {
  34515. this._areMiscDirty = true;
  34516. this._isDirty = true;
  34517. };
  34518. /**
  34519. * Rebuilds the material defines
  34520. */
  34521. MaterialDefines.prototype.rebuild = function () {
  34522. if (this._keys) {
  34523. delete this._keys;
  34524. }
  34525. this._keys = [];
  34526. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  34527. var key = _a[_i];
  34528. if (key[0] === "_") {
  34529. continue;
  34530. }
  34531. this._keys.push(key);
  34532. }
  34533. };
  34534. /**
  34535. * Specifies if two material defines are equal
  34536. * @param other - A material define instance to compare to
  34537. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  34538. */
  34539. MaterialDefines.prototype.isEqual = function (other) {
  34540. if (this._keys.length !== other._keys.length) {
  34541. return false;
  34542. }
  34543. for (var index = 0; index < this._keys.length; index++) {
  34544. var prop = this._keys[index];
  34545. if (this[prop] !== other[prop]) {
  34546. return false;
  34547. }
  34548. }
  34549. return true;
  34550. };
  34551. /**
  34552. * Clones this instance's defines to another instance
  34553. * @param other - material defines to clone values to
  34554. */
  34555. MaterialDefines.prototype.cloneTo = function (other) {
  34556. if (this._keys.length !== other._keys.length) {
  34557. other._keys = this._keys.slice(0);
  34558. }
  34559. for (var index = 0; index < this._keys.length; index++) {
  34560. var prop = this._keys[index];
  34561. other[prop] = this[prop];
  34562. }
  34563. };
  34564. /**
  34565. * Resets the material define values
  34566. */
  34567. MaterialDefines.prototype.reset = function () {
  34568. for (var index = 0; index < this._keys.length; index++) {
  34569. var prop = this._keys[index];
  34570. var type = typeof this[prop];
  34571. switch (type) {
  34572. case "number":
  34573. this[prop] = 0;
  34574. break;
  34575. case "string":
  34576. this[prop] = "";
  34577. break;
  34578. default:
  34579. this[prop] = false;
  34580. break;
  34581. }
  34582. }
  34583. };
  34584. /**
  34585. * Converts the material define values to a string
  34586. * @returns - String of material define information
  34587. */
  34588. MaterialDefines.prototype.toString = function () {
  34589. var result = "";
  34590. for (var index = 0; index < this._keys.length; index++) {
  34591. var prop = this._keys[index];
  34592. var value = this[prop];
  34593. var type = typeof value;
  34594. switch (type) {
  34595. case "number":
  34596. case "string":
  34597. result += "#define " + prop + " " + value + "\n";
  34598. break;
  34599. default:
  34600. if (value) {
  34601. result += "#define " + prop + "\n";
  34602. }
  34603. break;
  34604. }
  34605. }
  34606. return result;
  34607. };
  34608. return MaterialDefines;
  34609. }());
  34610. BABYLON.MaterialDefines = MaterialDefines;
  34611. /**
  34612. * Base class for the main features of a material in Babylon.js
  34613. */
  34614. var Material = /** @class */ (function () {
  34615. /**
  34616. * Creates a material instance
  34617. * @param name defines the name of the material
  34618. * @param scene defines the scene to reference
  34619. * @param doNotAdd specifies if the material should be added to the scene
  34620. */
  34621. function Material(name, scene, doNotAdd) {
  34622. /**
  34623. * Specifies if the ready state should be checked on each call
  34624. */
  34625. this.checkReadyOnEveryCall = false;
  34626. /**
  34627. * Specifies if the ready state should be checked once
  34628. */
  34629. this.checkReadyOnlyOnce = false;
  34630. /**
  34631. * The state of the material
  34632. */
  34633. this.state = "";
  34634. /**
  34635. * The alpha value of the material
  34636. */
  34637. this._alpha = 1.0;
  34638. /**
  34639. * Specifies if back face culling is enabled
  34640. */
  34641. this._backFaceCulling = true;
  34642. /**
  34643. * Specifies if the material should be serialized
  34644. */
  34645. this.doNotSerialize = false;
  34646. /**
  34647. * Specifies if the effect should be stored on sub meshes
  34648. */
  34649. this.storeEffectOnSubMeshes = false;
  34650. /**
  34651. * An event triggered when the material is disposed
  34652. */
  34653. this.onDisposeObservable = new BABYLON.Observable();
  34654. /**
  34655. * An event triggered when the material is bound
  34656. */
  34657. this.onBindObservable = new BABYLON.Observable();
  34658. /**
  34659. * An event triggered when the material is unbound
  34660. */
  34661. this.onUnBindObservable = new BABYLON.Observable();
  34662. /**
  34663. * Stores the value of the alpha mode
  34664. */
  34665. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  34666. /**
  34667. * Stores the state of the need depth pre-pass value
  34668. */
  34669. this._needDepthPrePass = false;
  34670. /**
  34671. * Specifies if depth writing should be disabled
  34672. */
  34673. this.disableDepthWrite = false;
  34674. /**
  34675. * Specifies if depth writing should be forced
  34676. */
  34677. this.forceDepthWrite = false;
  34678. /**
  34679. * Specifies if there should be a separate pass for culling
  34680. */
  34681. this.separateCullingPass = false;
  34682. /**
  34683. * Stores the state specifing if fog should be enabled
  34684. */
  34685. this._fogEnabled = true;
  34686. /**
  34687. * Stores the size of points
  34688. */
  34689. this.pointSize = 1.0;
  34690. /**
  34691. * Stores the z offset value
  34692. */
  34693. this.zOffset = 0;
  34694. /**
  34695. * Specifies if the material was previously ready
  34696. */
  34697. this._wasPreviouslyReady = false;
  34698. /**
  34699. * Stores the fill mode state
  34700. */
  34701. this._fillMode = Material.TriangleFillMode;
  34702. this.name = name;
  34703. this.id = name || BABYLON.Tools.RandomId();
  34704. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  34705. if (this._scene.useRightHandedSystem) {
  34706. this.sideOrientation = Material.ClockWiseSideOrientation;
  34707. }
  34708. else {
  34709. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  34710. }
  34711. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  34712. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  34713. if (!doNotAdd) {
  34714. this._scene.materials.push(this);
  34715. }
  34716. }
  34717. Object.defineProperty(Material, "TriangleFillMode", {
  34718. /**
  34719. * Returns the triangle fill mode
  34720. */
  34721. get: function () {
  34722. return Material._TriangleFillMode;
  34723. },
  34724. enumerable: true,
  34725. configurable: true
  34726. });
  34727. Object.defineProperty(Material, "WireFrameFillMode", {
  34728. /**
  34729. * Returns the wireframe mode
  34730. */
  34731. get: function () {
  34732. return Material._WireFrameFillMode;
  34733. },
  34734. enumerable: true,
  34735. configurable: true
  34736. });
  34737. Object.defineProperty(Material, "PointFillMode", {
  34738. /**
  34739. * Returns the point fill mode
  34740. */
  34741. get: function () {
  34742. return Material._PointFillMode;
  34743. },
  34744. enumerable: true,
  34745. configurable: true
  34746. });
  34747. Object.defineProperty(Material, "PointListDrawMode", {
  34748. /**
  34749. * Returns the point list draw mode
  34750. */
  34751. get: function () {
  34752. return Material._PointListDrawMode;
  34753. },
  34754. enumerable: true,
  34755. configurable: true
  34756. });
  34757. Object.defineProperty(Material, "LineListDrawMode", {
  34758. /**
  34759. * Returns the line list draw mode
  34760. */
  34761. get: function () {
  34762. return Material._LineListDrawMode;
  34763. },
  34764. enumerable: true,
  34765. configurable: true
  34766. });
  34767. Object.defineProperty(Material, "LineLoopDrawMode", {
  34768. /**
  34769. * Returns the line loop draw mode
  34770. */
  34771. get: function () {
  34772. return Material._LineLoopDrawMode;
  34773. },
  34774. enumerable: true,
  34775. configurable: true
  34776. });
  34777. Object.defineProperty(Material, "LineStripDrawMode", {
  34778. /**
  34779. * Returns the line strip draw mode
  34780. */
  34781. get: function () {
  34782. return Material._LineStripDrawMode;
  34783. },
  34784. enumerable: true,
  34785. configurable: true
  34786. });
  34787. Object.defineProperty(Material, "TriangleStripDrawMode", {
  34788. /**
  34789. * Returns the triangle strip draw mode
  34790. */
  34791. get: function () {
  34792. return Material._TriangleStripDrawMode;
  34793. },
  34794. enumerable: true,
  34795. configurable: true
  34796. });
  34797. Object.defineProperty(Material, "TriangleFanDrawMode", {
  34798. /**
  34799. * Returns the triangle fan draw mode
  34800. */
  34801. get: function () {
  34802. return Material._TriangleFanDrawMode;
  34803. },
  34804. enumerable: true,
  34805. configurable: true
  34806. });
  34807. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  34808. /**
  34809. * Returns the clock-wise side orientation
  34810. */
  34811. get: function () {
  34812. return Material._ClockWiseSideOrientation;
  34813. },
  34814. enumerable: true,
  34815. configurable: true
  34816. });
  34817. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  34818. /**
  34819. * Returns the counter clock-wise side orientation
  34820. */
  34821. get: function () {
  34822. return Material._CounterClockWiseSideOrientation;
  34823. },
  34824. enumerable: true,
  34825. configurable: true
  34826. });
  34827. Object.defineProperty(Material, "TextureDirtyFlag", {
  34828. /**
  34829. * Returns the dirty texture flag value
  34830. */
  34831. get: function () {
  34832. return Material._TextureDirtyFlag;
  34833. },
  34834. enumerable: true,
  34835. configurable: true
  34836. });
  34837. Object.defineProperty(Material, "LightDirtyFlag", {
  34838. /**
  34839. * Returns the dirty light flag value
  34840. */
  34841. get: function () {
  34842. return Material._LightDirtyFlag;
  34843. },
  34844. enumerable: true,
  34845. configurable: true
  34846. });
  34847. Object.defineProperty(Material, "FresnelDirtyFlag", {
  34848. /**
  34849. * Returns the dirty fresnel flag value
  34850. */
  34851. get: function () {
  34852. return Material._FresnelDirtyFlag;
  34853. },
  34854. enumerable: true,
  34855. configurable: true
  34856. });
  34857. Object.defineProperty(Material, "AttributesDirtyFlag", {
  34858. /**
  34859. * Returns the dirty attributes flag value
  34860. */
  34861. get: function () {
  34862. return Material._AttributesDirtyFlag;
  34863. },
  34864. enumerable: true,
  34865. configurable: true
  34866. });
  34867. Object.defineProperty(Material, "MiscDirtyFlag", {
  34868. /**
  34869. * Returns the dirty misc flag value
  34870. */
  34871. get: function () {
  34872. return Material._MiscDirtyFlag;
  34873. },
  34874. enumerable: true,
  34875. configurable: true
  34876. });
  34877. Object.defineProperty(Material.prototype, "alpha", {
  34878. /**
  34879. * Gets the alpha value of the material
  34880. */
  34881. get: function () {
  34882. return this._alpha;
  34883. },
  34884. /**
  34885. * Sets the alpha value of the material
  34886. */
  34887. set: function (value) {
  34888. if (this._alpha === value) {
  34889. return;
  34890. }
  34891. this._alpha = value;
  34892. this.markAsDirty(Material.MiscDirtyFlag);
  34893. },
  34894. enumerable: true,
  34895. configurable: true
  34896. });
  34897. Object.defineProperty(Material.prototype, "backFaceCulling", {
  34898. /**
  34899. * Gets the back-face culling state
  34900. */
  34901. get: function () {
  34902. return this._backFaceCulling;
  34903. },
  34904. /**
  34905. * Sets the back-face culling state
  34906. */
  34907. set: function (value) {
  34908. if (this._backFaceCulling === value) {
  34909. return;
  34910. }
  34911. this._backFaceCulling = value;
  34912. this.markAsDirty(Material.TextureDirtyFlag);
  34913. },
  34914. enumerable: true,
  34915. configurable: true
  34916. });
  34917. Object.defineProperty(Material.prototype, "onDispose", {
  34918. /**
  34919. * Called during a dispose event
  34920. */
  34921. set: function (callback) {
  34922. if (this._onDisposeObserver) {
  34923. this.onDisposeObservable.remove(this._onDisposeObserver);
  34924. }
  34925. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  34926. },
  34927. enumerable: true,
  34928. configurable: true
  34929. });
  34930. Object.defineProperty(Material.prototype, "onBind", {
  34931. /**
  34932. * Called during a bind event
  34933. */
  34934. set: function (callback) {
  34935. if (this._onBindObserver) {
  34936. this.onBindObservable.remove(this._onBindObserver);
  34937. }
  34938. this._onBindObserver = this.onBindObservable.add(callback);
  34939. },
  34940. enumerable: true,
  34941. configurable: true
  34942. });
  34943. Object.defineProperty(Material.prototype, "alphaMode", {
  34944. /**
  34945. * Gets the value of the alpha mode
  34946. */
  34947. get: function () {
  34948. return this._alphaMode;
  34949. },
  34950. /**
  34951. * Sets the value of the alpha mode.
  34952. *
  34953. * | Value | Type | Description |
  34954. * | --- | --- | --- |
  34955. * | 0 | ALPHA_DISABLE | |
  34956. * | 1 | ALPHA_ADD | |
  34957. * | 2 | ALPHA_COMBINE | |
  34958. * | 3 | ALPHA_SUBTRACT | |
  34959. * | 4 | ALPHA_MULTIPLY | |
  34960. * | 5 | ALPHA_MAXIMIZED | |
  34961. * | 6 | ALPHA_ONEONE | |
  34962. * | 7 | ALPHA_PREMULTIPLIED | |
  34963. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  34964. * | 9 | ALPHA_INTERPOLATE | |
  34965. * | 10 | ALPHA_SCREENMODE | |
  34966. *
  34967. */
  34968. set: function (value) {
  34969. if (this._alphaMode === value) {
  34970. return;
  34971. }
  34972. this._alphaMode = value;
  34973. this.markAsDirty(Material.TextureDirtyFlag);
  34974. },
  34975. enumerable: true,
  34976. configurable: true
  34977. });
  34978. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  34979. /**
  34980. * Gets the depth pre-pass value
  34981. */
  34982. get: function () {
  34983. return this._needDepthPrePass;
  34984. },
  34985. /**
  34986. * Sets the need depth pre-pass value
  34987. */
  34988. set: function (value) {
  34989. if (this._needDepthPrePass === value) {
  34990. return;
  34991. }
  34992. this._needDepthPrePass = value;
  34993. if (this._needDepthPrePass) {
  34994. this.checkReadyOnEveryCall = true;
  34995. }
  34996. },
  34997. enumerable: true,
  34998. configurable: true
  34999. });
  35000. Object.defineProperty(Material.prototype, "fogEnabled", {
  35001. /**
  35002. * Gets the value of the fog enabled state
  35003. */
  35004. get: function () {
  35005. return this._fogEnabled;
  35006. },
  35007. /**
  35008. * Sets the state for enabling fog
  35009. */
  35010. set: function (value) {
  35011. if (this._fogEnabled === value) {
  35012. return;
  35013. }
  35014. this._fogEnabled = value;
  35015. this.markAsDirty(Material.MiscDirtyFlag);
  35016. },
  35017. enumerable: true,
  35018. configurable: true
  35019. });
  35020. Object.defineProperty(Material.prototype, "wireframe", {
  35021. /**
  35022. * Gets a value specifying if wireframe mode is enabled
  35023. */
  35024. get: function () {
  35025. switch (this._fillMode) {
  35026. case Material.WireFrameFillMode:
  35027. case Material.LineListDrawMode:
  35028. case Material.LineLoopDrawMode:
  35029. case Material.LineStripDrawMode:
  35030. return true;
  35031. }
  35032. return this._scene.forceWireframe;
  35033. },
  35034. /**
  35035. * Sets the state of wireframe mode
  35036. */
  35037. set: function (value) {
  35038. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35039. },
  35040. enumerable: true,
  35041. configurable: true
  35042. });
  35043. Object.defineProperty(Material.prototype, "pointsCloud", {
  35044. /**
  35045. * Gets the value specifying if point clouds are enabled
  35046. */
  35047. get: function () {
  35048. switch (this._fillMode) {
  35049. case Material.PointFillMode:
  35050. case Material.PointListDrawMode:
  35051. return true;
  35052. }
  35053. return this._scene.forcePointsCloud;
  35054. },
  35055. /**
  35056. * Sets the state of point cloud mode
  35057. */
  35058. set: function (value) {
  35059. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35060. },
  35061. enumerable: true,
  35062. configurable: true
  35063. });
  35064. Object.defineProperty(Material.prototype, "fillMode", {
  35065. /**
  35066. * Gets the material fill mode
  35067. */
  35068. get: function () {
  35069. return this._fillMode;
  35070. },
  35071. /**
  35072. * Sets the material fill mode
  35073. */
  35074. set: function (value) {
  35075. if (this._fillMode === value) {
  35076. return;
  35077. }
  35078. this._fillMode = value;
  35079. this.markAsDirty(Material.MiscDirtyFlag);
  35080. },
  35081. enumerable: true,
  35082. configurable: true
  35083. });
  35084. /**
  35085. * Returns a string representation of the current material
  35086. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35087. * @returns a string with material information
  35088. */
  35089. Material.prototype.toString = function (fullDetails) {
  35090. var ret = "Name: " + this.name;
  35091. if (fullDetails) {
  35092. }
  35093. return ret;
  35094. };
  35095. /**
  35096. * Gets the class name of the material
  35097. * @returns a string with the class name of the material
  35098. */
  35099. Material.prototype.getClassName = function () {
  35100. return "Material";
  35101. };
  35102. Object.defineProperty(Material.prototype, "isFrozen", {
  35103. /**
  35104. * Specifies if updates for the material been locked
  35105. */
  35106. get: function () {
  35107. return this.checkReadyOnlyOnce;
  35108. },
  35109. enumerable: true,
  35110. configurable: true
  35111. });
  35112. /**
  35113. * Locks updates for the material
  35114. */
  35115. Material.prototype.freeze = function () {
  35116. this.checkReadyOnlyOnce = true;
  35117. };
  35118. /**
  35119. * Unlocks updates for the material
  35120. */
  35121. Material.prototype.unfreeze = function () {
  35122. this.checkReadyOnlyOnce = false;
  35123. };
  35124. /**
  35125. * Specifies if the material is ready to be used
  35126. * @param mesh defines the mesh to check
  35127. * @param useInstances specifies if instances should be used
  35128. * @returns a boolean indicating if the material is ready to be used
  35129. */
  35130. Material.prototype.isReady = function (mesh, useInstances) {
  35131. return true;
  35132. };
  35133. /**
  35134. * Specifies that the submesh is ready to be used
  35135. * @param mesh defines the mesh to check
  35136. * @param subMesh defines which submesh to check
  35137. * @param useInstances specifies that instances should be used
  35138. * @returns a boolean indicating that the submesh is ready or not
  35139. */
  35140. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35141. return false;
  35142. };
  35143. /**
  35144. * Returns the material effect
  35145. * @returns the effect associated with the material
  35146. */
  35147. Material.prototype.getEffect = function () {
  35148. return this._effect;
  35149. };
  35150. /**
  35151. * Returns the current scene
  35152. * @returns a Scene
  35153. */
  35154. Material.prototype.getScene = function () {
  35155. return this._scene;
  35156. };
  35157. /**
  35158. * Specifies if the material will require alpha blending
  35159. * @returns a boolean specifying if alpha blending is needed
  35160. */
  35161. Material.prototype.needAlphaBlending = function () {
  35162. return (this.alpha < 1.0);
  35163. };
  35164. /**
  35165. * Specifies if the mesh will require alpha blending
  35166. * @param mesh defines the mesh to check
  35167. * @returns a boolean specifying if alpha blending is needed for the mesh
  35168. */
  35169. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35170. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35171. };
  35172. /**
  35173. * Specifies if this material should be rendered in alpha test mode
  35174. * @returns a boolean specifying if an alpha test is needed.
  35175. */
  35176. Material.prototype.needAlphaTesting = function () {
  35177. return false;
  35178. };
  35179. /**
  35180. * Gets the texture used for the alpha test
  35181. * @returns the texture to use for alpha testing
  35182. */
  35183. Material.prototype.getAlphaTestTexture = function () {
  35184. return null;
  35185. };
  35186. /**
  35187. * Marks the material to indicate that it needs to be re-calculated
  35188. */
  35189. Material.prototype.markDirty = function () {
  35190. this._wasPreviouslyReady = false;
  35191. };
  35192. /** @hidden */
  35193. Material.prototype._preBind = function (effect, overrideOrientation) {
  35194. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35195. var engine = this._scene.getEngine();
  35196. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35197. var reverse = orientation === Material.ClockWiseSideOrientation;
  35198. engine.enableEffect(effect ? effect : this._effect);
  35199. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35200. return reverse;
  35201. };
  35202. /**
  35203. * Binds the material to the mesh
  35204. * @param world defines the world transformation matrix
  35205. * @param mesh defines the mesh to bind the material to
  35206. */
  35207. Material.prototype.bind = function (world, mesh) {
  35208. };
  35209. /**
  35210. * Binds the submesh to the material
  35211. * @param world defines the world transformation matrix
  35212. * @param mesh defines the mesh containing the submesh
  35213. * @param subMesh defines the submesh to bind the material to
  35214. */
  35215. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35216. };
  35217. /**
  35218. * Binds the world matrix to the material
  35219. * @param world defines the world transformation matrix
  35220. */
  35221. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35222. };
  35223. /**
  35224. * Binds the scene's uniform buffer to the effect.
  35225. * @param effect defines the effect to bind to the scene uniform buffer
  35226. * @param sceneUbo defines the uniform buffer storing scene data
  35227. */
  35228. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35229. sceneUbo.bindToEffect(effect, "Scene");
  35230. };
  35231. /**
  35232. * Binds the view matrix to the effect
  35233. * @param effect defines the effect to bind the view matrix to
  35234. */
  35235. Material.prototype.bindView = function (effect) {
  35236. if (!this._useUBO) {
  35237. effect.setMatrix("view", this.getScene().getViewMatrix());
  35238. }
  35239. else {
  35240. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35241. }
  35242. };
  35243. /**
  35244. * Binds the view projection matrix to the effect
  35245. * @param effect defines the effect to bind the view projection matrix to
  35246. */
  35247. Material.prototype.bindViewProjection = function (effect) {
  35248. if (!this._useUBO) {
  35249. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35250. }
  35251. else {
  35252. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35253. }
  35254. };
  35255. /**
  35256. * Specifies if material alpha testing should be turned on for the mesh
  35257. * @param mesh defines the mesh to check
  35258. */
  35259. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35260. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35261. };
  35262. /**
  35263. * Processes to execute after binding the material to a mesh
  35264. * @param mesh defines the rendered mesh
  35265. */
  35266. Material.prototype._afterBind = function (mesh) {
  35267. this._scene._cachedMaterial = this;
  35268. if (mesh) {
  35269. this._scene._cachedVisibility = mesh.visibility;
  35270. }
  35271. else {
  35272. this._scene._cachedVisibility = 1;
  35273. }
  35274. if (mesh) {
  35275. this.onBindObservable.notifyObservers(mesh);
  35276. }
  35277. if (this.disableDepthWrite) {
  35278. var engine = this._scene.getEngine();
  35279. this._cachedDepthWriteState = engine.getDepthWrite();
  35280. engine.setDepthWrite(false);
  35281. }
  35282. };
  35283. /**
  35284. * Unbinds the material from the mesh
  35285. */
  35286. Material.prototype.unbind = function () {
  35287. this.onUnBindObservable.notifyObservers(this);
  35288. if (this.disableDepthWrite) {
  35289. var engine = this._scene.getEngine();
  35290. engine.setDepthWrite(this._cachedDepthWriteState);
  35291. }
  35292. };
  35293. /**
  35294. * Gets the active textures from the material
  35295. * @returns an array of textures
  35296. */
  35297. Material.prototype.getActiveTextures = function () {
  35298. return [];
  35299. };
  35300. /**
  35301. * Specifies if the material uses a texture
  35302. * @param texture defines the texture to check against the material
  35303. * @returns a boolean specifying if the material uses the texture
  35304. */
  35305. Material.prototype.hasTexture = function (texture) {
  35306. return false;
  35307. };
  35308. /**
  35309. * Makes a duplicate of the material, and gives it a new name
  35310. * @param name defines the new name for the duplicated material
  35311. * @returns the cloned material
  35312. */
  35313. Material.prototype.clone = function (name) {
  35314. return null;
  35315. };
  35316. /**
  35317. * Gets the meshes bound to the material
  35318. * @returns an array of meshes bound to the material
  35319. */
  35320. Material.prototype.getBindedMeshes = function () {
  35321. var result = new Array();
  35322. for (var index = 0; index < this._scene.meshes.length; index++) {
  35323. var mesh = this._scene.meshes[index];
  35324. if (mesh.material === this) {
  35325. result.push(mesh);
  35326. }
  35327. }
  35328. return result;
  35329. };
  35330. /**
  35331. * Force shader compilation
  35332. * @param mesh defines the mesh associated with this material
  35333. * @param onCompiled defines a function to execute once the material is compiled
  35334. * @param options defines the options to configure the compilation
  35335. */
  35336. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35337. var _this = this;
  35338. var localOptions = __assign({ clipPlane: false }, options);
  35339. var subMesh = new BABYLON.BaseSubMesh();
  35340. var scene = this.getScene();
  35341. var checkReady = function () {
  35342. if (!_this._scene || !_this._scene.getEngine()) {
  35343. return;
  35344. }
  35345. if (subMesh._materialDefines) {
  35346. subMesh._materialDefines._renderId = -1;
  35347. }
  35348. var clipPlaneState = scene.clipPlane;
  35349. if (localOptions.clipPlane) {
  35350. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35351. }
  35352. if (_this.storeEffectOnSubMeshes) {
  35353. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35354. if (onCompiled) {
  35355. onCompiled(_this);
  35356. }
  35357. }
  35358. else {
  35359. setTimeout(checkReady, 16);
  35360. }
  35361. }
  35362. else {
  35363. if (_this.isReady(mesh)) {
  35364. if (onCompiled) {
  35365. onCompiled(_this);
  35366. }
  35367. }
  35368. else {
  35369. setTimeout(checkReady, 16);
  35370. }
  35371. }
  35372. if (localOptions.clipPlane) {
  35373. scene.clipPlane = clipPlaneState;
  35374. }
  35375. };
  35376. checkReady();
  35377. };
  35378. /**
  35379. * Force shader compilation
  35380. * @param mesh defines the mesh that will use this material
  35381. * @param options defines additional options for compiling the shaders
  35382. * @returns a promise that resolves when the compilation completes
  35383. */
  35384. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35385. var _this = this;
  35386. return new Promise(function (resolve) {
  35387. _this.forceCompilation(mesh, function () {
  35388. resolve();
  35389. }, options);
  35390. });
  35391. };
  35392. /**
  35393. * Marks a define in the material to indicate that it needs to be re-computed
  35394. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35395. */
  35396. Material.prototype.markAsDirty = function (flag) {
  35397. if (flag & Material.TextureDirtyFlag) {
  35398. this._markAllSubMeshesAsTexturesDirty();
  35399. }
  35400. if (flag & Material.LightDirtyFlag) {
  35401. this._markAllSubMeshesAsLightsDirty();
  35402. }
  35403. if (flag & Material.FresnelDirtyFlag) {
  35404. this._markAllSubMeshesAsFresnelDirty();
  35405. }
  35406. if (flag & Material.AttributesDirtyFlag) {
  35407. this._markAllSubMeshesAsAttributesDirty();
  35408. }
  35409. if (flag & Material.MiscDirtyFlag) {
  35410. this._markAllSubMeshesAsMiscDirty();
  35411. }
  35412. this.getScene().resetCachedMaterial();
  35413. };
  35414. /**
  35415. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  35416. * @param func defines a function which checks material defines against the submeshes
  35417. */
  35418. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  35419. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  35420. var mesh = _a[_i];
  35421. if (!mesh.subMeshes) {
  35422. continue;
  35423. }
  35424. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  35425. var subMesh = _c[_b];
  35426. if (subMesh.getMaterial() !== this) {
  35427. continue;
  35428. }
  35429. if (!subMesh._materialDefines) {
  35430. continue;
  35431. }
  35432. func(subMesh._materialDefines);
  35433. }
  35434. }
  35435. };
  35436. /**
  35437. * Indicates that image processing needs to be re-calculated for all submeshes
  35438. */
  35439. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  35440. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  35441. };
  35442. /**
  35443. * Indicates that textures need to be re-calculated for all submeshes
  35444. */
  35445. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  35446. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  35447. };
  35448. /**
  35449. * Indicates that fresnel needs to be re-calculated for all submeshes
  35450. */
  35451. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  35452. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  35453. };
  35454. /**
  35455. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  35456. */
  35457. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  35458. this._markAllSubMeshesAsDirty(function (defines) {
  35459. defines.markAsFresnelDirty();
  35460. defines.markAsMiscDirty();
  35461. });
  35462. };
  35463. /**
  35464. * Indicates that lights need to be re-calculated for all submeshes
  35465. */
  35466. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  35467. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  35468. };
  35469. /**
  35470. * Indicates that attributes need to be re-calculated for all submeshes
  35471. */
  35472. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  35473. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  35474. };
  35475. /**
  35476. * Indicates that misc needs to be re-calculated for all submeshes
  35477. */
  35478. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  35479. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  35480. };
  35481. /**
  35482. * Indicates that textures and misc need to be re-calculated for all submeshes
  35483. */
  35484. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  35485. this._markAllSubMeshesAsDirty(function (defines) {
  35486. defines.markAsTexturesDirty();
  35487. defines.markAsMiscDirty();
  35488. });
  35489. };
  35490. /**
  35491. * Disposes the material
  35492. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  35493. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  35494. */
  35495. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  35496. // Animations
  35497. this.getScene().stopAnimation(this);
  35498. this.getScene().freeProcessedMaterials();
  35499. // Remove from scene
  35500. var index = this._scene.materials.indexOf(this);
  35501. if (index >= 0) {
  35502. this._scene.materials.splice(index, 1);
  35503. }
  35504. // Remove from meshes
  35505. for (index = 0; index < this._scene.meshes.length; index++) {
  35506. var mesh = this._scene.meshes[index];
  35507. if (mesh.material === this) {
  35508. mesh.material = null;
  35509. if (mesh.geometry) {
  35510. var geometry = (mesh.geometry);
  35511. if (this.storeEffectOnSubMeshes) {
  35512. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  35513. var subMesh = _a[_i];
  35514. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  35515. if (forceDisposeEffect && subMesh._materialEffect) {
  35516. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  35517. }
  35518. }
  35519. }
  35520. else {
  35521. geometry._releaseVertexArrayObject(this._effect);
  35522. }
  35523. }
  35524. }
  35525. }
  35526. this._uniformBuffer.dispose();
  35527. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  35528. if (forceDisposeEffect && this._effect) {
  35529. if (!this.storeEffectOnSubMeshes) {
  35530. this._scene.getEngine()._releaseEffect(this._effect);
  35531. }
  35532. this._effect = null;
  35533. }
  35534. // Callback
  35535. this.onDisposeObservable.notifyObservers(this);
  35536. this.onDisposeObservable.clear();
  35537. this.onBindObservable.clear();
  35538. this.onUnBindObservable.clear();
  35539. };
  35540. /**
  35541. * Serializes this material
  35542. * @returns the serialized material object
  35543. */
  35544. Material.prototype.serialize = function () {
  35545. return BABYLON.SerializationHelper.Serialize(this);
  35546. };
  35547. /**
  35548. * Creates a MultiMaterial from parsed MultiMaterial data.
  35549. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  35550. * @param scene defines the hosting scene
  35551. * @returns a new MultiMaterial
  35552. */
  35553. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  35554. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  35555. multiMaterial.id = parsedMultiMaterial.id;
  35556. if (BABYLON.Tags) {
  35557. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  35558. }
  35559. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  35560. var subMatId = parsedMultiMaterial.materials[matIndex];
  35561. if (subMatId) {
  35562. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  35563. }
  35564. else {
  35565. multiMaterial.subMaterials.push(null);
  35566. }
  35567. }
  35568. return multiMaterial;
  35569. };
  35570. /**
  35571. * Creates a material from parsed material data
  35572. * @param parsedMaterial defines parsed material data
  35573. * @param scene defines the hosting scene
  35574. * @param rootUrl defines the root URL to use to load textures
  35575. * @returns a new material
  35576. */
  35577. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  35578. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  35579. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  35580. }
  35581. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  35582. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  35583. if (!BABYLON.LegacyPBRMaterial) {
  35584. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  35585. return;
  35586. }
  35587. }
  35588. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  35589. return materialType.Parse(parsedMaterial, scene, rootUrl);
  35590. };
  35591. // Triangle views
  35592. Material._TriangleFillMode = 0;
  35593. Material._WireFrameFillMode = 1;
  35594. Material._PointFillMode = 2;
  35595. // Draw modes
  35596. Material._PointListDrawMode = 3;
  35597. Material._LineListDrawMode = 4;
  35598. Material._LineLoopDrawMode = 5;
  35599. Material._LineStripDrawMode = 6;
  35600. Material._TriangleStripDrawMode = 7;
  35601. Material._TriangleFanDrawMode = 8;
  35602. /**
  35603. * Stores the clock-wise side orientation
  35604. */
  35605. Material._ClockWiseSideOrientation = 0;
  35606. /**
  35607. * Stores the counter clock-wise side orientation
  35608. */
  35609. Material._CounterClockWiseSideOrientation = 1;
  35610. /**
  35611. * The dirty texture flag value
  35612. */
  35613. Material._TextureDirtyFlag = 1;
  35614. /**
  35615. * The dirty light flag value
  35616. */
  35617. Material._LightDirtyFlag = 2;
  35618. /**
  35619. * The dirty fresnel flag value
  35620. */
  35621. Material._FresnelDirtyFlag = 4;
  35622. /**
  35623. * The dirty attribute flag value
  35624. */
  35625. Material._AttributesDirtyFlag = 8;
  35626. /**
  35627. * The dirty misc flag value
  35628. */
  35629. Material._MiscDirtyFlag = 16;
  35630. __decorate([
  35631. BABYLON.serialize()
  35632. ], Material.prototype, "id", void 0);
  35633. __decorate([
  35634. BABYLON.serialize()
  35635. ], Material.prototype, "name", void 0);
  35636. __decorate([
  35637. BABYLON.serialize()
  35638. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  35639. __decorate([
  35640. BABYLON.serialize()
  35641. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  35642. __decorate([
  35643. BABYLON.serialize()
  35644. ], Material.prototype, "state", void 0);
  35645. __decorate([
  35646. BABYLON.serialize("alpha")
  35647. ], Material.prototype, "_alpha", void 0);
  35648. __decorate([
  35649. BABYLON.serialize("backFaceCulling")
  35650. ], Material.prototype, "_backFaceCulling", void 0);
  35651. __decorate([
  35652. BABYLON.serialize()
  35653. ], Material.prototype, "sideOrientation", void 0);
  35654. __decorate([
  35655. BABYLON.serialize("alphaMode")
  35656. ], Material.prototype, "_alphaMode", void 0);
  35657. __decorate([
  35658. BABYLON.serialize()
  35659. ], Material.prototype, "_needDepthPrePass", void 0);
  35660. __decorate([
  35661. BABYLON.serialize()
  35662. ], Material.prototype, "disableDepthWrite", void 0);
  35663. __decorate([
  35664. BABYLON.serialize()
  35665. ], Material.prototype, "forceDepthWrite", void 0);
  35666. __decorate([
  35667. BABYLON.serialize()
  35668. ], Material.prototype, "separateCullingPass", void 0);
  35669. __decorate([
  35670. BABYLON.serialize("fogEnabled")
  35671. ], Material.prototype, "_fogEnabled", void 0);
  35672. __decorate([
  35673. BABYLON.serialize()
  35674. ], Material.prototype, "pointSize", void 0);
  35675. __decorate([
  35676. BABYLON.serialize()
  35677. ], Material.prototype, "zOffset", void 0);
  35678. __decorate([
  35679. BABYLON.serialize()
  35680. ], Material.prototype, "wireframe", null);
  35681. __decorate([
  35682. BABYLON.serialize()
  35683. ], Material.prototype, "pointsCloud", null);
  35684. __decorate([
  35685. BABYLON.serialize()
  35686. ], Material.prototype, "fillMode", null);
  35687. return Material;
  35688. }());
  35689. BABYLON.Material = Material;
  35690. })(BABYLON || (BABYLON = {}));
  35691. //# sourceMappingURL=babylon.material.js.map
  35692. var BABYLON;
  35693. (function (BABYLON) {
  35694. var UniformBuffer = /** @class */ (function () {
  35695. /**
  35696. * Uniform buffer objects.
  35697. *
  35698. * Handles blocks of uniform on the GPU.
  35699. *
  35700. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  35701. *
  35702. * For more information, please refer to :
  35703. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  35704. */
  35705. function UniformBuffer(engine, data, dynamic) {
  35706. this._engine = engine;
  35707. this._noUBO = !engine.supportsUniformBuffers;
  35708. this._dynamic = dynamic;
  35709. this._data = data || [];
  35710. this._uniformLocations = {};
  35711. this._uniformSizes = {};
  35712. this._uniformLocationPointer = 0;
  35713. this._needSync = false;
  35714. if (this._noUBO) {
  35715. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  35716. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  35717. this.updateFloat = this._updateFloatForEffect;
  35718. this.updateFloat2 = this._updateFloat2ForEffect;
  35719. this.updateFloat3 = this._updateFloat3ForEffect;
  35720. this.updateFloat4 = this._updateFloat4ForEffect;
  35721. this.updateMatrix = this._updateMatrixForEffect;
  35722. this.updateVector3 = this._updateVector3ForEffect;
  35723. this.updateVector4 = this._updateVector4ForEffect;
  35724. this.updateColor3 = this._updateColor3ForEffect;
  35725. this.updateColor4 = this._updateColor4ForEffect;
  35726. }
  35727. else {
  35728. this._engine._uniformBuffers.push(this);
  35729. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  35730. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  35731. this.updateFloat = this._updateFloatForUniform;
  35732. this.updateFloat2 = this._updateFloat2ForUniform;
  35733. this.updateFloat3 = this._updateFloat3ForUniform;
  35734. this.updateFloat4 = this._updateFloat4ForUniform;
  35735. this.updateMatrix = this._updateMatrixForUniform;
  35736. this.updateVector3 = this._updateVector3ForUniform;
  35737. this.updateVector4 = this._updateVector4ForUniform;
  35738. this.updateColor3 = this._updateColor3ForUniform;
  35739. this.updateColor4 = this._updateColor4ForUniform;
  35740. }
  35741. }
  35742. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  35743. // Properties
  35744. /**
  35745. * Indicates if the buffer is using the WebGL2 UBO implementation,
  35746. * or just falling back on setUniformXXX calls.
  35747. */
  35748. get: function () {
  35749. return !this._noUBO;
  35750. },
  35751. enumerable: true,
  35752. configurable: true
  35753. });
  35754. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  35755. /**
  35756. * Indicates if the WebGL underlying uniform buffer is in sync
  35757. * with the javascript cache data.
  35758. */
  35759. get: function () {
  35760. return !this._needSync;
  35761. },
  35762. enumerable: true,
  35763. configurable: true
  35764. });
  35765. /**
  35766. * Indicates if the WebGL underlying uniform buffer is dynamic.
  35767. * Also, a dynamic UniformBuffer will disable cache verification and always
  35768. * update the underlying WebGL uniform buffer to the GPU.
  35769. */
  35770. UniformBuffer.prototype.isDynamic = function () {
  35771. return this._dynamic !== undefined;
  35772. };
  35773. /**
  35774. * The data cache on JS side.
  35775. */
  35776. UniformBuffer.prototype.getData = function () {
  35777. return this._bufferData;
  35778. };
  35779. /**
  35780. * The underlying WebGL Uniform buffer.
  35781. */
  35782. UniformBuffer.prototype.getBuffer = function () {
  35783. return this._buffer;
  35784. };
  35785. /**
  35786. * std140 layout specifies how to align data within an UBO structure.
  35787. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  35788. * for specs.
  35789. */
  35790. UniformBuffer.prototype._fillAlignment = function (size) {
  35791. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  35792. // and 4x4 matrices
  35793. // TODO : change if other types are used
  35794. var alignment;
  35795. if (size <= 2) {
  35796. alignment = size;
  35797. }
  35798. else {
  35799. alignment = 4;
  35800. }
  35801. if ((this._uniformLocationPointer % alignment) !== 0) {
  35802. var oldPointer = this._uniformLocationPointer;
  35803. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  35804. var diff = this._uniformLocationPointer - oldPointer;
  35805. for (var i = 0; i < diff; i++) {
  35806. this._data.push(0);
  35807. }
  35808. }
  35809. };
  35810. /**
  35811. * Adds an uniform in the buffer.
  35812. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  35813. * for the layout to be correct !
  35814. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35815. * @param {number|number[]} size Data size, or data directly.
  35816. */
  35817. UniformBuffer.prototype.addUniform = function (name, size) {
  35818. if (this._noUBO) {
  35819. return;
  35820. }
  35821. if (this._uniformLocations[name] !== undefined) {
  35822. // Already existing uniform
  35823. return;
  35824. }
  35825. // This function must be called in the order of the shader layout !
  35826. // size can be the size of the uniform, or data directly
  35827. var data;
  35828. if (size instanceof Array) {
  35829. data = size;
  35830. size = data.length;
  35831. }
  35832. else {
  35833. size = size;
  35834. data = [];
  35835. // Fill with zeros
  35836. for (var i = 0; i < size; i++) {
  35837. data.push(0);
  35838. }
  35839. }
  35840. this._fillAlignment(size);
  35841. this._uniformSizes[name] = size;
  35842. this._uniformLocations[name] = this._uniformLocationPointer;
  35843. this._uniformLocationPointer += size;
  35844. for (var i = 0; i < size; i++) {
  35845. this._data.push(data[i]);
  35846. }
  35847. this._needSync = true;
  35848. };
  35849. /**
  35850. * Wrapper for addUniform.
  35851. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35852. * @param {Matrix} mat A 4x4 matrix.
  35853. */
  35854. UniformBuffer.prototype.addMatrix = function (name, mat) {
  35855. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  35856. };
  35857. /**
  35858. * Wrapper for addUniform.
  35859. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35860. * @param {number} x
  35861. * @param {number} y
  35862. */
  35863. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  35864. var temp = [x, y];
  35865. this.addUniform(name, temp);
  35866. };
  35867. /**
  35868. * Wrapper for addUniform.
  35869. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35870. * @param {number} x
  35871. * @param {number} y
  35872. * @param {number} z
  35873. */
  35874. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  35875. var temp = [x, y, z];
  35876. this.addUniform(name, temp);
  35877. };
  35878. /**
  35879. * Wrapper for addUniform.
  35880. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35881. * @param {Color3} color
  35882. */
  35883. UniformBuffer.prototype.addColor3 = function (name, color) {
  35884. var temp = new Array();
  35885. color.toArray(temp);
  35886. this.addUniform(name, temp);
  35887. };
  35888. /**
  35889. * Wrapper for addUniform.
  35890. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35891. * @param {Color3} color
  35892. * @param {number} alpha
  35893. */
  35894. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  35895. var temp = new Array();
  35896. color.toArray(temp);
  35897. temp.push(alpha);
  35898. this.addUniform(name, temp);
  35899. };
  35900. /**
  35901. * Wrapper for addUniform.
  35902. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35903. * @param {Vector3} vector
  35904. */
  35905. UniformBuffer.prototype.addVector3 = function (name, vector) {
  35906. var temp = new Array();
  35907. vector.toArray(temp);
  35908. this.addUniform(name, temp);
  35909. };
  35910. /**
  35911. * Wrapper for addUniform.
  35912. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35913. */
  35914. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  35915. this.addUniform(name, 12);
  35916. };
  35917. /**
  35918. * Wrapper for addUniform.
  35919. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  35920. */
  35921. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  35922. this.addUniform(name, 8);
  35923. };
  35924. /**
  35925. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  35926. */
  35927. UniformBuffer.prototype.create = function () {
  35928. if (this._noUBO) {
  35929. return;
  35930. }
  35931. if (this._buffer) {
  35932. return; // nothing to do
  35933. }
  35934. // See spec, alignment must be filled as a vec4
  35935. this._fillAlignment(4);
  35936. this._bufferData = new Float32Array(this._data);
  35937. this._rebuild();
  35938. this._needSync = true;
  35939. };
  35940. UniformBuffer.prototype._rebuild = function () {
  35941. if (this._noUBO) {
  35942. return;
  35943. }
  35944. if (this._dynamic) {
  35945. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  35946. }
  35947. else {
  35948. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  35949. }
  35950. };
  35951. /**
  35952. * Updates the WebGL Uniform Buffer on the GPU.
  35953. * If the `dynamic` flag is set to true, no cache comparison is done.
  35954. * Otherwise, the buffer will be updated only if the cache differs.
  35955. */
  35956. UniformBuffer.prototype.update = function () {
  35957. if (!this._buffer) {
  35958. this.create();
  35959. return;
  35960. }
  35961. if (!this._dynamic && !this._needSync) {
  35962. return;
  35963. }
  35964. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  35965. this._needSync = false;
  35966. };
  35967. /**
  35968. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  35969. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  35970. * @param {number[]|Float32Array} data Flattened data
  35971. * @param {number} size Size of the data.
  35972. */
  35973. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  35974. var location = this._uniformLocations[uniformName];
  35975. if (location === undefined) {
  35976. if (this._buffer) {
  35977. // Cannot add an uniform if the buffer is already created
  35978. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  35979. return;
  35980. }
  35981. this.addUniform(uniformName, size);
  35982. location = this._uniformLocations[uniformName];
  35983. }
  35984. if (!this._buffer) {
  35985. this.create();
  35986. }
  35987. if (!this._dynamic) {
  35988. // Cache for static uniform buffers
  35989. var changed = false;
  35990. for (var i = 0; i < size; i++) {
  35991. if (this._bufferData[location + i] !== data[i]) {
  35992. changed = true;
  35993. this._bufferData[location + i] = data[i];
  35994. }
  35995. }
  35996. this._needSync = this._needSync || changed;
  35997. }
  35998. else {
  35999. // No cache for dynamic
  36000. for (var i = 0; i < size; i++) {
  36001. this._bufferData[location + i] = data[i];
  36002. }
  36003. }
  36004. };
  36005. // Update methods
  36006. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36007. // To match std140, matrix must be realigned
  36008. for (var i = 0; i < 3; i++) {
  36009. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36010. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36011. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36012. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36013. }
  36014. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36015. };
  36016. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36017. this._currentEffect.setMatrix3x3(name, matrix);
  36018. };
  36019. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36020. this._currentEffect.setMatrix2x2(name, matrix);
  36021. };
  36022. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36023. // To match std140, matrix must be realigned
  36024. for (var i = 0; i < 2; i++) {
  36025. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36026. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36027. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36028. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36029. }
  36030. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36031. };
  36032. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36033. this._currentEffect.setFloat(name, x);
  36034. };
  36035. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36036. UniformBuffer._tempBuffer[0] = x;
  36037. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36038. };
  36039. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36040. if (suffix === void 0) { suffix = ""; }
  36041. this._currentEffect.setFloat2(name + suffix, x, y);
  36042. };
  36043. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36044. if (suffix === void 0) { suffix = ""; }
  36045. UniformBuffer._tempBuffer[0] = x;
  36046. UniformBuffer._tempBuffer[1] = y;
  36047. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36048. };
  36049. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36050. if (suffix === void 0) { suffix = ""; }
  36051. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36052. };
  36053. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36054. if (suffix === void 0) { suffix = ""; }
  36055. UniformBuffer._tempBuffer[0] = x;
  36056. UniformBuffer._tempBuffer[1] = y;
  36057. UniformBuffer._tempBuffer[2] = z;
  36058. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36059. };
  36060. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36061. if (suffix === void 0) { suffix = ""; }
  36062. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36063. };
  36064. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36065. if (suffix === void 0) { suffix = ""; }
  36066. UniformBuffer._tempBuffer[0] = x;
  36067. UniformBuffer._tempBuffer[1] = y;
  36068. UniformBuffer._tempBuffer[2] = z;
  36069. UniformBuffer._tempBuffer[3] = w;
  36070. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36071. };
  36072. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36073. this._currentEffect.setMatrix(name, mat);
  36074. };
  36075. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36076. this.updateUniform(name, mat.toArray(), 16);
  36077. };
  36078. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36079. this._currentEffect.setVector3(name, vector);
  36080. };
  36081. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36082. vector.toArray(UniformBuffer._tempBuffer);
  36083. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36084. };
  36085. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36086. this._currentEffect.setVector4(name, vector);
  36087. };
  36088. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36089. vector.toArray(UniformBuffer._tempBuffer);
  36090. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36091. };
  36092. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36093. if (suffix === void 0) { suffix = ""; }
  36094. this._currentEffect.setColor3(name + suffix, color);
  36095. };
  36096. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36097. if (suffix === void 0) { suffix = ""; }
  36098. color.toArray(UniformBuffer._tempBuffer);
  36099. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36100. };
  36101. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36102. if (suffix === void 0) { suffix = ""; }
  36103. this._currentEffect.setColor4(name + suffix, color, alpha);
  36104. };
  36105. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36106. if (suffix === void 0) { suffix = ""; }
  36107. color.toArray(UniformBuffer._tempBuffer);
  36108. UniformBuffer._tempBuffer[3] = alpha;
  36109. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36110. };
  36111. /**
  36112. * Sets a sampler uniform on the effect.
  36113. * @param {string} name Name of the sampler.
  36114. * @param {Texture} texture
  36115. */
  36116. UniformBuffer.prototype.setTexture = function (name, texture) {
  36117. this._currentEffect.setTexture(name, texture);
  36118. };
  36119. /**
  36120. * Directly updates the value of the uniform in the cache AND on the GPU.
  36121. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36122. * @param {number[]|Float32Array} data Flattened data
  36123. */
  36124. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36125. this.updateUniform(uniformName, data, data.length);
  36126. this.update();
  36127. };
  36128. /**
  36129. * Binds this uniform buffer to an effect.
  36130. * @param {Effect} effect
  36131. * @param {string} name Name of the uniform block in the shader.
  36132. */
  36133. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36134. this._currentEffect = effect;
  36135. if (this._noUBO || !this._buffer) {
  36136. return;
  36137. }
  36138. effect.bindUniformBuffer(this._buffer, name);
  36139. };
  36140. /**
  36141. * Disposes the uniform buffer.
  36142. */
  36143. UniformBuffer.prototype.dispose = function () {
  36144. if (this._noUBO) {
  36145. return;
  36146. }
  36147. var index = this._engine._uniformBuffers.indexOf(this);
  36148. if (index !== -1) {
  36149. this._engine._uniformBuffers.splice(index, 1);
  36150. }
  36151. if (!this._buffer) {
  36152. return;
  36153. }
  36154. if (this._engine._releaseBuffer(this._buffer)) {
  36155. this._buffer = null;
  36156. }
  36157. };
  36158. // Pool for avoiding memory leaks
  36159. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36160. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36161. return UniformBuffer;
  36162. }());
  36163. BABYLON.UniformBuffer = UniformBuffer;
  36164. })(BABYLON || (BABYLON = {}));
  36165. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36166. var BABYLON;
  36167. (function (BABYLON) {
  36168. /**
  36169. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36170. */
  36171. var VertexData = /** @class */ (function () {
  36172. function VertexData() {
  36173. }
  36174. /**
  36175. * Uses the passed data array to set the set the values for the specified kind of data
  36176. * @param data a linear array of floating numbers
  36177. * @param kind the type of data that is being set, eg positions, colors etc
  36178. */
  36179. VertexData.prototype.set = function (data, kind) {
  36180. switch (kind) {
  36181. case BABYLON.VertexBuffer.PositionKind:
  36182. this.positions = data;
  36183. break;
  36184. case BABYLON.VertexBuffer.NormalKind:
  36185. this.normals = data;
  36186. break;
  36187. case BABYLON.VertexBuffer.TangentKind:
  36188. this.tangents = data;
  36189. break;
  36190. case BABYLON.VertexBuffer.UVKind:
  36191. this.uvs = data;
  36192. break;
  36193. case BABYLON.VertexBuffer.UV2Kind:
  36194. this.uvs2 = data;
  36195. break;
  36196. case BABYLON.VertexBuffer.UV3Kind:
  36197. this.uvs3 = data;
  36198. break;
  36199. case BABYLON.VertexBuffer.UV4Kind:
  36200. this.uvs4 = data;
  36201. break;
  36202. case BABYLON.VertexBuffer.UV5Kind:
  36203. this.uvs5 = data;
  36204. break;
  36205. case BABYLON.VertexBuffer.UV6Kind:
  36206. this.uvs6 = data;
  36207. break;
  36208. case BABYLON.VertexBuffer.ColorKind:
  36209. this.colors = data;
  36210. break;
  36211. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36212. this.matricesIndices = data;
  36213. break;
  36214. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36215. this.matricesWeights = data;
  36216. break;
  36217. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36218. this.matricesIndicesExtra = data;
  36219. break;
  36220. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36221. this.matricesWeightsExtra = data;
  36222. break;
  36223. }
  36224. };
  36225. /**
  36226. * Associates the vertexData to the passed Mesh.
  36227. * Sets it as updatable or not (default `false`)
  36228. * @param mesh the mesh the vertexData is applied to
  36229. * @param updatable when used and having the value true allows new data to update the vertexData
  36230. * @returns the VertexData
  36231. */
  36232. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36233. this._applyTo(mesh, updatable);
  36234. return this;
  36235. };
  36236. /**
  36237. * Associates the vertexData to the passed Geometry.
  36238. * Sets it as updatable or not (default `false`)
  36239. * @param geometry the geometry the vertexData is applied to
  36240. * @param updatable when used and having the value true allows new data to update the vertexData
  36241. * @returns VertexData
  36242. */
  36243. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36244. this._applyTo(geometry, updatable);
  36245. return this;
  36246. };
  36247. /**
  36248. * Updates the associated mesh
  36249. * @param mesh the mesh to be updated
  36250. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36251. * @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
  36252. * @returns VertexData
  36253. */
  36254. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36255. this._update(mesh);
  36256. return this;
  36257. };
  36258. /**
  36259. * Updates the associated geometry
  36260. * @param geometry the geometry to be updated
  36261. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36262. * @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
  36263. * @returns VertexData.
  36264. */
  36265. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36266. this._update(geometry);
  36267. return this;
  36268. };
  36269. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36270. if (updatable === void 0) { updatable = false; }
  36271. if (this.positions) {
  36272. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36273. }
  36274. if (this.normals) {
  36275. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36276. }
  36277. if (this.tangents) {
  36278. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36279. }
  36280. if (this.uvs) {
  36281. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36282. }
  36283. if (this.uvs2) {
  36284. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36285. }
  36286. if (this.uvs3) {
  36287. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36288. }
  36289. if (this.uvs4) {
  36290. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36291. }
  36292. if (this.uvs5) {
  36293. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36294. }
  36295. if (this.uvs6) {
  36296. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36297. }
  36298. if (this.colors) {
  36299. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36300. }
  36301. if (this.matricesIndices) {
  36302. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36303. }
  36304. if (this.matricesWeights) {
  36305. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36306. }
  36307. if (this.matricesIndicesExtra) {
  36308. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36309. }
  36310. if (this.matricesWeightsExtra) {
  36311. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36312. }
  36313. if (this.indices) {
  36314. meshOrGeometry.setIndices(this.indices, null, updatable);
  36315. }
  36316. return this;
  36317. };
  36318. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36319. if (this.positions) {
  36320. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36321. }
  36322. if (this.normals) {
  36323. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36324. }
  36325. if (this.tangents) {
  36326. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36327. }
  36328. if (this.uvs) {
  36329. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36330. }
  36331. if (this.uvs2) {
  36332. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36333. }
  36334. if (this.uvs3) {
  36335. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36336. }
  36337. if (this.uvs4) {
  36338. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36339. }
  36340. if (this.uvs5) {
  36341. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36342. }
  36343. if (this.uvs6) {
  36344. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36345. }
  36346. if (this.colors) {
  36347. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36348. }
  36349. if (this.matricesIndices) {
  36350. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36351. }
  36352. if (this.matricesWeights) {
  36353. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36354. }
  36355. if (this.matricesIndicesExtra) {
  36356. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36357. }
  36358. if (this.matricesWeightsExtra) {
  36359. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36360. }
  36361. if (this.indices) {
  36362. meshOrGeometry.setIndices(this.indices, null);
  36363. }
  36364. return this;
  36365. };
  36366. /**
  36367. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36368. * @param matrix the transforming matrix
  36369. * @returns the VertexData
  36370. */
  36371. VertexData.prototype.transform = function (matrix) {
  36372. var transformed = BABYLON.Vector3.Zero();
  36373. var index;
  36374. if (this.positions) {
  36375. var position = BABYLON.Vector3.Zero();
  36376. for (index = 0; index < this.positions.length; index += 3) {
  36377. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36378. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36379. this.positions[index] = transformed.x;
  36380. this.positions[index + 1] = transformed.y;
  36381. this.positions[index + 2] = transformed.z;
  36382. }
  36383. }
  36384. if (this.normals) {
  36385. var normal = BABYLON.Vector3.Zero();
  36386. for (index = 0; index < this.normals.length; index += 3) {
  36387. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36388. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36389. this.normals[index] = transformed.x;
  36390. this.normals[index + 1] = transformed.y;
  36391. this.normals[index + 2] = transformed.z;
  36392. }
  36393. }
  36394. if (this.tangents) {
  36395. var tangent = BABYLON.Vector4.Zero();
  36396. var tangentTransformed = BABYLON.Vector4.Zero();
  36397. for (index = 0; index < this.tangents.length; index += 4) {
  36398. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36399. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  36400. this.tangents[index] = tangentTransformed.x;
  36401. this.tangents[index + 1] = tangentTransformed.y;
  36402. this.tangents[index + 2] = tangentTransformed.z;
  36403. this.tangents[index + 3] = tangentTransformed.w;
  36404. }
  36405. }
  36406. return this;
  36407. };
  36408. /**
  36409. * Merges the passed VertexData into the current one
  36410. * @param other the VertexData to be merged into the current one
  36411. * @returns the modified VertexData
  36412. */
  36413. VertexData.prototype.merge = function (other) {
  36414. this._validate();
  36415. other._validate();
  36416. if (!this.normals !== !other.normals ||
  36417. !this.tangents !== !other.tangents ||
  36418. !this.uvs !== !other.uvs ||
  36419. !this.uvs2 !== !other.uvs2 ||
  36420. !this.uvs3 !== !other.uvs3 ||
  36421. !this.uvs4 !== !other.uvs4 ||
  36422. !this.uvs5 !== !other.uvs5 ||
  36423. !this.uvs6 !== !other.uvs6 ||
  36424. !this.colors !== !other.colors ||
  36425. !this.matricesIndices !== !other.matricesIndices ||
  36426. !this.matricesWeights !== !other.matricesWeights ||
  36427. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  36428. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  36429. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  36430. }
  36431. if (other.indices) {
  36432. if (!this.indices) {
  36433. this.indices = [];
  36434. }
  36435. var offset = this.positions ? this.positions.length / 3 : 0;
  36436. for (var index = 0; index < other.indices.length; index++) {
  36437. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  36438. this.indices.push(other.indices[index] + offset);
  36439. }
  36440. }
  36441. this.positions = this._mergeElement(this.positions, other.positions);
  36442. this.normals = this._mergeElement(this.normals, other.normals);
  36443. this.tangents = this._mergeElement(this.tangents, other.tangents);
  36444. this.uvs = this._mergeElement(this.uvs, other.uvs);
  36445. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  36446. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  36447. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  36448. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  36449. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  36450. this.colors = this._mergeElement(this.colors, other.colors);
  36451. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  36452. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  36453. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  36454. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  36455. return this;
  36456. };
  36457. VertexData.prototype._mergeElement = function (source, other) {
  36458. if (!source) {
  36459. return other;
  36460. }
  36461. if (!other) {
  36462. return source;
  36463. }
  36464. var len = other.length + source.length;
  36465. var isSrcTypedArray = source instanceof Float32Array;
  36466. var isOthTypedArray = other instanceof Float32Array;
  36467. // use non-loop method when the source is Float32Array
  36468. if (isSrcTypedArray) {
  36469. var ret32 = new Float32Array(len);
  36470. ret32.set(source);
  36471. ret32.set(other, source.length);
  36472. return ret32;
  36473. // source is number[], when other is also use concat
  36474. }
  36475. else if (!isOthTypedArray) {
  36476. return source.concat(other);
  36477. // source is a number[], but other is a Float32Array, loop required
  36478. }
  36479. else {
  36480. var ret = source.slice(0); // copy source to a separate array
  36481. for (var i = 0, len = other.length; i < len; i++) {
  36482. ret.push(other[i]);
  36483. }
  36484. return ret;
  36485. }
  36486. };
  36487. VertexData.prototype._validate = function () {
  36488. if (!this.positions) {
  36489. throw new Error("Positions are required");
  36490. }
  36491. var getElementCount = function (kind, values) {
  36492. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  36493. if ((values.length % stride) !== 0) {
  36494. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  36495. }
  36496. return values.length / stride;
  36497. };
  36498. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  36499. var validateElementCount = function (kind, values) {
  36500. var elementCount = getElementCount(kind, values);
  36501. if (elementCount !== positionsElementCount) {
  36502. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  36503. }
  36504. };
  36505. if (this.normals)
  36506. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  36507. if (this.tangents)
  36508. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  36509. if (this.uvs)
  36510. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  36511. if (this.uvs2)
  36512. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  36513. if (this.uvs3)
  36514. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  36515. if (this.uvs4)
  36516. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  36517. if (this.uvs5)
  36518. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  36519. if (this.uvs6)
  36520. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  36521. if (this.colors)
  36522. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  36523. if (this.matricesIndices)
  36524. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  36525. if (this.matricesWeights)
  36526. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  36527. if (this.matricesIndicesExtra)
  36528. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  36529. if (this.matricesWeightsExtra)
  36530. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  36531. };
  36532. /**
  36533. * Serializes the VertexData
  36534. * @returns a serialized object
  36535. */
  36536. VertexData.prototype.serialize = function () {
  36537. var serializationObject = this.serialize();
  36538. if (this.positions) {
  36539. serializationObject.positions = this.positions;
  36540. }
  36541. if (this.normals) {
  36542. serializationObject.normals = this.normals;
  36543. }
  36544. if (this.tangents) {
  36545. serializationObject.tangents = this.tangents;
  36546. }
  36547. if (this.uvs) {
  36548. serializationObject.uvs = this.uvs;
  36549. }
  36550. if (this.uvs2) {
  36551. serializationObject.uvs2 = this.uvs2;
  36552. }
  36553. if (this.uvs3) {
  36554. serializationObject.uvs3 = this.uvs3;
  36555. }
  36556. if (this.uvs4) {
  36557. serializationObject.uvs4 = this.uvs4;
  36558. }
  36559. if (this.uvs5) {
  36560. serializationObject.uvs5 = this.uvs5;
  36561. }
  36562. if (this.uvs6) {
  36563. serializationObject.uvs6 = this.uvs6;
  36564. }
  36565. if (this.colors) {
  36566. serializationObject.colors = this.colors;
  36567. }
  36568. if (this.matricesIndices) {
  36569. serializationObject.matricesIndices = this.matricesIndices;
  36570. serializationObject.matricesIndices._isExpanded = true;
  36571. }
  36572. if (this.matricesWeights) {
  36573. serializationObject.matricesWeights = this.matricesWeights;
  36574. }
  36575. if (this.matricesIndicesExtra) {
  36576. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  36577. serializationObject.matricesIndicesExtra._isExpanded = true;
  36578. }
  36579. if (this.matricesWeightsExtra) {
  36580. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  36581. }
  36582. serializationObject.indices = this.indices;
  36583. return serializationObject;
  36584. };
  36585. // Statics
  36586. /**
  36587. * Extracts the vertexData from a mesh
  36588. * @param mesh the mesh from which to extract the VertexData
  36589. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  36590. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36591. * @returns the object VertexData associated to the passed mesh
  36592. */
  36593. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  36594. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  36595. };
  36596. /**
  36597. * Extracts the vertexData from the geometry
  36598. * @param geometry the geometry from which to extract the VertexData
  36599. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  36600. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  36601. * @returns the object VertexData associated to the passed mesh
  36602. */
  36603. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  36604. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  36605. };
  36606. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  36607. var result = new VertexData();
  36608. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  36609. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  36610. }
  36611. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  36612. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  36613. }
  36614. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  36615. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  36616. }
  36617. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  36618. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  36619. }
  36620. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  36621. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  36622. }
  36623. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  36624. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  36625. }
  36626. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  36627. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  36628. }
  36629. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  36630. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  36631. }
  36632. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  36633. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  36634. }
  36635. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  36636. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  36637. }
  36638. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  36639. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  36640. }
  36641. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  36642. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  36643. }
  36644. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  36645. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  36646. }
  36647. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  36648. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  36649. }
  36650. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  36651. return result;
  36652. };
  36653. /**
  36654. * Creates the VertexData for a Ribbon
  36655. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  36656. * * pathArray array of paths, each of which an array of successive Vector3
  36657. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  36658. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  36659. * * 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
  36660. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36661. * * 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)
  36662. * * 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)
  36663. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  36664. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  36665. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  36666. * @returns the VertexData of the ribbon
  36667. */
  36668. VertexData.CreateRibbon = function (options) {
  36669. var pathArray = options.pathArray;
  36670. var closeArray = options.closeArray || false;
  36671. var closePath = options.closePath || false;
  36672. var invertUV = options.invertUV || false;
  36673. var defaultOffset = Math.floor(pathArray[0].length / 2);
  36674. var offset = options.offset || defaultOffset;
  36675. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  36676. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36677. var customUV = options.uvs;
  36678. var customColors = options.colors;
  36679. var positions = [];
  36680. var indices = [];
  36681. var normals = [];
  36682. var uvs = [];
  36683. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  36684. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  36685. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  36686. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  36687. var minlg; // minimal length among all paths from pathArray
  36688. var lg = []; // array of path lengths : nb of vertex per path
  36689. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  36690. var p; // path iterator
  36691. var i; // point iterator
  36692. var j; // point iterator
  36693. // if single path in pathArray
  36694. if (pathArray.length < 2) {
  36695. var ar1 = [];
  36696. var ar2 = [];
  36697. for (i = 0; i < pathArray[0].length - offset; i++) {
  36698. ar1.push(pathArray[0][i]);
  36699. ar2.push(pathArray[0][i + offset]);
  36700. }
  36701. pathArray = [ar1, ar2];
  36702. }
  36703. // positions and horizontal distances (u)
  36704. var idc = 0;
  36705. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  36706. var path;
  36707. var l;
  36708. minlg = pathArray[0].length;
  36709. var vectlg;
  36710. var dist;
  36711. for (p = 0; p < pathArray.length; p++) {
  36712. uTotalDistance[p] = 0;
  36713. us[p] = [0];
  36714. path = pathArray[p];
  36715. l = path.length;
  36716. minlg = (minlg < l) ? minlg : l;
  36717. j = 0;
  36718. while (j < l) {
  36719. positions.push(path[j].x, path[j].y, path[j].z);
  36720. if (j > 0) {
  36721. vectlg = path[j].subtract(path[j - 1]).length();
  36722. dist = vectlg + uTotalDistance[p];
  36723. us[p].push(dist);
  36724. uTotalDistance[p] = dist;
  36725. }
  36726. j++;
  36727. }
  36728. if (closePath) { // an extra hidden vertex is added in the "positions" array
  36729. j--;
  36730. positions.push(path[0].x, path[0].y, path[0].z);
  36731. vectlg = path[j].subtract(path[0]).length();
  36732. dist = vectlg + uTotalDistance[p];
  36733. us[p].push(dist);
  36734. uTotalDistance[p] = dist;
  36735. }
  36736. lg[p] = l + closePathCorr;
  36737. idx[p] = idc;
  36738. idc += (l + closePathCorr);
  36739. }
  36740. // vertical distances (v)
  36741. var path1;
  36742. var path2;
  36743. var vertex1 = null;
  36744. var vertex2 = null;
  36745. for (i = 0; i < minlg + closePathCorr; i++) {
  36746. vTotalDistance[i] = 0;
  36747. vs[i] = [0];
  36748. for (p = 0; p < pathArray.length - 1; p++) {
  36749. path1 = pathArray[p];
  36750. path2 = pathArray[p + 1];
  36751. if (i === minlg) { // closePath
  36752. vertex1 = path1[0];
  36753. vertex2 = path2[0];
  36754. }
  36755. else {
  36756. vertex1 = path1[i];
  36757. vertex2 = path2[i];
  36758. }
  36759. vectlg = vertex2.subtract(vertex1).length();
  36760. dist = vectlg + vTotalDistance[i];
  36761. vs[i].push(dist);
  36762. vTotalDistance[i] = dist;
  36763. }
  36764. if (closeArray && vertex2 && vertex1) {
  36765. path1 = pathArray[p];
  36766. path2 = pathArray[0];
  36767. if (i === minlg) { // closePath
  36768. vertex2 = path2[0];
  36769. }
  36770. vectlg = vertex2.subtract(vertex1).length();
  36771. dist = vectlg + vTotalDistance[i];
  36772. vTotalDistance[i] = dist;
  36773. }
  36774. }
  36775. // uvs
  36776. var u;
  36777. var v;
  36778. if (customUV) {
  36779. for (p = 0; p < customUV.length; p++) {
  36780. uvs.push(customUV[p].x, customUV[p].y);
  36781. }
  36782. }
  36783. else {
  36784. for (p = 0; p < pathArray.length; p++) {
  36785. for (i = 0; i < minlg + closePathCorr; i++) {
  36786. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  36787. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  36788. if (invertUV) {
  36789. uvs.push(v, u);
  36790. }
  36791. else {
  36792. uvs.push(u, v);
  36793. }
  36794. }
  36795. }
  36796. }
  36797. // indices
  36798. p = 0; // path index
  36799. var pi = 0; // positions array index
  36800. var l1 = lg[p] - 1; // path1 length
  36801. var l2 = lg[p + 1] - 1; // path2 length
  36802. var min = (l1 < l2) ? l1 : l2; // current path stop index
  36803. var shft = idx[1] - idx[0]; // shift
  36804. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  36805. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  36806. // 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
  36807. indices.push(pi, pi + shft, pi + 1);
  36808. indices.push(pi + shft + 1, pi + 1, pi + shft);
  36809. pi += 1;
  36810. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  36811. p++;
  36812. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  36813. shft = idx[0] - idx[p];
  36814. l1 = lg[p] - 1;
  36815. l2 = lg[0] - 1;
  36816. }
  36817. else {
  36818. shft = idx[p + 1] - idx[p];
  36819. l1 = lg[p] - 1;
  36820. l2 = lg[p + 1] - 1;
  36821. }
  36822. pi = idx[p];
  36823. min = (l1 < l2) ? l1 + pi : l2 + pi;
  36824. }
  36825. }
  36826. // normals
  36827. VertexData.ComputeNormals(positions, indices, normals);
  36828. if (closePath) { // update both the first and last vertex normals to their average value
  36829. var indexFirst = 0;
  36830. var indexLast = 0;
  36831. for (p = 0; p < pathArray.length; p++) {
  36832. indexFirst = idx[p] * 3;
  36833. if (p + 1 < pathArray.length) {
  36834. indexLast = (idx[p + 1] - 1) * 3;
  36835. }
  36836. else {
  36837. indexLast = normals.length - 3;
  36838. }
  36839. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  36840. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  36841. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  36842. normals[indexLast] = normals[indexFirst];
  36843. normals[indexLast + 1] = normals[indexFirst + 1];
  36844. normals[indexLast + 2] = normals[indexFirst + 2];
  36845. }
  36846. }
  36847. // sides
  36848. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36849. // Colors
  36850. var colors = null;
  36851. if (customColors) {
  36852. colors = new Float32Array(customColors.length * 4);
  36853. for (var c = 0; c < customColors.length; c++) {
  36854. colors[c * 4] = customColors[c].r;
  36855. colors[c * 4 + 1] = customColors[c].g;
  36856. colors[c * 4 + 2] = customColors[c].b;
  36857. colors[c * 4 + 3] = customColors[c].a;
  36858. }
  36859. }
  36860. // Result
  36861. var vertexData = new VertexData();
  36862. var positions32 = new Float32Array(positions);
  36863. var normals32 = new Float32Array(normals);
  36864. var uvs32 = new Float32Array(uvs);
  36865. vertexData.indices = indices;
  36866. vertexData.positions = positions32;
  36867. vertexData.normals = normals32;
  36868. vertexData.uvs = uvs32;
  36869. if (colors) {
  36870. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  36871. }
  36872. if (closePath) {
  36873. vertexData._idx = idx;
  36874. }
  36875. return vertexData;
  36876. };
  36877. /**
  36878. * Creates the VertexData for a box
  36879. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36880. * * size sets the width, height and depth of the box to the value of size, optional default 1
  36881. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  36882. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  36883. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  36884. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  36885. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  36886. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36887. * * 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)
  36888. * * 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)
  36889. * @returns the VertexData of the box
  36890. */
  36891. VertexData.CreateBox = function (options) {
  36892. var normalsSource = [
  36893. new BABYLON.Vector3(0, 0, 1),
  36894. new BABYLON.Vector3(0, 0, -1),
  36895. new BABYLON.Vector3(1, 0, 0),
  36896. new BABYLON.Vector3(-1, 0, 0),
  36897. new BABYLON.Vector3(0, 1, 0),
  36898. new BABYLON.Vector3(0, -1, 0)
  36899. ];
  36900. var indices = [];
  36901. var positions = [];
  36902. var normals = [];
  36903. var uvs = [];
  36904. var width = options.width || options.size || 1;
  36905. var height = options.height || options.size || 1;
  36906. var depth = options.depth || options.size || 1;
  36907. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  36908. var faceUV = options.faceUV || new Array(6);
  36909. var faceColors = options.faceColors;
  36910. var colors = [];
  36911. // default face colors and UV if undefined
  36912. for (var f = 0; f < 6; f++) {
  36913. if (faceUV[f] === undefined) {
  36914. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  36915. }
  36916. if (faceColors && faceColors[f] === undefined) {
  36917. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  36918. }
  36919. }
  36920. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  36921. // Create each face in turn.
  36922. for (var index = 0; index < normalsSource.length; index++) {
  36923. var normal = normalsSource[index];
  36924. // Get two vectors perpendicular to the face normal and to each other.
  36925. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  36926. var side2 = BABYLON.Vector3.Cross(normal, side1);
  36927. // Six indices (two triangles) per face.
  36928. var verticesLength = positions.length / 3;
  36929. indices.push(verticesLength);
  36930. indices.push(verticesLength + 1);
  36931. indices.push(verticesLength + 2);
  36932. indices.push(verticesLength);
  36933. indices.push(verticesLength + 2);
  36934. indices.push(verticesLength + 3);
  36935. // Four vertices per face.
  36936. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  36937. positions.push(vertex.x, vertex.y, vertex.z);
  36938. normals.push(normal.x, normal.y, normal.z);
  36939. uvs.push(faceUV[index].z, faceUV[index].w);
  36940. if (faceColors) {
  36941. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36942. }
  36943. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  36944. positions.push(vertex.x, vertex.y, vertex.z);
  36945. normals.push(normal.x, normal.y, normal.z);
  36946. uvs.push(faceUV[index].x, faceUV[index].w);
  36947. if (faceColors) {
  36948. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36949. }
  36950. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  36951. positions.push(vertex.x, vertex.y, vertex.z);
  36952. normals.push(normal.x, normal.y, normal.z);
  36953. uvs.push(faceUV[index].x, faceUV[index].y);
  36954. if (faceColors) {
  36955. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36956. }
  36957. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  36958. positions.push(vertex.x, vertex.y, vertex.z);
  36959. normals.push(normal.x, normal.y, normal.z);
  36960. uvs.push(faceUV[index].z, faceUV[index].y);
  36961. if (faceColors) {
  36962. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  36963. }
  36964. }
  36965. // sides
  36966. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  36967. // Result
  36968. var vertexData = new VertexData();
  36969. vertexData.indices = indices;
  36970. vertexData.positions = positions;
  36971. vertexData.normals = normals;
  36972. vertexData.uvs = uvs;
  36973. if (faceColors) {
  36974. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  36975. vertexData.colors = totalColors;
  36976. }
  36977. return vertexData;
  36978. };
  36979. /**
  36980. * Creates the VertexData for an ellipsoid, defaults to a sphere
  36981. * @param options an object used to set the following optional parameters for the box, required but can be empty
  36982. * * segments sets the number of horizontal strips optional, default 32
  36983. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  36984. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  36985. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  36986. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  36987. * * 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
  36988. * * 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
  36989. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  36990. * * 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)
  36991. * * 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)
  36992. * @returns the VertexData of the ellipsoid
  36993. */
  36994. VertexData.CreateSphere = function (options) {
  36995. var segments = options.segments || 32;
  36996. var diameterX = options.diameterX || options.diameter || 1;
  36997. var diameterY = options.diameterY || options.diameter || 1;
  36998. var diameterZ = options.diameterZ || options.diameter || 1;
  36999. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37000. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37001. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37002. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37003. var totalZRotationSteps = 2 + segments;
  37004. var totalYRotationSteps = 2 * totalZRotationSteps;
  37005. var indices = [];
  37006. var positions = [];
  37007. var normals = [];
  37008. var uvs = [];
  37009. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37010. var normalizedZ = zRotationStep / totalZRotationSteps;
  37011. var angleZ = normalizedZ * Math.PI * slice;
  37012. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37013. var normalizedY = yRotationStep / totalYRotationSteps;
  37014. var angleY = normalizedY * Math.PI * 2 * arc;
  37015. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37016. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37017. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37018. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37019. var vertex = complete.multiply(radius);
  37020. var normal = complete.divide(radius).normalize();
  37021. positions.push(vertex.x, vertex.y, vertex.z);
  37022. normals.push(normal.x, normal.y, normal.z);
  37023. uvs.push(normalizedY, normalizedZ);
  37024. }
  37025. if (zRotationStep > 0) {
  37026. var verticesCount = positions.length / 3;
  37027. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37028. indices.push((firstIndex));
  37029. indices.push((firstIndex + 1));
  37030. indices.push(firstIndex + totalYRotationSteps + 1);
  37031. indices.push((firstIndex + totalYRotationSteps + 1));
  37032. indices.push((firstIndex + 1));
  37033. indices.push((firstIndex + totalYRotationSteps + 2));
  37034. }
  37035. }
  37036. }
  37037. // Sides
  37038. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37039. // Result
  37040. var vertexData = new VertexData();
  37041. vertexData.indices = indices;
  37042. vertexData.positions = positions;
  37043. vertexData.normals = normals;
  37044. vertexData.uvs = uvs;
  37045. return vertexData;
  37046. };
  37047. /**
  37048. * Creates the VertexData for a cylinder, cone or prism
  37049. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37050. * * height sets the height (y direction) of the cylinder, optional, default 2
  37051. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37052. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37053. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37054. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37055. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37056. * * 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
  37057. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37058. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37059. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37060. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37061. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37062. * * 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)
  37063. * * 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)
  37064. * @returns the VertexData of the cylinder, cone or prism
  37065. */
  37066. VertexData.CreateCylinder = function (options) {
  37067. var height = options.height || 2;
  37068. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37069. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37070. var tessellation = options.tessellation || 24;
  37071. var subdivisions = options.subdivisions || 1;
  37072. var hasRings = options.hasRings ? true : false;
  37073. var enclose = options.enclose ? true : false;
  37074. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37075. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37076. var faceUV = options.faceUV || new Array(3);
  37077. var faceColors = options.faceColors;
  37078. // default face colors and UV if undefined
  37079. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37080. var ringNb = (hasRings) ? subdivisions : 1;
  37081. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37082. var f;
  37083. for (f = 0; f < surfaceNb; f++) {
  37084. if (faceColors && faceColors[f] === undefined) {
  37085. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37086. }
  37087. }
  37088. for (f = 0; f < surfaceNb; f++) {
  37089. if (faceUV && faceUV[f] === undefined) {
  37090. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37091. }
  37092. }
  37093. var indices = new Array();
  37094. var positions = new Array();
  37095. var normals = new Array();
  37096. var uvs = new Array();
  37097. var colors = new Array();
  37098. var angle_step = Math.PI * 2 * arc / tessellation;
  37099. var angle;
  37100. var h;
  37101. var radius;
  37102. var tan = (diameterBottom - diameterTop) / 2 / height;
  37103. var ringVertex = BABYLON.Vector3.Zero();
  37104. var ringNormal = BABYLON.Vector3.Zero();
  37105. var ringFirstVertex = BABYLON.Vector3.Zero();
  37106. var ringFirstNormal = BABYLON.Vector3.Zero();
  37107. var quadNormal = BABYLON.Vector3.Zero();
  37108. var Y = BABYLON.Axis.Y;
  37109. // positions, normals, uvs
  37110. var i;
  37111. var j;
  37112. var r;
  37113. var ringIdx = 1;
  37114. var s = 1; // surface index
  37115. var cs = 0;
  37116. var v = 0;
  37117. for (i = 0; i <= subdivisions; i++) {
  37118. h = i / subdivisions;
  37119. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37120. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37121. for (r = 0; r < ringIdx; r++) {
  37122. if (hasRings) {
  37123. s += r;
  37124. }
  37125. if (enclose) {
  37126. s += 2 * r;
  37127. }
  37128. for (j = 0; j <= tessellation; j++) {
  37129. angle = j * angle_step;
  37130. // position
  37131. ringVertex.x = Math.cos(-angle) * radius;
  37132. ringVertex.y = -height / 2 + h * height;
  37133. ringVertex.z = Math.sin(-angle) * radius;
  37134. // normal
  37135. if (diameterTop === 0 && i === subdivisions) {
  37136. // if no top cap, reuse former normals
  37137. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37138. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37139. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37140. }
  37141. else {
  37142. ringNormal.x = ringVertex.x;
  37143. ringNormal.z = ringVertex.z;
  37144. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37145. ringNormal.normalize();
  37146. }
  37147. // keep first ring vertex values for enclose
  37148. if (j === 0) {
  37149. ringFirstVertex.copyFrom(ringVertex);
  37150. ringFirstNormal.copyFrom(ringNormal);
  37151. }
  37152. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37153. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37154. if (hasRings) {
  37155. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37156. }
  37157. else {
  37158. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37159. }
  37160. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37161. if (faceColors) {
  37162. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37163. }
  37164. }
  37165. // if enclose, add four vertices and their dedicated normals
  37166. if (arc !== 1 && enclose) {
  37167. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37168. positions.push(0, ringVertex.y, 0);
  37169. positions.push(0, ringVertex.y, 0);
  37170. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37171. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37172. quadNormal.normalize();
  37173. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37174. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37175. quadNormal.normalize();
  37176. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37177. if (hasRings) {
  37178. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37179. }
  37180. else {
  37181. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37182. }
  37183. uvs.push(faceUV[s + 1].x, v);
  37184. uvs.push(faceUV[s + 1].z, v);
  37185. if (hasRings) {
  37186. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37187. }
  37188. else {
  37189. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37190. }
  37191. uvs.push(faceUV[s + 2].x, v);
  37192. uvs.push(faceUV[s + 2].z, v);
  37193. if (faceColors) {
  37194. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37195. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37196. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37197. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37198. }
  37199. }
  37200. if (cs !== s) {
  37201. cs = s;
  37202. }
  37203. }
  37204. }
  37205. // indices
  37206. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37207. var s;
  37208. i = 0;
  37209. for (s = 0; s < subdivisions; s++) {
  37210. var i0 = 0;
  37211. var i1 = 0;
  37212. var i2 = 0;
  37213. var i3 = 0;
  37214. for (j = 0; j < tessellation; j++) {
  37215. i0 = i * (e + 1) + j;
  37216. i1 = (i + 1) * (e + 1) + j;
  37217. i2 = i * (e + 1) + (j + 1);
  37218. i3 = (i + 1) * (e + 1) + (j + 1);
  37219. indices.push(i0, i1, i2);
  37220. indices.push(i3, i2, i1);
  37221. }
  37222. if (arc !== 1 && enclose) { // if enclose, add two quads
  37223. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37224. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37225. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37226. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37227. }
  37228. i = (hasRings) ? (i + 2) : (i + 1);
  37229. }
  37230. // Caps
  37231. var createCylinderCap = function (isTop) {
  37232. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37233. if (radius === 0) {
  37234. return;
  37235. }
  37236. // Cap positions, normals & uvs
  37237. var angle;
  37238. var circleVector;
  37239. var i;
  37240. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37241. var c = null;
  37242. if (faceColors) {
  37243. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37244. }
  37245. // cap center
  37246. var vbase = positions.length / 3;
  37247. var offset = isTop ? height / 2 : -height / 2;
  37248. var center = new BABYLON.Vector3(0, offset, 0);
  37249. positions.push(center.x, center.y, center.z);
  37250. normals.push(0, isTop ? 1 : -1, 0);
  37251. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37252. if (c) {
  37253. colors.push(c.r, c.g, c.b, c.a);
  37254. }
  37255. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37256. for (i = 0; i <= tessellation; i++) {
  37257. angle = Math.PI * 2 * i * arc / tessellation;
  37258. var cos = Math.cos(-angle);
  37259. var sin = Math.sin(-angle);
  37260. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37261. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37262. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37263. normals.push(0, isTop ? 1 : -1, 0);
  37264. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37265. if (c) {
  37266. colors.push(c.r, c.g, c.b, c.a);
  37267. }
  37268. }
  37269. // Cap indices
  37270. for (i = 0; i < tessellation; i++) {
  37271. if (!isTop) {
  37272. indices.push(vbase);
  37273. indices.push(vbase + (i + 1));
  37274. indices.push(vbase + (i + 2));
  37275. }
  37276. else {
  37277. indices.push(vbase);
  37278. indices.push(vbase + (i + 2));
  37279. indices.push(vbase + (i + 1));
  37280. }
  37281. }
  37282. };
  37283. // add caps to geometry
  37284. createCylinderCap(false);
  37285. createCylinderCap(true);
  37286. // Sides
  37287. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37288. var vertexData = new VertexData();
  37289. vertexData.indices = indices;
  37290. vertexData.positions = positions;
  37291. vertexData.normals = normals;
  37292. vertexData.uvs = uvs;
  37293. if (faceColors) {
  37294. vertexData.colors = colors;
  37295. }
  37296. return vertexData;
  37297. };
  37298. /**
  37299. * Creates the VertexData for a torus
  37300. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37301. * * diameter the diameter of the torus, optional default 1
  37302. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37303. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37304. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37305. * * 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)
  37306. * * 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)
  37307. * @returns the VertexData of the torus
  37308. */
  37309. VertexData.CreateTorus = function (options) {
  37310. var indices = [];
  37311. var positions = [];
  37312. var normals = [];
  37313. var uvs = [];
  37314. var diameter = options.diameter || 1;
  37315. var thickness = options.thickness || 0.5;
  37316. var tessellation = options.tessellation || 16;
  37317. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37318. var stride = tessellation + 1;
  37319. for (var i = 0; i <= tessellation; i++) {
  37320. var u = i / tessellation;
  37321. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37322. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37323. for (var j = 0; j <= tessellation; j++) {
  37324. var v = 1 - j / tessellation;
  37325. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37326. var dx = Math.cos(innerAngle);
  37327. var dy = Math.sin(innerAngle);
  37328. // Create a vertex.
  37329. var normal = new BABYLON.Vector3(dx, dy, 0);
  37330. var position = normal.scale(thickness / 2);
  37331. var textureCoordinate = new BABYLON.Vector2(u, v);
  37332. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37333. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37334. positions.push(position.x, position.y, position.z);
  37335. normals.push(normal.x, normal.y, normal.z);
  37336. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37337. // And create indices for two triangles.
  37338. var nextI = (i + 1) % stride;
  37339. var nextJ = (j + 1) % stride;
  37340. indices.push(i * stride + j);
  37341. indices.push(i * stride + nextJ);
  37342. indices.push(nextI * stride + j);
  37343. indices.push(i * stride + nextJ);
  37344. indices.push(nextI * stride + nextJ);
  37345. indices.push(nextI * stride + j);
  37346. }
  37347. }
  37348. // Sides
  37349. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37350. // Result
  37351. var vertexData = new VertexData();
  37352. vertexData.indices = indices;
  37353. vertexData.positions = positions;
  37354. vertexData.normals = normals;
  37355. vertexData.uvs = uvs;
  37356. return vertexData;
  37357. };
  37358. /**
  37359. * Creates the VertexData of the LineSystem
  37360. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37361. * - lines an array of lines, each line being an array of successive Vector3
  37362. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37363. * @returns the VertexData of the LineSystem
  37364. */
  37365. VertexData.CreateLineSystem = function (options) {
  37366. var indices = [];
  37367. var positions = [];
  37368. var lines = options.lines;
  37369. var colors = options.colors;
  37370. var vertexColors = [];
  37371. var idx = 0;
  37372. for (var l = 0; l < lines.length; l++) {
  37373. var points = lines[l];
  37374. for (var index = 0; index < points.length; index++) {
  37375. positions.push(points[index].x, points[index].y, points[index].z);
  37376. if (colors) {
  37377. var color = colors[l];
  37378. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37379. }
  37380. if (index > 0) {
  37381. indices.push(idx - 1);
  37382. indices.push(idx);
  37383. }
  37384. idx++;
  37385. }
  37386. }
  37387. var vertexData = new VertexData();
  37388. vertexData.indices = indices;
  37389. vertexData.positions = positions;
  37390. if (colors) {
  37391. vertexData.colors = vertexColors;
  37392. }
  37393. return vertexData;
  37394. };
  37395. /**
  37396. * Create the VertexData for a DashedLines
  37397. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  37398. * - points an array successive Vector3
  37399. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  37400. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  37401. * - dashNb the intended total number of dashes, optional, default 200
  37402. * @returns the VertexData for the DashedLines
  37403. */
  37404. VertexData.CreateDashedLines = function (options) {
  37405. var dashSize = options.dashSize || 3;
  37406. var gapSize = options.gapSize || 1;
  37407. var dashNb = options.dashNb || 200;
  37408. var points = options.points;
  37409. var positions = new Array();
  37410. var indices = new Array();
  37411. var curvect = BABYLON.Vector3.Zero();
  37412. var lg = 0;
  37413. var nb = 0;
  37414. var shft = 0;
  37415. var dashshft = 0;
  37416. var curshft = 0;
  37417. var idx = 0;
  37418. var i = 0;
  37419. for (i = 0; i < points.length - 1; i++) {
  37420. points[i + 1].subtractToRef(points[i], curvect);
  37421. lg += curvect.length();
  37422. }
  37423. shft = lg / dashNb;
  37424. dashshft = dashSize * shft / (dashSize + gapSize);
  37425. for (i = 0; i < points.length - 1; i++) {
  37426. points[i + 1].subtractToRef(points[i], curvect);
  37427. nb = Math.floor(curvect.length() / shft);
  37428. curvect.normalize();
  37429. for (var j = 0; j < nb; j++) {
  37430. curshft = shft * j;
  37431. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  37432. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  37433. indices.push(idx, idx + 1);
  37434. idx += 2;
  37435. }
  37436. }
  37437. // Result
  37438. var vertexData = new VertexData();
  37439. vertexData.positions = positions;
  37440. vertexData.indices = indices;
  37441. return vertexData;
  37442. };
  37443. /**
  37444. * Creates the VertexData for a Ground
  37445. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37446. * - width the width (x direction) of the ground, optional, default 1
  37447. * - height the height (z direction) of the ground, optional, default 1
  37448. * - subdivisions the number of subdivisions per side, optional, default 1
  37449. * @returns the VertexData of the Ground
  37450. */
  37451. VertexData.CreateGround = function (options) {
  37452. var indices = [];
  37453. var positions = [];
  37454. var normals = [];
  37455. var uvs = [];
  37456. var row, col;
  37457. var width = options.width || 1;
  37458. var height = options.height || 1;
  37459. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  37460. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  37461. for (row = 0; row <= subdivisionsY; row++) {
  37462. for (col = 0; col <= subdivisionsX; col++) {
  37463. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  37464. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37465. positions.push(position.x, position.y, position.z);
  37466. normals.push(normal.x, normal.y, normal.z);
  37467. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  37468. }
  37469. }
  37470. for (row = 0; row < subdivisionsY; row++) {
  37471. for (col = 0; col < subdivisionsX; col++) {
  37472. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37473. indices.push(col + 1 + row * (subdivisionsX + 1));
  37474. indices.push(col + row * (subdivisionsX + 1));
  37475. indices.push(col + (row + 1) * (subdivisionsX + 1));
  37476. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  37477. indices.push(col + row * (subdivisionsX + 1));
  37478. }
  37479. }
  37480. // Result
  37481. var vertexData = new VertexData();
  37482. vertexData.indices = indices;
  37483. vertexData.positions = positions;
  37484. vertexData.normals = normals;
  37485. vertexData.uvs = uvs;
  37486. return vertexData;
  37487. };
  37488. /**
  37489. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  37490. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  37491. * * xmin the ground minimum X coordinate, optional, default -1
  37492. * * zmin the ground minimum Z coordinate, optional, default -1
  37493. * * xmax the ground maximum X coordinate, optional, default 1
  37494. * * zmax the ground maximum Z coordinate, optional, default 1
  37495. * * 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}
  37496. * * 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}
  37497. * @returns the VertexData of the TiledGround
  37498. */
  37499. VertexData.CreateTiledGround = function (options) {
  37500. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  37501. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  37502. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  37503. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  37504. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  37505. var precision = options.precision || { w: 1, h: 1 };
  37506. var indices = new Array();
  37507. var positions = new Array();
  37508. var normals = new Array();
  37509. var uvs = new Array();
  37510. var row, col, tileRow, tileCol;
  37511. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  37512. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  37513. precision.w = (precision.w < 1) ? 1 : precision.w;
  37514. precision.h = (precision.h < 1) ? 1 : precision.h;
  37515. var tileSize = {
  37516. 'w': (xmax - xmin) / subdivisions.w,
  37517. 'h': (zmax - zmin) / subdivisions.h
  37518. };
  37519. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  37520. // Indices
  37521. var base = positions.length / 3;
  37522. var rowLength = precision.w + 1;
  37523. for (row = 0; row < precision.h; row++) {
  37524. for (col = 0; col < precision.w; col++) {
  37525. var square = [
  37526. base + col + row * rowLength,
  37527. base + (col + 1) + row * rowLength,
  37528. base + (col + 1) + (row + 1) * rowLength,
  37529. base + col + (row + 1) * rowLength
  37530. ];
  37531. indices.push(square[1]);
  37532. indices.push(square[2]);
  37533. indices.push(square[3]);
  37534. indices.push(square[0]);
  37535. indices.push(square[1]);
  37536. indices.push(square[3]);
  37537. }
  37538. }
  37539. // Position, normals and uvs
  37540. var position = BABYLON.Vector3.Zero();
  37541. var normal = new BABYLON.Vector3(0, 1.0, 0);
  37542. for (row = 0; row <= precision.h; row++) {
  37543. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  37544. for (col = 0; col <= precision.w; col++) {
  37545. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  37546. position.y = 0;
  37547. positions.push(position.x, position.y, position.z);
  37548. normals.push(normal.x, normal.y, normal.z);
  37549. uvs.push(col / precision.w, row / precision.h);
  37550. }
  37551. }
  37552. }
  37553. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  37554. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  37555. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  37556. }
  37557. }
  37558. // Result
  37559. var vertexData = new VertexData();
  37560. vertexData.indices = indices;
  37561. vertexData.positions = positions;
  37562. vertexData.normals = normals;
  37563. vertexData.uvs = uvs;
  37564. return vertexData;
  37565. };
  37566. /**
  37567. * Creates the VertexData of the Ground designed from a heightmap
  37568. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  37569. * * width the width (x direction) of the ground
  37570. * * height the height (z direction) of the ground
  37571. * * subdivisions the number of subdivisions per side
  37572. * * minHeight the minimum altitude on the ground, optional, default 0
  37573. * * maxHeight the maximum altitude on the ground, optional default 1
  37574. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  37575. * * buffer the array holding the image color data
  37576. * * bufferWidth the width of image
  37577. * * bufferHeight the height of image
  37578. * @returns the VertexData of the Ground designed from a heightmap
  37579. */
  37580. VertexData.CreateGroundFromHeightMap = function (options) {
  37581. var indices = [];
  37582. var positions = [];
  37583. var normals = [];
  37584. var uvs = [];
  37585. var row, col;
  37586. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  37587. // Vertices
  37588. for (row = 0; row <= options.subdivisions; row++) {
  37589. for (col = 0; col <= options.subdivisions; col++) {
  37590. 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));
  37591. // Compute height
  37592. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  37593. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  37594. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  37595. var r = options.buffer[pos] / 255.0;
  37596. var g = options.buffer[pos + 1] / 255.0;
  37597. var b = options.buffer[pos + 2] / 255.0;
  37598. var gradient = r * filter.r + g * filter.g + b * filter.b;
  37599. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  37600. // Add vertex
  37601. positions.push(position.x, position.y, position.z);
  37602. normals.push(0, 0, 0);
  37603. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  37604. }
  37605. }
  37606. // Indices
  37607. for (row = 0; row < options.subdivisions; row++) {
  37608. for (col = 0; col < options.subdivisions; col++) {
  37609. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37610. indices.push(col + 1 + row * (options.subdivisions + 1));
  37611. indices.push(col + row * (options.subdivisions + 1));
  37612. indices.push(col + (row + 1) * (options.subdivisions + 1));
  37613. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  37614. indices.push(col + row * (options.subdivisions + 1));
  37615. }
  37616. }
  37617. // Normals
  37618. VertexData.ComputeNormals(positions, indices, normals);
  37619. // Result
  37620. var vertexData = new VertexData();
  37621. vertexData.indices = indices;
  37622. vertexData.positions = positions;
  37623. vertexData.normals = normals;
  37624. vertexData.uvs = uvs;
  37625. return vertexData;
  37626. };
  37627. /**
  37628. * Creates the VertexData for a Plane
  37629. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  37630. * * size sets the width and height of the plane to the value of size, optional default 1
  37631. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  37632. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  37633. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37634. * * 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)
  37635. * * 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)
  37636. * @returns the VertexData of the box
  37637. */
  37638. VertexData.CreatePlane = function (options) {
  37639. var indices = [];
  37640. var positions = [];
  37641. var normals = [];
  37642. var uvs = [];
  37643. var width = options.width || options.size || 1;
  37644. var height = options.height || options.size || 1;
  37645. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37646. // Vertices
  37647. var halfWidth = width / 2.0;
  37648. var halfHeight = height / 2.0;
  37649. positions.push(-halfWidth, -halfHeight, 0);
  37650. normals.push(0, 0, -1.0);
  37651. uvs.push(0.0, 0.0);
  37652. positions.push(halfWidth, -halfHeight, 0);
  37653. normals.push(0, 0, -1.0);
  37654. uvs.push(1.0, 0.0);
  37655. positions.push(halfWidth, halfHeight, 0);
  37656. normals.push(0, 0, -1.0);
  37657. uvs.push(1.0, 1.0);
  37658. positions.push(-halfWidth, halfHeight, 0);
  37659. normals.push(0, 0, -1.0);
  37660. uvs.push(0.0, 1.0);
  37661. // Indices
  37662. indices.push(0);
  37663. indices.push(1);
  37664. indices.push(2);
  37665. indices.push(0);
  37666. indices.push(2);
  37667. indices.push(3);
  37668. // Sides
  37669. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37670. // Result
  37671. var vertexData = new VertexData();
  37672. vertexData.indices = indices;
  37673. vertexData.positions = positions;
  37674. vertexData.normals = normals;
  37675. vertexData.uvs = uvs;
  37676. return vertexData;
  37677. };
  37678. /**
  37679. * Creates the VertexData of the Disc or regular Polygon
  37680. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  37681. * * radius the radius of the disc, optional default 0.5
  37682. * * tessellation the number of polygon sides, optional, default 64
  37683. * * 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
  37684. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37685. * * 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)
  37686. * * 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)
  37687. * @returns the VertexData of the box
  37688. */
  37689. VertexData.CreateDisc = function (options) {
  37690. var positions = new Array();
  37691. var indices = new Array();
  37692. var normals = new Array();
  37693. var uvs = new Array();
  37694. var radius = options.radius || 0.5;
  37695. var tessellation = options.tessellation || 64;
  37696. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37697. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37698. // positions and uvs
  37699. positions.push(0, 0, 0); // disc center first
  37700. uvs.push(0.5, 0.5);
  37701. var theta = Math.PI * 2 * arc;
  37702. var step = theta / tessellation;
  37703. for (var a = 0; a < theta; a += step) {
  37704. var x = Math.cos(a);
  37705. var y = Math.sin(a);
  37706. var u = (x + 1) / 2;
  37707. var v = (1 - y) / 2;
  37708. positions.push(radius * x, radius * y, 0);
  37709. uvs.push(u, v);
  37710. }
  37711. if (arc === 1) {
  37712. positions.push(positions[3], positions[4], positions[5]); // close the circle
  37713. uvs.push(uvs[2], uvs[3]);
  37714. }
  37715. //indices
  37716. var vertexNb = positions.length / 3;
  37717. for (var i = 1; i < vertexNb - 1; i++) {
  37718. indices.push(i + 1, 0, i);
  37719. }
  37720. // result
  37721. VertexData.ComputeNormals(positions, indices, normals);
  37722. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37723. var vertexData = new VertexData();
  37724. vertexData.indices = indices;
  37725. vertexData.positions = positions;
  37726. vertexData.normals = normals;
  37727. vertexData.uvs = uvs;
  37728. return vertexData;
  37729. };
  37730. /**
  37731. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  37732. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  37733. * @param polygon a mesh built from polygonTriangulation.build()
  37734. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37735. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37736. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37737. * @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)
  37738. * @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)
  37739. * @returns the VertexData of the Polygon
  37740. */
  37741. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  37742. var faceUV = fUV || new Array(3);
  37743. var faceColors = fColors;
  37744. var colors = [];
  37745. // default face colors and UV if undefined
  37746. for (var f = 0; f < 3; f++) {
  37747. if (faceUV[f] === undefined) {
  37748. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37749. }
  37750. if (faceColors && faceColors[f] === undefined) {
  37751. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37752. }
  37753. }
  37754. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  37755. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  37756. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  37757. var indices = polygon.getIndices();
  37758. // set face colours and textures
  37759. var idx = 0;
  37760. var face = 0;
  37761. for (var index = 0; index < normals.length; index += 3) {
  37762. //Edge Face no. 1
  37763. if (Math.abs(normals[index + 1]) < 0.001) {
  37764. face = 1;
  37765. }
  37766. //Top Face no. 0
  37767. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  37768. face = 0;
  37769. }
  37770. //Bottom Face no. 2
  37771. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  37772. face = 2;
  37773. }
  37774. idx = index / 3;
  37775. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  37776. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  37777. if (faceColors) {
  37778. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  37779. }
  37780. }
  37781. // sides
  37782. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  37783. // Result
  37784. var vertexData = new VertexData();
  37785. vertexData.indices = indices;
  37786. vertexData.positions = positions;
  37787. vertexData.normals = normals;
  37788. vertexData.uvs = uvs;
  37789. if (faceColors) {
  37790. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37791. vertexData.colors = totalColors;
  37792. }
  37793. return vertexData;
  37794. };
  37795. /**
  37796. * Creates the VertexData of the IcoSphere
  37797. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  37798. * * radius the radius of the IcoSphere, optional default 1
  37799. * * radiusX allows stretching in the x direction, optional, default radius
  37800. * * radiusY allows stretching in the y direction, optional, default radius
  37801. * * radiusZ allows stretching in the z direction, optional, default radius
  37802. * * flat when true creates a flat shaded mesh, optional, default true
  37803. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  37804. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37805. * * 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)
  37806. * * 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)
  37807. * @returns the VertexData of the IcoSphere
  37808. */
  37809. VertexData.CreateIcoSphere = function (options) {
  37810. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37811. var radius = options.radius || 1;
  37812. var flat = (options.flat === undefined) ? true : options.flat;
  37813. var subdivisions = options.subdivisions || 4;
  37814. var radiusX = options.radiusX || radius;
  37815. var radiusY = options.radiusY || radius;
  37816. var radiusZ = options.radiusZ || radius;
  37817. var t = (1 + Math.sqrt(5)) / 2;
  37818. // 12 vertex x,y,z
  37819. var ico_vertices = [
  37820. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  37821. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  37822. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  37823. ];
  37824. // index of 3 vertex makes a face of icopshere
  37825. var ico_indices = [
  37826. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  37827. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  37828. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  37829. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  37830. ];
  37831. // vertex for uv have aliased position, not for UV
  37832. var vertices_unalias_id = [
  37833. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  37834. // vertex alias
  37835. 0,
  37836. 2,
  37837. 3,
  37838. 3,
  37839. 3,
  37840. 4,
  37841. 7,
  37842. 8,
  37843. 9,
  37844. 9,
  37845. 10,
  37846. 11 // 23: B + 12
  37847. ];
  37848. // uv as integer step (not pixels !)
  37849. var ico_vertexuv = [
  37850. 5, 1, 3, 1, 6, 4, 0, 0,
  37851. 5, 3, 4, 2, 2, 2, 4, 0,
  37852. 2, 0, 1, 1, 6, 0, 6, 2,
  37853. // vertex alias (for same vertex on different faces)
  37854. 0, 4,
  37855. 3, 3,
  37856. 4, 4,
  37857. 3, 1,
  37858. 4, 2,
  37859. 4, 4,
  37860. 0, 2,
  37861. 1, 1,
  37862. 2, 2,
  37863. 3, 3,
  37864. 1, 3,
  37865. 2, 4 // 23: B + 12
  37866. ];
  37867. // Vertices[0, 1, ...9, A, B] : position on UV plane
  37868. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  37869. // First island of uv mapping
  37870. // v = 4h 3+ 2
  37871. // v = 3h 9+ 4
  37872. // v = 2h 9+ 5 B
  37873. // v = 1h 9 1 0
  37874. // v = 0h 3 8 7 A
  37875. // u = 0 1 2 3 4 5 6 *a
  37876. // Second island of uv mapping
  37877. // v = 4h 0+ B+ 4+
  37878. // v = 3h A+ 2+
  37879. // v = 2h 7+ 6 3+
  37880. // v = 1h 8+ 3+
  37881. // v = 0h
  37882. // u = 0 1 2 3 4 5 6 *a
  37883. // Face layout on texture UV mapping
  37884. // ============
  37885. // \ 4 /\ 16 / ======
  37886. // \ / \ / /\ 11 /
  37887. // \/ 7 \/ / \ /
  37888. // ======= / 10 \/
  37889. // /\ 17 /\ =======
  37890. // / \ / \ \ 15 /\
  37891. // / 8 \/ 12 \ \ / \
  37892. // ============ \/ 6 \
  37893. // \ 18 /\ ============
  37894. // \ / \ \ 5 /\ 0 /
  37895. // \/ 13 \ \ / \ /
  37896. // ======= \/ 1 \/
  37897. // =============
  37898. // /\ 19 /\ 2 /\
  37899. // / \ / \ / \
  37900. // / 14 \/ 9 \/ 3 \
  37901. // ===================
  37902. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  37903. var ustep = 138 / 1024;
  37904. var vstep = 239 / 1024;
  37905. var uoffset = 60 / 1024;
  37906. var voffset = 26 / 1024;
  37907. // Second island should have margin, not to touch the first island
  37908. // avoid any borderline artefact in pixel rounding
  37909. var island_u_offset = -40 / 1024;
  37910. var island_v_offset = +20 / 1024;
  37911. // face is either island 0 or 1 :
  37912. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  37913. var island = [
  37914. 0, 0, 0, 0, 1,
  37915. 0, 0, 1, 1, 0,
  37916. 0, 0, 1, 1, 0,
  37917. 0, 1, 1, 1, 0 // 15 - 19
  37918. ];
  37919. var indices = new Array();
  37920. var positions = new Array();
  37921. var normals = new Array();
  37922. var uvs = new Array();
  37923. var current_indice = 0;
  37924. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  37925. var face_vertex_pos = new Array(3);
  37926. var face_vertex_uv = new Array(3);
  37927. var v012;
  37928. for (v012 = 0; v012 < 3; v012++) {
  37929. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  37930. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  37931. }
  37932. // create all with normals
  37933. for (var face = 0; face < 20; face++) {
  37934. // 3 vertex per face
  37935. for (v012 = 0; v012 < 3; v012++) {
  37936. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  37937. var v_id = ico_indices[3 * face + v012];
  37938. // vertex have 3D position (x,y,z)
  37939. 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]);
  37940. // Normalize to get normal, then scale to radius
  37941. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  37942. // uv Coordinates from vertex ID
  37943. 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);
  37944. }
  37945. // Subdivide the face (interpolate pos, norm, uv)
  37946. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  37947. // - norm is linear interpolation of vertex corner normal
  37948. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  37949. // - uv is linear interpolation
  37950. //
  37951. // Topology is as below for sub-divide by 2
  37952. // vertex shown as v0,v1,v2
  37953. // interp index is i1 to progress in range [v0,v1[
  37954. // interp index is i2 to progress in range [v0,v2[
  37955. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  37956. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  37957. //
  37958. //
  37959. // i2 v2
  37960. // ^ ^
  37961. // / / \
  37962. // / / \
  37963. // / / \
  37964. // / / (0,1) \
  37965. // / #---------\
  37966. // / / \ (0,0)'/ \
  37967. // / / \ / \
  37968. // / / \ / \
  37969. // / / (0,0) \ / (1,0) \
  37970. // / #---------#---------\
  37971. // v0 v1
  37972. //
  37973. // --------------------> i1
  37974. //
  37975. // interp of (i1,i2):
  37976. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  37977. // along i1 : lerp(x0,x1, i1/(S-i2))
  37978. //
  37979. // centroid of triangle is needed to get help normal computation
  37980. // (c1,c2) are used for centroid location
  37981. var interp_vertex = function (i1, i2, c1, c2) {
  37982. // vertex is interpolated from
  37983. // - face_vertex_pos[0..2]
  37984. // - face_vertex_uv[0..2]
  37985. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  37986. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  37987. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  37988. pos_interp.normalize();
  37989. var vertex_normal;
  37990. if (flat) {
  37991. // in flat mode, recalculate normal as face centroid normal
  37992. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  37993. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  37994. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  37995. }
  37996. else {
  37997. // in smooth mode, recalculate normal from each single vertex position
  37998. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  37999. }
  38000. // Vertex normal need correction due to X,Y,Z radius scaling
  38001. vertex_normal.x /= radiusX;
  38002. vertex_normal.y /= radiusY;
  38003. vertex_normal.z /= radiusZ;
  38004. vertex_normal.normalize();
  38005. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38006. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38007. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38008. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38009. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38010. uvs.push(uv_interp.x, uv_interp.y);
  38011. // push each vertex has member of a face
  38012. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38013. indices.push(current_indice);
  38014. current_indice++;
  38015. };
  38016. for (var i2 = 0; i2 < subdivisions; i2++) {
  38017. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38018. // face : (i1,i2) for /\ :
  38019. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38020. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38021. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38022. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38023. if (i1 + i2 + 1 < subdivisions) {
  38024. // face : (i1,i2)' for \/ :
  38025. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38026. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38027. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38028. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38029. }
  38030. }
  38031. }
  38032. }
  38033. // Sides
  38034. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38035. // Result
  38036. var vertexData = new VertexData();
  38037. vertexData.indices = indices;
  38038. vertexData.positions = positions;
  38039. vertexData.normals = normals;
  38040. vertexData.uvs = uvs;
  38041. return vertexData;
  38042. };
  38043. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38044. /**
  38045. * Creates the VertexData for a Polyhedron
  38046. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38047. * * type provided types are:
  38048. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38049. * * 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)
  38050. * * size the size of the IcoSphere, optional default 1
  38051. * * sizeX allows stretching in the x direction, optional, default size
  38052. * * sizeY allows stretching in the y direction, optional, default size
  38053. * * sizeZ allows stretching in the z direction, optional, default size
  38054. * * 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
  38055. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38056. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38057. * * flat when true creates a flat shaded mesh, optional, default true
  38058. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38059. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38060. * * 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)
  38061. * * 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)
  38062. * @returns the VertexData of the Polyhedron
  38063. */
  38064. VertexData.CreatePolyhedron = function (options) {
  38065. // provided polyhedron types :
  38066. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38067. // 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)
  38068. var polyhedra = [];
  38069. 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]] };
  38070. 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]] };
  38071. polyhedra[2] = {
  38072. 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]],
  38073. 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]]
  38074. };
  38075. polyhedra[3] = {
  38076. 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]],
  38077. 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]]
  38078. };
  38079. polyhedra[4] = {
  38080. 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]],
  38081. 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]]
  38082. };
  38083. 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]] };
  38084. 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]] };
  38085. 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]] };
  38086. 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]] };
  38087. 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]] };
  38088. 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]] };
  38089. 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]] };
  38090. 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]] };
  38091. 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]] };
  38092. polyhedra[14] = {
  38093. 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]],
  38094. 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]]
  38095. };
  38096. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38097. var size = options.size;
  38098. var sizeX = options.sizeX || size || 1;
  38099. var sizeY = options.sizeY || size || 1;
  38100. var sizeZ = options.sizeZ || size || 1;
  38101. var data = options.custom || polyhedra[type];
  38102. var nbfaces = data.face.length;
  38103. var faceUV = options.faceUV || new Array(nbfaces);
  38104. var faceColors = options.faceColors;
  38105. var flat = (options.flat === undefined) ? true : options.flat;
  38106. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38107. var positions = new Array();
  38108. var indices = new Array();
  38109. var normals = new Array();
  38110. var uvs = new Array();
  38111. var colors = new Array();
  38112. var index = 0;
  38113. var faceIdx = 0; // face cursor in the array "indexes"
  38114. var indexes = new Array();
  38115. var i = 0;
  38116. var f = 0;
  38117. var u, v, ang, x, y, tmp;
  38118. // default face colors and UV if undefined
  38119. if (flat) {
  38120. for (f = 0; f < nbfaces; f++) {
  38121. if (faceColors && faceColors[f] === undefined) {
  38122. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38123. }
  38124. if (faceUV && faceUV[f] === undefined) {
  38125. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38126. }
  38127. }
  38128. }
  38129. if (!flat) {
  38130. for (i = 0; i < data.vertex.length; i++) {
  38131. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38132. uvs.push(0, 0);
  38133. }
  38134. for (f = 0; f < nbfaces; f++) {
  38135. for (i = 0; i < data.face[f].length - 2; i++) {
  38136. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38137. }
  38138. }
  38139. }
  38140. else {
  38141. for (f = 0; f < nbfaces; f++) {
  38142. var fl = data.face[f].length; // number of vertices of the current face
  38143. ang = 2 * Math.PI / fl;
  38144. x = 0.5 * Math.tan(ang / 2);
  38145. y = 0.5;
  38146. // positions, uvs, colors
  38147. for (i = 0; i < fl; i++) {
  38148. // positions
  38149. 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);
  38150. indexes.push(index);
  38151. index++;
  38152. // uvs
  38153. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38154. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38155. uvs.push(u, v);
  38156. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38157. y = x * Math.sin(ang) + y * Math.cos(ang);
  38158. x = tmp;
  38159. // colors
  38160. if (faceColors) {
  38161. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38162. }
  38163. }
  38164. // indices from indexes
  38165. for (i = 0; i < fl - 2; i++) {
  38166. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38167. }
  38168. faceIdx += fl;
  38169. }
  38170. }
  38171. VertexData.ComputeNormals(positions, indices, normals);
  38172. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38173. var vertexData = new VertexData();
  38174. vertexData.positions = positions;
  38175. vertexData.indices = indices;
  38176. vertexData.normals = normals;
  38177. vertexData.uvs = uvs;
  38178. if (faceColors && flat) {
  38179. vertexData.colors = colors;
  38180. }
  38181. return vertexData;
  38182. };
  38183. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38184. /**
  38185. * Creates the VertexData for a TorusKnot
  38186. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38187. * * radius the radius of the torus knot, optional, default 2
  38188. * * tube the thickness of the tube, optional, default 0.5
  38189. * * radialSegments the number of sides on each tube segments, optional, default 32
  38190. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38191. * * p the number of windings around the z axis, optional, default 2
  38192. * * q the number of windings around the x axis, optional, default 3
  38193. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38194. * * 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)
  38195. * * 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)
  38196. * @returns the VertexData of the Torus Knot
  38197. */
  38198. VertexData.CreateTorusKnot = function (options) {
  38199. var indices = new Array();
  38200. var positions = new Array();
  38201. var normals = new Array();
  38202. var uvs = new Array();
  38203. var radius = options.radius || 2;
  38204. var tube = options.tube || 0.5;
  38205. var radialSegments = options.radialSegments || 32;
  38206. var tubularSegments = options.tubularSegments || 32;
  38207. var p = options.p || 2;
  38208. var q = options.q || 3;
  38209. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38210. // Helper
  38211. var getPos = function (angle) {
  38212. var cu = Math.cos(angle);
  38213. var su = Math.sin(angle);
  38214. var quOverP = q / p * angle;
  38215. var cs = Math.cos(quOverP);
  38216. var tx = radius * (2 + cs) * 0.5 * cu;
  38217. var ty = radius * (2 + cs) * su * 0.5;
  38218. var tz = radius * Math.sin(quOverP) * 0.5;
  38219. return new BABYLON.Vector3(tx, ty, tz);
  38220. };
  38221. // Vertices
  38222. var i;
  38223. var j;
  38224. for (i = 0; i <= radialSegments; i++) {
  38225. var modI = i % radialSegments;
  38226. var u = modI / radialSegments * 2 * p * Math.PI;
  38227. var p1 = getPos(u);
  38228. var p2 = getPos(u + 0.01);
  38229. var tang = p2.subtract(p1);
  38230. var n = p2.add(p1);
  38231. var bitan = BABYLON.Vector3.Cross(tang, n);
  38232. n = BABYLON.Vector3.Cross(bitan, tang);
  38233. bitan.normalize();
  38234. n.normalize();
  38235. for (j = 0; j < tubularSegments; j++) {
  38236. var modJ = j % tubularSegments;
  38237. var v = modJ / tubularSegments * 2 * Math.PI;
  38238. var cx = -tube * Math.cos(v);
  38239. var cy = tube * Math.sin(v);
  38240. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38241. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38242. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38243. uvs.push(i / radialSegments);
  38244. uvs.push(j / tubularSegments);
  38245. }
  38246. }
  38247. for (i = 0; i < radialSegments; i++) {
  38248. for (j = 0; j < tubularSegments; j++) {
  38249. var jNext = (j + 1) % tubularSegments;
  38250. var a = i * tubularSegments + j;
  38251. var b = (i + 1) * tubularSegments + j;
  38252. var c = (i + 1) * tubularSegments + jNext;
  38253. var d = i * tubularSegments + jNext;
  38254. indices.push(d);
  38255. indices.push(b);
  38256. indices.push(a);
  38257. indices.push(d);
  38258. indices.push(c);
  38259. indices.push(b);
  38260. }
  38261. }
  38262. // Normals
  38263. VertexData.ComputeNormals(positions, indices, normals);
  38264. // Sides
  38265. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38266. // Result
  38267. var vertexData = new VertexData();
  38268. vertexData.indices = indices;
  38269. vertexData.positions = positions;
  38270. vertexData.normals = normals;
  38271. vertexData.uvs = uvs;
  38272. return vertexData;
  38273. };
  38274. // Tools
  38275. /**
  38276. * Compute normals for given positions and indices
  38277. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38278. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38279. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38280. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38281. * * facetNormals : optional array of facet normals (vector3)
  38282. * * facetPositions : optional array of facet positions (vector3)
  38283. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38284. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38285. * * bInfo : optional bounding info, required for facetPartitioning computation
  38286. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38287. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38288. * * useRightHandedSystem: optional boolean to for right handed system computation
  38289. * * depthSort : optional boolean to enable the facet depth sort computation
  38290. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38291. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38292. */
  38293. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38294. // temporary scalar variables
  38295. var index = 0; // facet index
  38296. var p1p2x = 0.0; // p1p2 vector x coordinate
  38297. var p1p2y = 0.0; // p1p2 vector y coordinate
  38298. var p1p2z = 0.0; // p1p2 vector z coordinate
  38299. var p3p2x = 0.0; // p3p2 vector x coordinate
  38300. var p3p2y = 0.0; // p3p2 vector y coordinate
  38301. var p3p2z = 0.0; // p3p2 vector z coordinate
  38302. var faceNormalx = 0.0; // facet normal x coordinate
  38303. var faceNormaly = 0.0; // facet normal y coordinate
  38304. var faceNormalz = 0.0; // facet normal z coordinate
  38305. var length = 0.0; // facet normal length before normalization
  38306. var v1x = 0; // vector1 x index in the positions array
  38307. var v1y = 0; // vector1 y index in the positions array
  38308. var v1z = 0; // vector1 z index in the positions array
  38309. var v2x = 0; // vector2 x index in the positions array
  38310. var v2y = 0; // vector2 y index in the positions array
  38311. var v2z = 0; // vector2 z index in the positions array
  38312. var v3x = 0; // vector3 x index in the positions array
  38313. var v3y = 0; // vector3 y index in the positions array
  38314. var v3z = 0; // vector3 z index in the positions array
  38315. var computeFacetNormals = false;
  38316. var computeFacetPositions = false;
  38317. var computeFacetPartitioning = false;
  38318. var computeDepthSort = false;
  38319. var faceNormalSign = 1;
  38320. var ratio = 0;
  38321. var distanceTo = null;
  38322. if (options) {
  38323. computeFacetNormals = (options.facetNormals) ? true : false;
  38324. computeFacetPositions = (options.facetPositions) ? true : false;
  38325. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38326. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38327. ratio = options.ratio || 0;
  38328. computeDepthSort = (options.depthSort) ? true : false;
  38329. distanceTo = (options.distanceTo);
  38330. if (computeDepthSort) {
  38331. if (distanceTo === undefined) {
  38332. distanceTo = BABYLON.Vector3.Zero();
  38333. }
  38334. var depthSortedFacets = options.depthSortedFacets;
  38335. }
  38336. }
  38337. // facetPartitioning reinit if needed
  38338. var xSubRatio = 0;
  38339. var ySubRatio = 0;
  38340. var zSubRatio = 0;
  38341. var subSq = 0;
  38342. if (computeFacetPartitioning && options && options.bbSize) {
  38343. var ox = 0; // X partitioning index for facet position
  38344. var oy = 0; // Y partinioning index for facet position
  38345. var oz = 0; // Z partinioning index for facet position
  38346. var b1x = 0; // X partitioning index for facet v1 vertex
  38347. var b1y = 0; // Y partitioning index for facet v1 vertex
  38348. var b1z = 0; // z partitioning index for facet v1 vertex
  38349. var b2x = 0; // X partitioning index for facet v2 vertex
  38350. var b2y = 0; // Y partitioning index for facet v2 vertex
  38351. var b2z = 0; // Z partitioning index for facet v2 vertex
  38352. var b3x = 0; // X partitioning index for facet v3 vertex
  38353. var b3y = 0; // Y partitioning index for facet v3 vertex
  38354. var b3z = 0; // Z partitioning index for facet v3 vertex
  38355. var block_idx_o = 0; // facet barycenter block index
  38356. var block_idx_v1 = 0; // v1 vertex block index
  38357. var block_idx_v2 = 0; // v2 vertex block index
  38358. var block_idx_v3 = 0; // v3 vertex block index
  38359. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38360. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38361. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38362. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38363. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38364. subSq = options.subDiv.max * options.subDiv.max;
  38365. options.facetPartitioning.length = 0;
  38366. }
  38367. // reset the normals
  38368. for (index = 0; index < positions.length; index++) {
  38369. normals[index] = 0.0;
  38370. }
  38371. // Loop : 1 indice triplet = 1 facet
  38372. var nbFaces = (indices.length / 3) | 0;
  38373. for (index = 0; index < nbFaces; index++) {
  38374. // get the indexes of the coordinates of each vertex of the facet
  38375. v1x = indices[index * 3] * 3;
  38376. v1y = v1x + 1;
  38377. v1z = v1x + 2;
  38378. v2x = indices[index * 3 + 1] * 3;
  38379. v2y = v2x + 1;
  38380. v2z = v2x + 2;
  38381. v3x = indices[index * 3 + 2] * 3;
  38382. v3y = v3x + 1;
  38383. v3z = v3x + 2;
  38384. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38385. p1p2y = positions[v1y] - positions[v2y];
  38386. p1p2z = positions[v1z] - positions[v2z];
  38387. p3p2x = positions[v3x] - positions[v2x];
  38388. p3p2y = positions[v3y] - positions[v2y];
  38389. p3p2z = positions[v3z] - positions[v2z];
  38390. // compute the face normal with the cross product
  38391. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38392. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  38393. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  38394. // normalize this normal and store it in the array facetData
  38395. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38396. length = (length === 0) ? 1.0 : length;
  38397. faceNormalx /= length;
  38398. faceNormaly /= length;
  38399. faceNormalz /= length;
  38400. if (computeFacetNormals && options) {
  38401. options.facetNormals[index].x = faceNormalx;
  38402. options.facetNormals[index].y = faceNormaly;
  38403. options.facetNormals[index].z = faceNormalz;
  38404. }
  38405. if (computeFacetPositions && options) {
  38406. // compute and the facet barycenter coordinates in the array facetPositions
  38407. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  38408. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  38409. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  38410. }
  38411. if (computeFacetPartitioning && options) {
  38412. // store the facet indexes in arrays in the main facetPartitioning array :
  38413. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  38414. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  38415. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  38416. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  38417. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38418. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38419. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38420. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38421. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38422. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38423. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  38424. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  38425. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  38426. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  38427. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  38428. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  38429. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  38430. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  38431. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  38432. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  38433. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  38434. // push each facet index in each block containing the vertex
  38435. options.facetPartitioning[block_idx_v1].push(index);
  38436. if (block_idx_v2 != block_idx_v1) {
  38437. options.facetPartitioning[block_idx_v2].push(index);
  38438. }
  38439. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  38440. options.facetPartitioning[block_idx_v3].push(index);
  38441. }
  38442. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  38443. options.facetPartitioning[block_idx_o].push(index);
  38444. }
  38445. }
  38446. if (computeDepthSort && options && options.facetPositions) {
  38447. var dsf = depthSortedFacets[index];
  38448. dsf.ind = index * 3;
  38449. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  38450. }
  38451. // compute the normals anyway
  38452. normals[v1x] += faceNormalx; // accumulate all the normals per face
  38453. normals[v1y] += faceNormaly;
  38454. normals[v1z] += faceNormalz;
  38455. normals[v2x] += faceNormalx;
  38456. normals[v2y] += faceNormaly;
  38457. normals[v2z] += faceNormalz;
  38458. normals[v3x] += faceNormalx;
  38459. normals[v3y] += faceNormaly;
  38460. normals[v3z] += faceNormalz;
  38461. }
  38462. // last normalization of each normal
  38463. for (index = 0; index < normals.length / 3; index++) {
  38464. faceNormalx = normals[index * 3];
  38465. faceNormaly = normals[index * 3 + 1];
  38466. faceNormalz = normals[index * 3 + 2];
  38467. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  38468. length = (length === 0) ? 1.0 : length;
  38469. faceNormalx /= length;
  38470. faceNormaly /= length;
  38471. faceNormalz /= length;
  38472. normals[index * 3] = faceNormalx;
  38473. normals[index * 3 + 1] = faceNormaly;
  38474. normals[index * 3 + 2] = faceNormalz;
  38475. }
  38476. };
  38477. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  38478. var li = indices.length;
  38479. var ln = normals.length;
  38480. var i;
  38481. var n;
  38482. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38483. switch (sideOrientation) {
  38484. case BABYLON.Mesh.FRONTSIDE:
  38485. // nothing changed
  38486. break;
  38487. case BABYLON.Mesh.BACKSIDE:
  38488. var tmp;
  38489. // indices
  38490. for (i = 0; i < li; i += 3) {
  38491. tmp = indices[i];
  38492. indices[i] = indices[i + 2];
  38493. indices[i + 2] = tmp;
  38494. }
  38495. // normals
  38496. for (n = 0; n < ln; n++) {
  38497. normals[n] = -normals[n];
  38498. }
  38499. break;
  38500. case BABYLON.Mesh.DOUBLESIDE:
  38501. // positions
  38502. var lp = positions.length;
  38503. var l = lp / 3;
  38504. for (var p = 0; p < lp; p++) {
  38505. positions[lp + p] = positions[p];
  38506. }
  38507. // indices
  38508. for (i = 0; i < li; i += 3) {
  38509. indices[i + li] = indices[i + 2] + l;
  38510. indices[i + 1 + li] = indices[i + 1] + l;
  38511. indices[i + 2 + li] = indices[i] + l;
  38512. }
  38513. // normals
  38514. for (n = 0; n < ln; n++) {
  38515. normals[ln + n] = -normals[n];
  38516. }
  38517. // uvs
  38518. var lu = uvs.length;
  38519. var u = 0;
  38520. for (u = 0; u < lu; u++) {
  38521. uvs[u + lu] = uvs[u];
  38522. }
  38523. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38524. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  38525. u = 0;
  38526. for (i = 0; i < lu / 2; i++) {
  38527. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  38528. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  38529. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  38530. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  38531. u += 2;
  38532. }
  38533. break;
  38534. }
  38535. };
  38536. /**
  38537. * Applies VertexData created from the imported parameters to the geometry
  38538. * @param parsedVertexData the parsed data from an imported file
  38539. * @param geometry the geometry to apply the VertexData to
  38540. */
  38541. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  38542. var vertexData = new VertexData();
  38543. // positions
  38544. var positions = parsedVertexData.positions;
  38545. if (positions) {
  38546. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  38547. }
  38548. // normals
  38549. var normals = parsedVertexData.normals;
  38550. if (normals) {
  38551. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  38552. }
  38553. // tangents
  38554. var tangents = parsedVertexData.tangents;
  38555. if (tangents) {
  38556. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  38557. }
  38558. // uvs
  38559. var uvs = parsedVertexData.uvs;
  38560. if (uvs) {
  38561. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  38562. }
  38563. // uv2s
  38564. var uv2s = parsedVertexData.uv2s;
  38565. if (uv2s) {
  38566. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  38567. }
  38568. // uv3s
  38569. var uv3s = parsedVertexData.uv3s;
  38570. if (uv3s) {
  38571. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  38572. }
  38573. // uv4s
  38574. var uv4s = parsedVertexData.uv4s;
  38575. if (uv4s) {
  38576. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  38577. }
  38578. // uv5s
  38579. var uv5s = parsedVertexData.uv5s;
  38580. if (uv5s) {
  38581. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  38582. }
  38583. // uv6s
  38584. var uv6s = parsedVertexData.uv6s;
  38585. if (uv6s) {
  38586. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  38587. }
  38588. // colors
  38589. var colors = parsedVertexData.colors;
  38590. if (colors) {
  38591. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  38592. }
  38593. // matricesIndices
  38594. var matricesIndices = parsedVertexData.matricesIndices;
  38595. if (matricesIndices) {
  38596. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  38597. }
  38598. // matricesWeights
  38599. var matricesWeights = parsedVertexData.matricesWeights;
  38600. if (matricesWeights) {
  38601. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  38602. }
  38603. // indices
  38604. var indices = parsedVertexData.indices;
  38605. if (indices) {
  38606. vertexData.indices = indices;
  38607. }
  38608. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  38609. };
  38610. return VertexData;
  38611. }());
  38612. BABYLON.VertexData = VertexData;
  38613. })(BABYLON || (BABYLON = {}));
  38614. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  38615. var BABYLON;
  38616. (function (BABYLON) {
  38617. /**
  38618. * Class used to store geometry data (vertex buffers + index buffer)
  38619. */
  38620. var Geometry = /** @class */ (function () {
  38621. /**
  38622. * Creates a new geometry
  38623. * @param id defines the unique ID
  38624. * @param scene defines the hosting scene
  38625. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  38626. * @param updatable defines if geometry must be updatable (false by default)
  38627. * @param mesh defines the mesh that will be associated with the geometry
  38628. */
  38629. function Geometry(id, scene, vertexData, updatable, mesh) {
  38630. if (updatable === void 0) { updatable = false; }
  38631. if (mesh === void 0) { mesh = null; }
  38632. /**
  38633. * Gets the delay loading state of the geometry (none by default which means not delayed)
  38634. */
  38635. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  38636. this._totalVertices = 0;
  38637. this._isDisposed = false;
  38638. this._indexBufferIsUpdatable = false;
  38639. this.id = id;
  38640. this._engine = scene.getEngine();
  38641. this._meshes = [];
  38642. this._scene = scene;
  38643. //Init vertex buffer cache
  38644. this._vertexBuffers = {};
  38645. this._indices = [];
  38646. this._updatable = updatable;
  38647. // vertexData
  38648. if (vertexData) {
  38649. this.setAllVerticesData(vertexData, updatable);
  38650. }
  38651. else {
  38652. this._totalVertices = 0;
  38653. this._indices = [];
  38654. }
  38655. if (this._engine.getCaps().vertexArrayObject) {
  38656. this._vertexArrayObjects = {};
  38657. }
  38658. // applyToMesh
  38659. if (mesh) {
  38660. if (mesh.getClassName() === "LinesMesh") {
  38661. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  38662. this._updateExtend();
  38663. }
  38664. this.applyToMesh(mesh);
  38665. mesh.computeWorldMatrix(true);
  38666. }
  38667. }
  38668. Object.defineProperty(Geometry.prototype, "boundingBias", {
  38669. /**
  38670. * 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
  38671. */
  38672. get: function () {
  38673. return this._boundingBias;
  38674. },
  38675. /**
  38676. * 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
  38677. */
  38678. set: function (value) {
  38679. if (this._boundingBias && this._boundingBias.equals(value)) {
  38680. return;
  38681. }
  38682. this._boundingBias = value.clone();
  38683. this._updateBoundingInfo(true, null);
  38684. },
  38685. enumerable: true,
  38686. configurable: true
  38687. });
  38688. /**
  38689. * Static function used to attach a new empty geometry to a mesh
  38690. * @param mesh defines the mesh to attach the geometry to
  38691. * @returns the new {BABYLON.Geometry}
  38692. */
  38693. Geometry.CreateGeometryForMesh = function (mesh) {
  38694. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  38695. geometry.applyToMesh(mesh);
  38696. return geometry;
  38697. };
  38698. Object.defineProperty(Geometry.prototype, "extend", {
  38699. /**
  38700. * Gets the current extend of the geometry
  38701. */
  38702. get: function () {
  38703. return this._extend;
  38704. },
  38705. enumerable: true,
  38706. configurable: true
  38707. });
  38708. /**
  38709. * Gets the hosting scene
  38710. * @returns the hosting {BABYLON.Scene}
  38711. */
  38712. Geometry.prototype.getScene = function () {
  38713. return this._scene;
  38714. };
  38715. /**
  38716. * Gets the hosting engine
  38717. * @returns the hosting {BABYLON.Engine}
  38718. */
  38719. Geometry.prototype.getEngine = function () {
  38720. return this._engine;
  38721. };
  38722. /**
  38723. * Defines if the geometry is ready to use
  38724. * @returns true if the geometry is ready to be used
  38725. */
  38726. Geometry.prototype.isReady = function () {
  38727. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  38728. };
  38729. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  38730. /**
  38731. * Gets a value indicating that the geometry should not be serialized
  38732. */
  38733. get: function () {
  38734. for (var index = 0; index < this._meshes.length; index++) {
  38735. if (!this._meshes[index].doNotSerialize) {
  38736. return false;
  38737. }
  38738. }
  38739. return true;
  38740. },
  38741. enumerable: true,
  38742. configurable: true
  38743. });
  38744. /** @hidden */
  38745. Geometry.prototype._rebuild = function () {
  38746. if (this._vertexArrayObjects) {
  38747. this._vertexArrayObjects = {};
  38748. }
  38749. // Index buffer
  38750. if (this._meshes.length !== 0 && this._indices) {
  38751. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  38752. }
  38753. // Vertex buffers
  38754. for (var key in this._vertexBuffers) {
  38755. var vertexBuffer = this._vertexBuffers[key];
  38756. vertexBuffer._rebuild();
  38757. }
  38758. };
  38759. /**
  38760. * Affects all gemetry data in one call
  38761. * @param vertexData defines the geometry data
  38762. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  38763. */
  38764. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  38765. vertexData.applyToGeometry(this, updatable);
  38766. this.notifyUpdate();
  38767. };
  38768. /**
  38769. * Set specific vertex data
  38770. * @param kind defines the data kind (Position, normal, etc...)
  38771. * @param data defines the vertex data to use
  38772. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  38773. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  38774. */
  38775. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  38776. if (updatable === void 0) { updatable = false; }
  38777. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  38778. this.setVerticesBuffer(buffer);
  38779. };
  38780. /**
  38781. * Removes a specific vertex data
  38782. * @param kind defines the data kind (Position, normal, etc...)
  38783. */
  38784. Geometry.prototype.removeVerticesData = function (kind) {
  38785. if (this._vertexBuffers[kind]) {
  38786. this._vertexBuffers[kind].dispose();
  38787. delete this._vertexBuffers[kind];
  38788. }
  38789. };
  38790. /**
  38791. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  38792. * @param buffer defines the vertex buffer to use
  38793. * @param totalVertices defines the total number of vertices for position kind (could be null)
  38794. */
  38795. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  38796. if (totalVertices === void 0) { totalVertices = null; }
  38797. var kind = buffer.getKind();
  38798. if (this._vertexBuffers[kind]) {
  38799. this._vertexBuffers[kind].dispose();
  38800. }
  38801. this._vertexBuffers[kind] = buffer;
  38802. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38803. var data = buffer.getData();
  38804. if (totalVertices != null) {
  38805. this._totalVertices = totalVertices;
  38806. }
  38807. else {
  38808. if (data != null) {
  38809. this._totalVertices = data.length / (buffer.byteStride / 4);
  38810. }
  38811. }
  38812. this._updateExtend(data);
  38813. this._resetPointsArrayCache();
  38814. var meshes = this._meshes;
  38815. var numOfMeshes = meshes.length;
  38816. for (var index = 0; index < numOfMeshes; index++) {
  38817. var mesh = meshes[index];
  38818. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38819. mesh._createGlobalSubMesh(false);
  38820. mesh.computeWorldMatrix(true);
  38821. }
  38822. }
  38823. this.notifyUpdate(kind);
  38824. if (this._vertexArrayObjects) {
  38825. this._disposeVertexArrayObjects();
  38826. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  38827. }
  38828. };
  38829. /**
  38830. * Update a specific vertex buffer
  38831. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  38832. * It will do nothing if the buffer is not updatable
  38833. * @param kind defines the data kind (Position, normal, etc...)
  38834. * @param data defines the data to use
  38835. * @param offset defines the offset in the target buffer where to store the data
  38836. * @param useBytes set to true if the offset is in bytes
  38837. */
  38838. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  38839. if (useBytes === void 0) { useBytes = false; }
  38840. var vertexBuffer = this.getVertexBuffer(kind);
  38841. if (!vertexBuffer) {
  38842. return;
  38843. }
  38844. vertexBuffer.updateDirectly(data, offset, useBytes);
  38845. this.notifyUpdate(kind);
  38846. };
  38847. /**
  38848. * Update a specific vertex buffer
  38849. * This function will create a new buffer if the current one is not updatable
  38850. * @param kind defines the data kind (Position, normal, etc...)
  38851. * @param data defines the data to use
  38852. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  38853. */
  38854. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  38855. if (updateExtends === void 0) { updateExtends = false; }
  38856. var vertexBuffer = this.getVertexBuffer(kind);
  38857. if (!vertexBuffer) {
  38858. return;
  38859. }
  38860. vertexBuffer.update(data);
  38861. if (kind === BABYLON.VertexBuffer.PositionKind) {
  38862. this._updateBoundingInfo(updateExtends, data);
  38863. }
  38864. this.notifyUpdate(kind);
  38865. };
  38866. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  38867. if (updateExtends) {
  38868. this._updateExtend(data);
  38869. }
  38870. var meshes = this._meshes;
  38871. var numOfMeshes = meshes.length;
  38872. this._resetPointsArrayCache();
  38873. for (var index = 0; index < numOfMeshes; index++) {
  38874. var mesh = meshes[index];
  38875. if (updateExtends) {
  38876. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  38877. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  38878. var subMesh = mesh.subMeshes[subIndex];
  38879. subMesh.refreshBoundingInfo();
  38880. }
  38881. }
  38882. }
  38883. };
  38884. /** @hidden */
  38885. Geometry.prototype._bind = function (effect, indexToBind) {
  38886. if (!effect) {
  38887. return;
  38888. }
  38889. if (indexToBind === undefined) {
  38890. indexToBind = this._indexBuffer;
  38891. }
  38892. var vbs = this.getVertexBuffers();
  38893. if (!vbs) {
  38894. return;
  38895. }
  38896. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  38897. this._engine.bindBuffers(vbs, indexToBind, effect);
  38898. return;
  38899. }
  38900. // Using VAO
  38901. if (!this._vertexArrayObjects[effect.key]) {
  38902. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  38903. }
  38904. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  38905. };
  38906. /**
  38907. * Gets total number of vertices
  38908. * @returns the total number of vertices
  38909. */
  38910. Geometry.prototype.getTotalVertices = function () {
  38911. if (!this.isReady()) {
  38912. return 0;
  38913. }
  38914. return this._totalVertices;
  38915. };
  38916. /**
  38917. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  38918. * @param kind defines the data kind (Position, normal, etc...)
  38919. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  38920. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  38921. * @returns a float array containing vertex data
  38922. */
  38923. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  38924. var vertexBuffer = this.getVertexBuffer(kind);
  38925. if (!vertexBuffer) {
  38926. return null;
  38927. }
  38928. var data = vertexBuffer.getData();
  38929. if (!data) {
  38930. return null;
  38931. }
  38932. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  38933. var count = this._totalVertices * vertexBuffer.getSize();
  38934. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  38935. var copy_1 = new Array(count);
  38936. vertexBuffer.forEach(count, function (value, index) {
  38937. copy_1[index] = value;
  38938. });
  38939. return copy_1;
  38940. }
  38941. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  38942. if (data instanceof Array) {
  38943. var offset = vertexBuffer.byteOffset / 4;
  38944. return BABYLON.Tools.Slice(data, offset, offset + count);
  38945. }
  38946. else if (data instanceof ArrayBuffer) {
  38947. return new Float32Array(data, vertexBuffer.byteOffset, count);
  38948. }
  38949. else {
  38950. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  38951. }
  38952. }
  38953. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  38954. return BABYLON.Tools.Slice(data);
  38955. }
  38956. return data;
  38957. };
  38958. /**
  38959. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  38960. * @param kind defines the data kind (Position, normal, etc...)
  38961. * @returns true if the vertex buffer with the specified kind is updatable
  38962. */
  38963. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  38964. var vb = this._vertexBuffers[kind];
  38965. if (!vb) {
  38966. return false;
  38967. }
  38968. return vb.isUpdatable();
  38969. };
  38970. /**
  38971. * Gets a specific vertex buffer
  38972. * @param kind defines the data kind (Position, normal, etc...)
  38973. * @returns a {BABYLON.VertexBuffer}
  38974. */
  38975. Geometry.prototype.getVertexBuffer = function (kind) {
  38976. if (!this.isReady()) {
  38977. return null;
  38978. }
  38979. return this._vertexBuffers[kind];
  38980. };
  38981. /**
  38982. * Returns all vertex buffers
  38983. * @return an object holding all vertex buffers indexed by kind
  38984. */
  38985. Geometry.prototype.getVertexBuffers = function () {
  38986. if (!this.isReady()) {
  38987. return null;
  38988. }
  38989. return this._vertexBuffers;
  38990. };
  38991. /**
  38992. * Gets a boolean indicating if specific vertex buffer is present
  38993. * @param kind defines the data kind (Position, normal, etc...)
  38994. * @returns true if data is present
  38995. */
  38996. Geometry.prototype.isVerticesDataPresent = function (kind) {
  38997. if (!this._vertexBuffers) {
  38998. if (this._delayInfo) {
  38999. return this._delayInfo.indexOf(kind) !== -1;
  39000. }
  39001. return false;
  39002. }
  39003. return this._vertexBuffers[kind] !== undefined;
  39004. };
  39005. /**
  39006. * Gets a list of all attached data kinds (Position, normal, etc...)
  39007. * @returns a list of string containing all kinds
  39008. */
  39009. Geometry.prototype.getVerticesDataKinds = function () {
  39010. var result = [];
  39011. var kind;
  39012. if (!this._vertexBuffers && this._delayInfo) {
  39013. for (kind in this._delayInfo) {
  39014. result.push(kind);
  39015. }
  39016. }
  39017. else {
  39018. for (kind in this._vertexBuffers) {
  39019. result.push(kind);
  39020. }
  39021. }
  39022. return result;
  39023. };
  39024. /**
  39025. * Update index buffer
  39026. * @param indices defines the indices to store in the index buffer
  39027. * @param offset defines the offset in the target buffer where to store the data
  39028. */
  39029. Geometry.prototype.updateIndices = function (indices, offset) {
  39030. if (!this._indexBuffer) {
  39031. return;
  39032. }
  39033. if (!this._indexBufferIsUpdatable) {
  39034. this.setIndices(indices, null, true);
  39035. }
  39036. else {
  39037. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39038. }
  39039. };
  39040. /**
  39041. * Creates a new index buffer
  39042. * @param indices defines the indices to store in the index buffer
  39043. * @param totalVertices defines the total number of vertices (could be null)
  39044. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39045. */
  39046. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39047. if (totalVertices === void 0) { totalVertices = null; }
  39048. if (updatable === void 0) { updatable = false; }
  39049. if (this._indexBuffer) {
  39050. this._engine._releaseBuffer(this._indexBuffer);
  39051. }
  39052. this._disposeVertexArrayObjects();
  39053. this._indices = indices;
  39054. this._indexBufferIsUpdatable = updatable;
  39055. if (this._meshes.length !== 0 && this._indices) {
  39056. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39057. }
  39058. if (totalVertices != undefined) { // including null and undefined
  39059. this._totalVertices = totalVertices;
  39060. }
  39061. var meshes = this._meshes;
  39062. var numOfMeshes = meshes.length;
  39063. for (var index = 0; index < numOfMeshes; index++) {
  39064. meshes[index]._createGlobalSubMesh(true);
  39065. }
  39066. this.notifyUpdate();
  39067. };
  39068. /**
  39069. * Return the total number of indices
  39070. * @returns the total number of indices
  39071. */
  39072. Geometry.prototype.getTotalIndices = function () {
  39073. if (!this.isReady()) {
  39074. return 0;
  39075. }
  39076. return this._indices.length;
  39077. };
  39078. /**
  39079. * Gets the index buffer array
  39080. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39081. * @returns the index buffer array
  39082. */
  39083. Geometry.prototype.getIndices = function (copyWhenShared) {
  39084. if (!this.isReady()) {
  39085. return null;
  39086. }
  39087. var orig = this._indices;
  39088. if (!copyWhenShared || this._meshes.length === 1) {
  39089. return orig;
  39090. }
  39091. else {
  39092. var len = orig.length;
  39093. var copy = [];
  39094. for (var i = 0; i < len; i++) {
  39095. copy.push(orig[i]);
  39096. }
  39097. return copy;
  39098. }
  39099. };
  39100. /**
  39101. * Gets the index buffer
  39102. * @return the index buffer
  39103. */
  39104. Geometry.prototype.getIndexBuffer = function () {
  39105. if (!this.isReady()) {
  39106. return null;
  39107. }
  39108. return this._indexBuffer;
  39109. };
  39110. /** @hidden */
  39111. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39112. if (effect === void 0) { effect = null; }
  39113. if (!effect || !this._vertexArrayObjects) {
  39114. return;
  39115. }
  39116. if (this._vertexArrayObjects[effect.key]) {
  39117. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39118. delete this._vertexArrayObjects[effect.key];
  39119. }
  39120. };
  39121. /**
  39122. * Release the associated resources for a specific mesh
  39123. * @param mesh defines the source mesh
  39124. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39125. */
  39126. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39127. var meshes = this._meshes;
  39128. var index = meshes.indexOf(mesh);
  39129. if (index === -1) {
  39130. return;
  39131. }
  39132. meshes.splice(index, 1);
  39133. mesh._geometry = null;
  39134. if (meshes.length === 0 && shouldDispose) {
  39135. this.dispose();
  39136. }
  39137. };
  39138. /**
  39139. * Apply current geometry to a given mesh
  39140. * @param mesh defines the mesh to apply geometry to
  39141. */
  39142. Geometry.prototype.applyToMesh = function (mesh) {
  39143. if (mesh._geometry === this) {
  39144. return;
  39145. }
  39146. var previousGeometry = mesh._geometry;
  39147. if (previousGeometry) {
  39148. previousGeometry.releaseForMesh(mesh);
  39149. }
  39150. var meshes = this._meshes;
  39151. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39152. mesh._geometry = this;
  39153. this._scene.pushGeometry(this);
  39154. meshes.push(mesh);
  39155. if (this.isReady()) {
  39156. this._applyToMesh(mesh);
  39157. }
  39158. else {
  39159. mesh._boundingInfo = this._boundingInfo;
  39160. }
  39161. };
  39162. Geometry.prototype._updateExtend = function (data) {
  39163. if (data === void 0) { data = null; }
  39164. if (!data) {
  39165. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39166. }
  39167. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39168. };
  39169. Geometry.prototype._applyToMesh = function (mesh) {
  39170. var numOfMeshes = this._meshes.length;
  39171. // vertexBuffers
  39172. for (var kind in this._vertexBuffers) {
  39173. if (numOfMeshes === 1) {
  39174. this._vertexBuffers[kind].create();
  39175. }
  39176. var buffer = this._vertexBuffers[kind].getBuffer();
  39177. if (buffer)
  39178. buffer.references = numOfMeshes;
  39179. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39180. if (!this._extend) {
  39181. this._updateExtend();
  39182. }
  39183. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39184. mesh._createGlobalSubMesh(false);
  39185. //bounding info was just created again, world matrix should be applied again.
  39186. mesh._updateBoundingInfo();
  39187. }
  39188. }
  39189. // indexBuffer
  39190. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39191. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39192. }
  39193. if (this._indexBuffer) {
  39194. this._indexBuffer.references = numOfMeshes;
  39195. }
  39196. };
  39197. Geometry.prototype.notifyUpdate = function (kind) {
  39198. if (this.onGeometryUpdated) {
  39199. this.onGeometryUpdated(this, kind);
  39200. }
  39201. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39202. var mesh = _a[_i];
  39203. mesh._markSubMeshesAsAttributesDirty();
  39204. }
  39205. };
  39206. /**
  39207. * Load the geometry if it was flagged as delay loaded
  39208. * @param scene defines the hosting scene
  39209. * @param onLoaded defines a callback called when the geometry is loaded
  39210. */
  39211. Geometry.prototype.load = function (scene, onLoaded) {
  39212. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39213. return;
  39214. }
  39215. if (this.isReady()) {
  39216. if (onLoaded) {
  39217. onLoaded();
  39218. }
  39219. return;
  39220. }
  39221. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39222. this._queueLoad(scene, onLoaded);
  39223. };
  39224. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39225. var _this = this;
  39226. if (!this.delayLoadingFile) {
  39227. return;
  39228. }
  39229. scene._addPendingData(this);
  39230. scene._loadFile(this.delayLoadingFile, function (data) {
  39231. if (!_this._delayLoadingFunction) {
  39232. return;
  39233. }
  39234. _this._delayLoadingFunction(JSON.parse(data), _this);
  39235. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39236. _this._delayInfo = [];
  39237. scene._removePendingData(_this);
  39238. var meshes = _this._meshes;
  39239. var numOfMeshes = meshes.length;
  39240. for (var index = 0; index < numOfMeshes; index++) {
  39241. _this._applyToMesh(meshes[index]);
  39242. }
  39243. if (onLoaded) {
  39244. onLoaded();
  39245. }
  39246. }, undefined, true);
  39247. };
  39248. /**
  39249. * Invert the geometry to move from a right handed system to a left handed one.
  39250. */
  39251. Geometry.prototype.toLeftHanded = function () {
  39252. // Flip faces
  39253. var tIndices = this.getIndices(false);
  39254. if (tIndices != null && tIndices.length > 0) {
  39255. for (var i = 0; i < tIndices.length; i += 3) {
  39256. var tTemp = tIndices[i + 0];
  39257. tIndices[i + 0] = tIndices[i + 2];
  39258. tIndices[i + 2] = tTemp;
  39259. }
  39260. this.setIndices(tIndices);
  39261. }
  39262. // Negate position.z
  39263. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39264. if (tPositions != null && tPositions.length > 0) {
  39265. for (var i = 0; i < tPositions.length; i += 3) {
  39266. tPositions[i + 2] = -tPositions[i + 2];
  39267. }
  39268. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39269. }
  39270. // Negate normal.z
  39271. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39272. if (tNormals != null && tNormals.length > 0) {
  39273. for (var i = 0; i < tNormals.length; i += 3) {
  39274. tNormals[i + 2] = -tNormals[i + 2];
  39275. }
  39276. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39277. }
  39278. };
  39279. // Cache
  39280. /** @hidden */
  39281. Geometry.prototype._resetPointsArrayCache = function () {
  39282. this._positions = null;
  39283. };
  39284. /** @hidden */
  39285. Geometry.prototype._generatePointsArray = function () {
  39286. if (this._positions)
  39287. return true;
  39288. this._positions = [];
  39289. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39290. if (!data) {
  39291. return false;
  39292. }
  39293. for (var index = 0; index < data.length; index += 3) {
  39294. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39295. }
  39296. return true;
  39297. };
  39298. /**
  39299. * Gets a value indicating if the geometry is disposed
  39300. * @returns true if the geometry was disposed
  39301. */
  39302. Geometry.prototype.isDisposed = function () {
  39303. return this._isDisposed;
  39304. };
  39305. Geometry.prototype._disposeVertexArrayObjects = function () {
  39306. if (this._vertexArrayObjects) {
  39307. for (var kind in this._vertexArrayObjects) {
  39308. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39309. }
  39310. this._vertexArrayObjects = {};
  39311. }
  39312. };
  39313. /**
  39314. * Free all associated resources
  39315. */
  39316. Geometry.prototype.dispose = function () {
  39317. var meshes = this._meshes;
  39318. var numOfMeshes = meshes.length;
  39319. var index;
  39320. for (index = 0; index < numOfMeshes; index++) {
  39321. this.releaseForMesh(meshes[index]);
  39322. }
  39323. this._meshes = [];
  39324. this._disposeVertexArrayObjects();
  39325. for (var kind in this._vertexBuffers) {
  39326. this._vertexBuffers[kind].dispose();
  39327. }
  39328. this._vertexBuffers = {};
  39329. this._totalVertices = 0;
  39330. if (this._indexBuffer) {
  39331. this._engine._releaseBuffer(this._indexBuffer);
  39332. }
  39333. this._indexBuffer = null;
  39334. this._indices = [];
  39335. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39336. this.delayLoadingFile = null;
  39337. this._delayLoadingFunction = null;
  39338. this._delayInfo = [];
  39339. this._boundingInfo = null;
  39340. this._scene.removeGeometry(this);
  39341. this._isDisposed = true;
  39342. };
  39343. /**
  39344. * Clone the current geometry into a new geometry
  39345. * @param id defines the unique ID of the new geometry
  39346. * @returns a new geometry object
  39347. */
  39348. Geometry.prototype.copy = function (id) {
  39349. var vertexData = new BABYLON.VertexData();
  39350. vertexData.indices = [];
  39351. var indices = this.getIndices();
  39352. if (indices) {
  39353. for (var index = 0; index < indices.length; index++) {
  39354. vertexData.indices.push(indices[index]);
  39355. }
  39356. }
  39357. var updatable = false;
  39358. var stopChecking = false;
  39359. var kind;
  39360. for (kind in this._vertexBuffers) {
  39361. // using slice() to make a copy of the array and not just reference it
  39362. var data = this.getVerticesData(kind);
  39363. if (data instanceof Float32Array) {
  39364. vertexData.set(new Float32Array(data), kind);
  39365. }
  39366. else {
  39367. vertexData.set(data.slice(0), kind);
  39368. }
  39369. if (!stopChecking) {
  39370. var vb = this.getVertexBuffer(kind);
  39371. if (vb) {
  39372. updatable = vb.isUpdatable();
  39373. stopChecking = !updatable;
  39374. }
  39375. }
  39376. }
  39377. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39378. geometry.delayLoadState = this.delayLoadState;
  39379. geometry.delayLoadingFile = this.delayLoadingFile;
  39380. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39381. for (kind in this._delayInfo) {
  39382. geometry._delayInfo = geometry._delayInfo || [];
  39383. geometry._delayInfo.push(kind);
  39384. }
  39385. // Bounding info
  39386. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39387. return geometry;
  39388. };
  39389. /**
  39390. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39391. * @return a JSON representation of the current geometry data (without the vertices data)
  39392. */
  39393. Geometry.prototype.serialize = function () {
  39394. var serializationObject = {};
  39395. serializationObject.id = this.id;
  39396. serializationObject.updatable = this._updatable;
  39397. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  39398. serializationObject.tags = BABYLON.Tags.GetTags(this);
  39399. }
  39400. return serializationObject;
  39401. };
  39402. Geometry.prototype.toNumberArray = function (origin) {
  39403. if (Array.isArray(origin)) {
  39404. return origin;
  39405. }
  39406. else {
  39407. return Array.prototype.slice.call(origin);
  39408. }
  39409. };
  39410. /**
  39411. * Serialize all vertices data into a JSON oject
  39412. * @returns a JSON representation of the current geometry data
  39413. */
  39414. Geometry.prototype.serializeVerticeData = function () {
  39415. var serializationObject = this.serialize();
  39416. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  39417. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  39418. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  39419. serializationObject.positions._updatable = true;
  39420. }
  39421. }
  39422. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  39423. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  39424. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  39425. serializationObject.normals._updatable = true;
  39426. }
  39427. }
  39428. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  39429. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  39430. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  39431. serializationObject.tangets._updatable = true;
  39432. }
  39433. }
  39434. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  39435. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  39436. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  39437. serializationObject.uvs._updatable = true;
  39438. }
  39439. }
  39440. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  39441. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  39442. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  39443. serializationObject.uv2s._updatable = true;
  39444. }
  39445. }
  39446. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  39447. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  39448. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  39449. serializationObject.uv3s._updatable = true;
  39450. }
  39451. }
  39452. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  39453. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  39454. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  39455. serializationObject.uv4s._updatable = true;
  39456. }
  39457. }
  39458. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  39459. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  39460. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  39461. serializationObject.uv5s._updatable = true;
  39462. }
  39463. }
  39464. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  39465. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  39466. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  39467. serializationObject.uv6s._updatable = true;
  39468. }
  39469. }
  39470. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  39471. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  39472. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  39473. serializationObject.colors._updatable = true;
  39474. }
  39475. }
  39476. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39477. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  39478. serializationObject.matricesIndices._isExpanded = true;
  39479. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  39480. serializationObject.matricesIndices._updatable = true;
  39481. }
  39482. }
  39483. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39484. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  39485. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  39486. serializationObject.matricesWeights._updatable = true;
  39487. }
  39488. }
  39489. serializationObject.indices = this.toNumberArray(this.getIndices());
  39490. return serializationObject;
  39491. };
  39492. // Statics
  39493. /**
  39494. * Extracts a clone of a mesh geometry
  39495. * @param mesh defines the source mesh
  39496. * @param id defines the unique ID of the new geometry object
  39497. * @returns the new geometry object
  39498. */
  39499. Geometry.ExtractFromMesh = function (mesh, id) {
  39500. var geometry = mesh._geometry;
  39501. if (!geometry) {
  39502. return null;
  39503. }
  39504. return geometry.copy(id);
  39505. };
  39506. /**
  39507. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  39508. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  39509. * Be aware Math.random() could cause collisions, but:
  39510. * "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"
  39511. * @returns a string containing a new GUID
  39512. */
  39513. Geometry.RandomId = function () {
  39514. return BABYLON.Tools.RandomId();
  39515. };
  39516. /** @hidden */
  39517. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  39518. var scene = mesh.getScene();
  39519. // Geometry
  39520. var geometryId = parsedGeometry.geometryId;
  39521. if (geometryId) {
  39522. var geometry = scene.getGeometryByID(geometryId);
  39523. if (geometry) {
  39524. geometry.applyToMesh(mesh);
  39525. }
  39526. }
  39527. else if (parsedGeometry instanceof ArrayBuffer) {
  39528. var binaryInfo = mesh._binaryInfo;
  39529. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  39530. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  39531. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  39532. }
  39533. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  39534. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  39535. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  39536. }
  39537. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  39538. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  39539. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  39540. }
  39541. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  39542. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  39543. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  39544. }
  39545. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  39546. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  39547. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  39548. }
  39549. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  39550. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  39551. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  39552. }
  39553. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  39554. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  39555. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  39556. }
  39557. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  39558. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  39559. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  39560. }
  39561. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  39562. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  39563. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  39564. }
  39565. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  39566. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  39567. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  39568. }
  39569. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  39570. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  39571. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndicesData, false);
  39572. }
  39573. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  39574. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  39575. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  39576. }
  39577. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  39578. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  39579. mesh.setIndices(indicesData, null);
  39580. }
  39581. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  39582. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  39583. mesh.subMeshes = [];
  39584. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  39585. var materialIndex = subMeshesData[(i * 5) + 0];
  39586. var verticesStart = subMeshesData[(i * 5) + 1];
  39587. var verticesCount = subMeshesData[(i * 5) + 2];
  39588. var indexStart = subMeshesData[(i * 5) + 3];
  39589. var indexCount = subMeshesData[(i * 5) + 4];
  39590. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  39591. }
  39592. }
  39593. }
  39594. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  39595. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  39596. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  39597. if (parsedGeometry.tangents) {
  39598. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  39599. }
  39600. if (parsedGeometry.uvs) {
  39601. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  39602. }
  39603. if (parsedGeometry.uvs2) {
  39604. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  39605. }
  39606. if (parsedGeometry.uvs3) {
  39607. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  39608. }
  39609. if (parsedGeometry.uvs4) {
  39610. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  39611. }
  39612. if (parsedGeometry.uvs5) {
  39613. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  39614. }
  39615. if (parsedGeometry.uvs6) {
  39616. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  39617. }
  39618. if (parsedGeometry.colors) {
  39619. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  39620. }
  39621. if (parsedGeometry.matricesIndices) {
  39622. if (!parsedGeometry.matricesIndices._isExpanded) {
  39623. var floatIndices = [];
  39624. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  39625. var matricesIndex = parsedGeometry.matricesIndices[i];
  39626. floatIndices.push(matricesIndex & 0x000000FF);
  39627. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39628. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39629. floatIndices.push(matricesIndex >> 24);
  39630. }
  39631. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  39632. }
  39633. else {
  39634. delete parsedGeometry.matricesIndices._isExpanded;
  39635. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  39636. }
  39637. }
  39638. if (parsedGeometry.matricesIndicesExtra) {
  39639. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  39640. var floatIndices = [];
  39641. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  39642. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  39643. floatIndices.push(matricesIndex & 0x000000FF);
  39644. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  39645. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  39646. floatIndices.push(matricesIndex >> 24);
  39647. }
  39648. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  39649. }
  39650. else {
  39651. delete parsedGeometry.matricesIndices._isExpanded;
  39652. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  39653. }
  39654. }
  39655. if (parsedGeometry.matricesWeights) {
  39656. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  39657. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  39658. }
  39659. if (parsedGeometry.matricesWeightsExtra) {
  39660. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  39661. }
  39662. mesh.setIndices(parsedGeometry.indices, null);
  39663. }
  39664. // SubMeshes
  39665. if (parsedGeometry.subMeshes) {
  39666. mesh.subMeshes = [];
  39667. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  39668. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  39669. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  39670. }
  39671. }
  39672. // Flat shading
  39673. if (mesh._shouldGenerateFlatShading) {
  39674. mesh.convertToFlatShadedMesh();
  39675. delete mesh._shouldGenerateFlatShading;
  39676. }
  39677. // Update
  39678. mesh.computeWorldMatrix(true);
  39679. // Octree
  39680. var sceneOctree = scene.selectionOctree;
  39681. if (sceneOctree !== undefined && sceneOctree !== null) {
  39682. sceneOctree.addMesh(mesh);
  39683. }
  39684. };
  39685. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  39686. var epsilon = 1e-3;
  39687. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  39688. return;
  39689. }
  39690. var noInfluenceBoneIndex = 0.0;
  39691. if (parsedGeometry.skeletonId > -1) {
  39692. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  39693. if (!skeleton) {
  39694. return;
  39695. }
  39696. noInfluenceBoneIndex = skeleton.bones.length;
  39697. }
  39698. else {
  39699. return;
  39700. }
  39701. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  39702. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  39703. var matricesWeights = parsedGeometry.matricesWeights;
  39704. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  39705. var influencers = parsedGeometry.numBoneInfluencer;
  39706. var size = matricesWeights.length;
  39707. for (var i = 0; i < size; i += 4) {
  39708. var weight = 0.0;
  39709. var firstZeroWeight = -1;
  39710. for (var j = 0; j < 4; j++) {
  39711. var w = matricesWeights[i + j];
  39712. weight += w;
  39713. if (w < epsilon && firstZeroWeight < 0) {
  39714. firstZeroWeight = j;
  39715. }
  39716. }
  39717. if (matricesWeightsExtra) {
  39718. for (var j = 0; j < 4; j++) {
  39719. var w = matricesWeightsExtra[i + j];
  39720. weight += w;
  39721. if (w < epsilon && firstZeroWeight < 0) {
  39722. firstZeroWeight = j + 4;
  39723. }
  39724. }
  39725. }
  39726. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  39727. firstZeroWeight = influencers - 1;
  39728. }
  39729. if (weight > epsilon) {
  39730. var mweight = 1.0 / weight;
  39731. for (var j = 0; j < 4; j++) {
  39732. matricesWeights[i + j] *= mweight;
  39733. }
  39734. if (matricesWeightsExtra) {
  39735. for (var j = 0; j < 4; j++) {
  39736. matricesWeightsExtra[i + j] *= mweight;
  39737. }
  39738. }
  39739. }
  39740. else {
  39741. if (firstZeroWeight >= 4) {
  39742. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  39743. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  39744. }
  39745. else {
  39746. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  39747. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  39748. }
  39749. }
  39750. }
  39751. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  39752. if (parsedGeometry.matricesWeightsExtra) {
  39753. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  39754. }
  39755. };
  39756. /**
  39757. * Create a new geometry from persisted data (Using .babylon file format)
  39758. * @param parsedVertexData defines the persisted data
  39759. * @param scene defines the hosting scene
  39760. * @param rootUrl defines the root url to use to load assets (like delayed data)
  39761. * @returns the new geometry object
  39762. */
  39763. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  39764. if (scene.getGeometryByID(parsedVertexData.id)) {
  39765. return null; // null since geometry could be something else than a box...
  39766. }
  39767. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  39768. if (BABYLON.Tags) {
  39769. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  39770. }
  39771. if (parsedVertexData.delayLoadingFile) {
  39772. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  39773. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  39774. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  39775. geometry._delayInfo = [];
  39776. if (parsedVertexData.hasUVs) {
  39777. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  39778. }
  39779. if (parsedVertexData.hasUVs2) {
  39780. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  39781. }
  39782. if (parsedVertexData.hasUVs3) {
  39783. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  39784. }
  39785. if (parsedVertexData.hasUVs4) {
  39786. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  39787. }
  39788. if (parsedVertexData.hasUVs5) {
  39789. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  39790. }
  39791. if (parsedVertexData.hasUVs6) {
  39792. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  39793. }
  39794. if (parsedVertexData.hasColors) {
  39795. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  39796. }
  39797. if (parsedVertexData.hasMatricesIndices) {
  39798. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  39799. }
  39800. if (parsedVertexData.hasMatricesWeights) {
  39801. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  39802. }
  39803. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  39804. }
  39805. else {
  39806. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  39807. }
  39808. scene.pushGeometry(geometry, true);
  39809. return geometry;
  39810. };
  39811. return Geometry;
  39812. }());
  39813. BABYLON.Geometry = Geometry;
  39814. // Primitives
  39815. /// Abstract class
  39816. /**
  39817. * Abstract class used to provide common services for all typed geometries
  39818. * @hidden
  39819. */
  39820. var _PrimitiveGeometry = /** @class */ (function (_super) {
  39821. __extends(_PrimitiveGeometry, _super);
  39822. /**
  39823. * Creates a new typed geometry
  39824. * @param id defines the unique ID of the geometry
  39825. * @param scene defines the hosting scene
  39826. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39827. * @param mesh defines the hosting mesh (can be null)
  39828. */
  39829. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  39830. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  39831. if (mesh === void 0) { mesh = null; }
  39832. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  39833. _this._canBeRegenerated = _canBeRegenerated;
  39834. _this._beingRegenerated = true;
  39835. _this.regenerate();
  39836. _this._beingRegenerated = false;
  39837. return _this;
  39838. }
  39839. /**
  39840. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  39841. * @returns true if the geometry can be regenerated
  39842. */
  39843. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  39844. return this._canBeRegenerated;
  39845. };
  39846. /**
  39847. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  39848. */
  39849. _PrimitiveGeometry.prototype.regenerate = function () {
  39850. if (!this._canBeRegenerated) {
  39851. return;
  39852. }
  39853. this._beingRegenerated = true;
  39854. this.setAllVerticesData(this._regenerateVertexData(), false);
  39855. this._beingRegenerated = false;
  39856. };
  39857. /**
  39858. * Clone the geometry
  39859. * @param id defines the unique ID of the new geometry
  39860. * @returns the new geometry
  39861. */
  39862. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  39863. return _super.prototype.copy.call(this, id);
  39864. };
  39865. // overrides
  39866. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39867. if (!this._beingRegenerated) {
  39868. return;
  39869. }
  39870. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  39871. };
  39872. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  39873. if (!this._beingRegenerated) {
  39874. return;
  39875. }
  39876. _super.prototype.setVerticesData.call(this, kind, data, false);
  39877. };
  39878. // to override
  39879. /** @hidden */
  39880. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  39881. throw new Error("Abstract method");
  39882. };
  39883. _PrimitiveGeometry.prototype.copy = function (id) {
  39884. throw new Error("Must be overriden in sub-classes.");
  39885. };
  39886. _PrimitiveGeometry.prototype.serialize = function () {
  39887. var serializationObject = _super.prototype.serialize.call(this);
  39888. serializationObject.canBeRegenerated = this.canBeRegenerated();
  39889. return serializationObject;
  39890. };
  39891. return _PrimitiveGeometry;
  39892. }(Geometry));
  39893. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  39894. /**
  39895. * Creates a ribbon geometry
  39896. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  39897. */
  39898. var RibbonGeometry = /** @class */ (function (_super) {
  39899. __extends(RibbonGeometry, _super);
  39900. /**
  39901. * Creates a ribbon geometry
  39902. * @param id defines the unique ID of the geometry
  39903. * @param scene defines the hosting scene
  39904. * @param pathArray defines the array of paths to use
  39905. * @param closeArray defines if the last path and the first path must be joined
  39906. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  39907. * @param offset defines the offset between points
  39908. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39909. * @param mesh defines the hosting mesh (can be null)
  39910. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39911. */
  39912. function RibbonGeometry(id, scene,
  39913. /**
  39914. * Defines the array of paths to use
  39915. */
  39916. pathArray,
  39917. /**
  39918. * Defines if the last and first points of each path in your pathArray must be joined
  39919. */
  39920. closeArray,
  39921. /**
  39922. * Defines if the last and first points of each path in your pathArray must be joined
  39923. */
  39924. closePath,
  39925. /**
  39926. * Defines the offset between points
  39927. */
  39928. offset, canBeRegenerated, mesh,
  39929. /**
  39930. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39931. */
  39932. side) {
  39933. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39934. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39935. _this.pathArray = pathArray;
  39936. _this.closeArray = closeArray;
  39937. _this.closePath = closePath;
  39938. _this.offset = offset;
  39939. _this.side = side;
  39940. return _this;
  39941. }
  39942. /** @hidden */
  39943. RibbonGeometry.prototype._regenerateVertexData = function () {
  39944. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  39945. };
  39946. RibbonGeometry.prototype.copy = function (id) {
  39947. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  39948. };
  39949. return RibbonGeometry;
  39950. }(_PrimitiveGeometry));
  39951. BABYLON.RibbonGeometry = RibbonGeometry;
  39952. /**
  39953. * Creates a box geometry
  39954. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  39955. */
  39956. var BoxGeometry = /** @class */ (function (_super) {
  39957. __extends(BoxGeometry, _super);
  39958. /**
  39959. * Creates a box geometry
  39960. * @param id defines the unique ID of the geometry
  39961. * @param scene defines the hosting scene
  39962. * @param size defines the zise of the box (width, height and depth are the same)
  39963. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  39964. * @param mesh defines the hosting mesh (can be null)
  39965. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39966. */
  39967. function BoxGeometry(id, scene,
  39968. /**
  39969. * Defines the zise of the box (width, height and depth are the same)
  39970. */
  39971. size, canBeRegenerated, mesh,
  39972. /**
  39973. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  39974. */
  39975. side) {
  39976. if (mesh === void 0) { mesh = null; }
  39977. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  39978. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  39979. _this.size = size;
  39980. _this.side = side;
  39981. return _this;
  39982. }
  39983. BoxGeometry.prototype._regenerateVertexData = function () {
  39984. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  39985. };
  39986. BoxGeometry.prototype.copy = function (id) {
  39987. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  39988. };
  39989. BoxGeometry.prototype.serialize = function () {
  39990. var serializationObject = _super.prototype.serialize.call(this);
  39991. serializationObject.size = this.size;
  39992. return serializationObject;
  39993. };
  39994. BoxGeometry.Parse = function (parsedBox, scene) {
  39995. if (scene.getGeometryByID(parsedBox.id)) {
  39996. return null; // null since geometry could be something else than a box...
  39997. }
  39998. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  39999. if (BABYLON.Tags) {
  40000. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40001. }
  40002. scene.pushGeometry(box, true);
  40003. return box;
  40004. };
  40005. return BoxGeometry;
  40006. }(_PrimitiveGeometry));
  40007. BABYLON.BoxGeometry = BoxGeometry;
  40008. /**
  40009. * Creates a sphere geometry
  40010. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40011. */
  40012. var SphereGeometry = /** @class */ (function (_super) {
  40013. __extends(SphereGeometry, _super);
  40014. /**
  40015. * Create a new sphere geometry
  40016. * @param id defines the unique ID of the geometry
  40017. * @param scene defines the hosting scene
  40018. * @param segments defines the number of segments to use to create the sphere
  40019. * @param diameter defines the diameter of the sphere
  40020. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40021. * @param mesh defines the hosting mesh (can be null)
  40022. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40023. */
  40024. function SphereGeometry(id, scene,
  40025. /**
  40026. * Defines the number of segments to use to create the sphere
  40027. */
  40028. segments,
  40029. /**
  40030. * Defines the diameter of the sphere
  40031. */
  40032. diameter, canBeRegenerated, mesh,
  40033. /**
  40034. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40035. */
  40036. side) {
  40037. if (mesh === void 0) { mesh = null; }
  40038. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40039. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40040. _this.segments = segments;
  40041. _this.diameter = diameter;
  40042. _this.side = side;
  40043. return _this;
  40044. }
  40045. SphereGeometry.prototype._regenerateVertexData = function () {
  40046. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40047. };
  40048. SphereGeometry.prototype.copy = function (id) {
  40049. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40050. };
  40051. SphereGeometry.prototype.serialize = function () {
  40052. var serializationObject = _super.prototype.serialize.call(this);
  40053. serializationObject.segments = this.segments;
  40054. serializationObject.diameter = this.diameter;
  40055. return serializationObject;
  40056. };
  40057. SphereGeometry.Parse = function (parsedSphere, scene) {
  40058. if (scene.getGeometryByID(parsedSphere.id)) {
  40059. return null; // null since geometry could be something else than a sphere...
  40060. }
  40061. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40062. if (BABYLON.Tags) {
  40063. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40064. }
  40065. scene.pushGeometry(sphere, true);
  40066. return sphere;
  40067. };
  40068. return SphereGeometry;
  40069. }(_PrimitiveGeometry));
  40070. BABYLON.SphereGeometry = SphereGeometry;
  40071. /**
  40072. * Creates a disc geometry
  40073. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40074. */
  40075. var DiscGeometry = /** @class */ (function (_super) {
  40076. __extends(DiscGeometry, _super);
  40077. /**
  40078. * Creates a new disc geometry
  40079. * @param id defines the unique ID of the geometry
  40080. * @param scene defines the hosting scene
  40081. * @param radius defines the radius of the disc
  40082. * @param tessellation defines the tesselation factor to apply to the disc
  40083. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40084. * @param mesh defines the hosting mesh (can be null)
  40085. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40086. */
  40087. function DiscGeometry(id, scene,
  40088. /**
  40089. * Defines the radius of the disc
  40090. */
  40091. radius,
  40092. /**
  40093. * Defines the tesselation factor to apply to the disc
  40094. */
  40095. tessellation, canBeRegenerated, mesh,
  40096. /**
  40097. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40098. */
  40099. side) {
  40100. if (mesh === void 0) { mesh = null; }
  40101. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40102. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40103. _this.radius = radius;
  40104. _this.tessellation = tessellation;
  40105. _this.side = side;
  40106. return _this;
  40107. }
  40108. DiscGeometry.prototype._regenerateVertexData = function () {
  40109. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40110. };
  40111. DiscGeometry.prototype.copy = function (id) {
  40112. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40113. };
  40114. return DiscGeometry;
  40115. }(_PrimitiveGeometry));
  40116. BABYLON.DiscGeometry = DiscGeometry;
  40117. /**
  40118. * Creates a new cylinder geometry
  40119. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40120. */
  40121. var CylinderGeometry = /** @class */ (function (_super) {
  40122. __extends(CylinderGeometry, _super);
  40123. /**
  40124. * Creates a new cylinder geometry
  40125. * @param id defines the unique ID of the geometry
  40126. * @param scene defines the hosting scene
  40127. * @param height defines the height of the cylinder
  40128. * @param diameterTop defines the diameter of the cylinder's top cap
  40129. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40130. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40131. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40132. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40133. * @param mesh defines the hosting mesh (can be null)
  40134. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40135. */
  40136. function CylinderGeometry(id, scene,
  40137. /**
  40138. * Defines the height of the cylinder
  40139. */
  40140. height,
  40141. /**
  40142. * Defines the diameter of the cylinder's top cap
  40143. */
  40144. diameterTop,
  40145. /**
  40146. * Defines the diameter of the cylinder's bottom cap
  40147. */
  40148. diameterBottom,
  40149. /**
  40150. * Defines the tessellation factor to apply to the cylinder
  40151. */
  40152. tessellation,
  40153. /**
  40154. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40155. */
  40156. subdivisions, canBeRegenerated, mesh,
  40157. /**
  40158. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40159. */
  40160. side) {
  40161. if (subdivisions === void 0) { subdivisions = 1; }
  40162. if (mesh === void 0) { mesh = null; }
  40163. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40164. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40165. _this.height = height;
  40166. _this.diameterTop = diameterTop;
  40167. _this.diameterBottom = diameterBottom;
  40168. _this.tessellation = tessellation;
  40169. _this.subdivisions = subdivisions;
  40170. _this.side = side;
  40171. return _this;
  40172. }
  40173. CylinderGeometry.prototype._regenerateVertexData = function () {
  40174. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40175. };
  40176. CylinderGeometry.prototype.copy = function (id) {
  40177. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40178. };
  40179. CylinderGeometry.prototype.serialize = function () {
  40180. var serializationObject = _super.prototype.serialize.call(this);
  40181. serializationObject.height = this.height;
  40182. serializationObject.diameterTop = this.diameterTop;
  40183. serializationObject.diameterBottom = this.diameterBottom;
  40184. serializationObject.tessellation = this.tessellation;
  40185. return serializationObject;
  40186. };
  40187. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40188. if (scene.getGeometryByID(parsedCylinder.id)) {
  40189. return null; // null since geometry could be something else than a cylinder...
  40190. }
  40191. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40192. if (BABYLON.Tags) {
  40193. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40194. }
  40195. scene.pushGeometry(cylinder, true);
  40196. return cylinder;
  40197. };
  40198. return CylinderGeometry;
  40199. }(_PrimitiveGeometry));
  40200. BABYLON.CylinderGeometry = CylinderGeometry;
  40201. /**
  40202. * Creates a new torus geometry
  40203. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40204. */
  40205. var TorusGeometry = /** @class */ (function (_super) {
  40206. __extends(TorusGeometry, _super);
  40207. /**
  40208. * Creates a new torus geometry
  40209. * @param id defines the unique ID of the geometry
  40210. * @param scene defines the hosting scene
  40211. * @param diameter defines the diameter of the torus
  40212. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40213. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40214. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40215. * @param mesh defines the hosting mesh (can be null)
  40216. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40217. */
  40218. function TorusGeometry(id, scene,
  40219. /**
  40220. * Defines the diameter of the torus
  40221. */
  40222. diameter,
  40223. /**
  40224. * Defines the thickness of the torus (ie. internal diameter)
  40225. */
  40226. thickness,
  40227. /**
  40228. * Defines the tesselation factor to apply to the torus
  40229. */
  40230. tessellation, canBeRegenerated, mesh,
  40231. /**
  40232. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40233. */
  40234. side) {
  40235. if (mesh === void 0) { mesh = null; }
  40236. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40237. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40238. _this.diameter = diameter;
  40239. _this.thickness = thickness;
  40240. _this.tessellation = tessellation;
  40241. _this.side = side;
  40242. return _this;
  40243. }
  40244. TorusGeometry.prototype._regenerateVertexData = function () {
  40245. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40246. };
  40247. TorusGeometry.prototype.copy = function (id) {
  40248. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40249. };
  40250. TorusGeometry.prototype.serialize = function () {
  40251. var serializationObject = _super.prototype.serialize.call(this);
  40252. serializationObject.diameter = this.diameter;
  40253. serializationObject.thickness = this.thickness;
  40254. serializationObject.tessellation = this.tessellation;
  40255. return serializationObject;
  40256. };
  40257. TorusGeometry.Parse = function (parsedTorus, scene) {
  40258. if (scene.getGeometryByID(parsedTorus.id)) {
  40259. return null; // null since geometry could be something else than a torus...
  40260. }
  40261. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40262. if (BABYLON.Tags) {
  40263. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40264. }
  40265. scene.pushGeometry(torus, true);
  40266. return torus;
  40267. };
  40268. return TorusGeometry;
  40269. }(_PrimitiveGeometry));
  40270. BABYLON.TorusGeometry = TorusGeometry;
  40271. /**
  40272. * Creates a new ground geometry
  40273. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40274. */
  40275. var GroundGeometry = /** @class */ (function (_super) {
  40276. __extends(GroundGeometry, _super);
  40277. /**
  40278. * Creates a new ground geometry
  40279. * @param id defines the unique ID of the geometry
  40280. * @param scene defines the hosting scene
  40281. * @param width defines the width of the ground
  40282. * @param height defines the height of the ground
  40283. * @param subdivisions defines the subdivisions to apply to the ground
  40284. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40285. * @param mesh defines the hosting mesh (can be null)
  40286. */
  40287. function GroundGeometry(id, scene,
  40288. /**
  40289. * Defines the width of the ground
  40290. */
  40291. width,
  40292. /**
  40293. * Defines the height of the ground
  40294. */
  40295. height,
  40296. /**
  40297. * Defines the subdivisions to apply to the ground
  40298. */
  40299. subdivisions, canBeRegenerated, mesh) {
  40300. if (mesh === void 0) { mesh = null; }
  40301. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40302. _this.width = width;
  40303. _this.height = height;
  40304. _this.subdivisions = subdivisions;
  40305. return _this;
  40306. }
  40307. GroundGeometry.prototype._regenerateVertexData = function () {
  40308. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40309. };
  40310. GroundGeometry.prototype.copy = function (id) {
  40311. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40312. };
  40313. GroundGeometry.prototype.serialize = function () {
  40314. var serializationObject = _super.prototype.serialize.call(this);
  40315. serializationObject.width = this.width;
  40316. serializationObject.height = this.height;
  40317. serializationObject.subdivisions = this.subdivisions;
  40318. return serializationObject;
  40319. };
  40320. GroundGeometry.Parse = function (parsedGround, scene) {
  40321. if (scene.getGeometryByID(parsedGround.id)) {
  40322. return null; // null since geometry could be something else than a ground...
  40323. }
  40324. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40325. if (BABYLON.Tags) {
  40326. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40327. }
  40328. scene.pushGeometry(ground, true);
  40329. return ground;
  40330. };
  40331. return GroundGeometry;
  40332. }(_PrimitiveGeometry));
  40333. BABYLON.GroundGeometry = GroundGeometry;
  40334. /**
  40335. * Creates a tiled ground geometry
  40336. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40337. */
  40338. var TiledGroundGeometry = /** @class */ (function (_super) {
  40339. __extends(TiledGroundGeometry, _super);
  40340. /**
  40341. * Creates a tiled ground geometry
  40342. * @param id defines the unique ID of the geometry
  40343. * @param scene defines the hosting scene
  40344. * @param xmin defines the minimum value on X axis
  40345. * @param zmin defines the minimum value on Z axis
  40346. * @param xmax defines the maximum value on X axis
  40347. * @param zmax defines the maximum value on Z axis
  40348. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40349. * @param precision defines the precision to use when computing the tiles
  40350. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40351. * @param mesh defines the hosting mesh (can be null)
  40352. */
  40353. function TiledGroundGeometry(id, scene,
  40354. /**
  40355. * Defines the minimum value on X axis
  40356. */
  40357. xmin,
  40358. /**
  40359. * Defines the minimum value on Z axis
  40360. */
  40361. zmin,
  40362. /**
  40363. * Defines the maximum value on X axis
  40364. */
  40365. xmax,
  40366. /**
  40367. * Defines the maximum value on Z axis
  40368. */
  40369. zmax,
  40370. /**
  40371. * Defines the subdivisions to apply to the ground
  40372. */
  40373. subdivisions,
  40374. /**
  40375. * Defines the precision to use when computing the tiles
  40376. */
  40377. precision, canBeRegenerated, mesh) {
  40378. if (mesh === void 0) { mesh = null; }
  40379. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40380. _this.xmin = xmin;
  40381. _this.zmin = zmin;
  40382. _this.xmax = xmax;
  40383. _this.zmax = zmax;
  40384. _this.subdivisions = subdivisions;
  40385. _this.precision = precision;
  40386. return _this;
  40387. }
  40388. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  40389. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  40390. };
  40391. TiledGroundGeometry.prototype.copy = function (id) {
  40392. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  40393. };
  40394. return TiledGroundGeometry;
  40395. }(_PrimitiveGeometry));
  40396. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  40397. /**
  40398. * Creates a plane geometry
  40399. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  40400. */
  40401. var PlaneGeometry = /** @class */ (function (_super) {
  40402. __extends(PlaneGeometry, _super);
  40403. /**
  40404. * Creates a plane geometry
  40405. * @param id defines the unique ID of the geometry
  40406. * @param scene defines the hosting scene
  40407. * @param size defines the size of the plane (width === height)
  40408. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40409. * @param mesh defines the hosting mesh (can be null)
  40410. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40411. */
  40412. function PlaneGeometry(id, scene,
  40413. /**
  40414. * Defines the size of the plane (width === height)
  40415. */
  40416. size, canBeRegenerated, mesh,
  40417. /**
  40418. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40419. */
  40420. side) {
  40421. if (mesh === void 0) { mesh = null; }
  40422. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40423. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40424. _this.size = size;
  40425. _this.side = side;
  40426. return _this;
  40427. }
  40428. PlaneGeometry.prototype._regenerateVertexData = function () {
  40429. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  40430. };
  40431. PlaneGeometry.prototype.copy = function (id) {
  40432. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  40433. };
  40434. PlaneGeometry.prototype.serialize = function () {
  40435. var serializationObject = _super.prototype.serialize.call(this);
  40436. serializationObject.size = this.size;
  40437. return serializationObject;
  40438. };
  40439. PlaneGeometry.Parse = function (parsedPlane, scene) {
  40440. if (scene.getGeometryByID(parsedPlane.id)) {
  40441. return null; // null since geometry could be something else than a ground...
  40442. }
  40443. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  40444. if (BABYLON.Tags) {
  40445. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  40446. }
  40447. scene.pushGeometry(plane, true);
  40448. return plane;
  40449. };
  40450. return PlaneGeometry;
  40451. }(_PrimitiveGeometry));
  40452. BABYLON.PlaneGeometry = PlaneGeometry;
  40453. /**
  40454. * Creates a torus knot geometry
  40455. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  40456. */
  40457. var TorusKnotGeometry = /** @class */ (function (_super) {
  40458. __extends(TorusKnotGeometry, _super);
  40459. /**
  40460. * Creates a torus knot geometry
  40461. * @param id defines the unique ID of the geometry
  40462. * @param scene defines the hosting scene
  40463. * @param radius defines the radius of the torus knot
  40464. * @param tube defines the thickness of the torus knot tube
  40465. * @param radialSegments defines the number of radial segments
  40466. * @param tubularSegments defines the number of tubular segments
  40467. * @param p defines the first number of windings
  40468. * @param q defines the second number of windings
  40469. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40470. * @param mesh defines the hosting mesh (can be null)
  40471. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40472. */
  40473. function TorusKnotGeometry(id, scene,
  40474. /**
  40475. * Defines the radius of the torus knot
  40476. */
  40477. radius,
  40478. /**
  40479. * Defines the thickness of the torus knot tube
  40480. */
  40481. tube,
  40482. /**
  40483. * Defines the number of radial segments
  40484. */
  40485. radialSegments,
  40486. /**
  40487. * Defines the number of tubular segments
  40488. */
  40489. tubularSegments,
  40490. /**
  40491. * Defines the first number of windings
  40492. */
  40493. p,
  40494. /**
  40495. * Defines the second number of windings
  40496. */
  40497. q, canBeRegenerated, mesh,
  40498. /**
  40499. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40500. */
  40501. side) {
  40502. if (mesh === void 0) { mesh = null; }
  40503. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40504. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40505. _this.radius = radius;
  40506. _this.tube = tube;
  40507. _this.radialSegments = radialSegments;
  40508. _this.tubularSegments = tubularSegments;
  40509. _this.p = p;
  40510. _this.q = q;
  40511. _this.side = side;
  40512. return _this;
  40513. }
  40514. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  40515. 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 });
  40516. };
  40517. TorusKnotGeometry.prototype.copy = function (id) {
  40518. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  40519. };
  40520. TorusKnotGeometry.prototype.serialize = function () {
  40521. var serializationObject = _super.prototype.serialize.call(this);
  40522. serializationObject.radius = this.radius;
  40523. serializationObject.tube = this.tube;
  40524. serializationObject.radialSegments = this.radialSegments;
  40525. serializationObject.tubularSegments = this.tubularSegments;
  40526. serializationObject.p = this.p;
  40527. serializationObject.q = this.q;
  40528. return serializationObject;
  40529. };
  40530. ;
  40531. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  40532. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  40533. return null; // null since geometry could be something else than a ground...
  40534. }
  40535. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  40536. if (BABYLON.Tags) {
  40537. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  40538. }
  40539. scene.pushGeometry(torusKnot, true);
  40540. return torusKnot;
  40541. };
  40542. return TorusKnotGeometry;
  40543. }(_PrimitiveGeometry));
  40544. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  40545. //}
  40546. })(BABYLON || (BABYLON = {}));
  40547. //# sourceMappingURL=babylon.geometry.js.map
  40548. var BABYLON;
  40549. (function (BABYLON) {
  40550. /**
  40551. * PostProcessManager is used to manage one or more post processes or post process pipelines
  40552. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  40553. */
  40554. var PostProcessManager = /** @class */ (function () {
  40555. /**
  40556. * Creates a new instance PostProcess
  40557. * @param scene The scene that the post process is associated with.
  40558. */
  40559. function PostProcessManager(scene) {
  40560. this._vertexBuffers = {};
  40561. this._scene = scene;
  40562. }
  40563. PostProcessManager.prototype._prepareBuffers = function () {
  40564. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  40565. return;
  40566. }
  40567. // VBO
  40568. var vertices = [];
  40569. vertices.push(1, 1);
  40570. vertices.push(-1, 1);
  40571. vertices.push(-1, -1);
  40572. vertices.push(1, -1);
  40573. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  40574. this._buildIndexBuffer();
  40575. };
  40576. PostProcessManager.prototype._buildIndexBuffer = function () {
  40577. // Indices
  40578. var indices = [];
  40579. indices.push(0);
  40580. indices.push(1);
  40581. indices.push(2);
  40582. indices.push(0);
  40583. indices.push(2);
  40584. indices.push(3);
  40585. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  40586. };
  40587. /**
  40588. * Rebuilds the vertex buffers of the manager.
  40589. */
  40590. PostProcessManager.prototype._rebuild = function () {
  40591. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40592. if (!vb) {
  40593. return;
  40594. }
  40595. vb._rebuild();
  40596. this._buildIndexBuffer();
  40597. };
  40598. // Methods
  40599. /**
  40600. * Prepares a frame to be run through a post process.
  40601. * @param sourceTexture The input texture to the post procesess. (default: null)
  40602. * @param postProcesses An array of post processes to be run. (default: null)
  40603. * @returns True if the post processes were able to be run.
  40604. */
  40605. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  40606. if (sourceTexture === void 0) { sourceTexture = null; }
  40607. if (postProcesses === void 0) { postProcesses = null; }
  40608. var camera = this._scene.activeCamera;
  40609. if (!camera) {
  40610. return false;
  40611. }
  40612. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40613. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40614. return false;
  40615. }
  40616. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  40617. return true;
  40618. };
  40619. /**
  40620. * Manually render a set of post processes to a texture.
  40621. * @param postProcesses An array of post processes to be run.
  40622. * @param targetTexture The target texture to render to.
  40623. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  40624. */
  40625. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport) {
  40626. if (targetTexture === void 0) { targetTexture = null; }
  40627. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40628. var engine = this._scene.getEngine();
  40629. for (var index = 0; index < postProcesses.length; index++) {
  40630. if (index < postProcesses.length - 1) {
  40631. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  40632. }
  40633. else {
  40634. if (targetTexture) {
  40635. engine.bindFramebuffer(targetTexture, 0, undefined, undefined, forceFullscreenViewport);
  40636. }
  40637. else {
  40638. engine.restoreDefaultFramebuffer();
  40639. }
  40640. }
  40641. var pp = postProcesses[index];
  40642. var effect = pp.apply();
  40643. if (effect) {
  40644. pp.onBeforeRenderObservable.notifyObservers(effect);
  40645. // VBOs
  40646. this._prepareBuffers();
  40647. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40648. // Draw order
  40649. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40650. pp.onAfterRenderObservable.notifyObservers(effect);
  40651. }
  40652. }
  40653. // Restore depth buffer
  40654. engine.setDepthBuffer(true);
  40655. engine.setDepthWrite(true);
  40656. };
  40657. /**
  40658. * Finalize the result of the output of the postprocesses.
  40659. * @param doNotPresent If true the result will not be displayed to the screen.
  40660. * @param targetTexture The target texture to render to.
  40661. * @param faceIndex The index of the face to bind the target texture to.
  40662. * @param postProcesses The array of post processes to render.
  40663. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  40664. */
  40665. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  40666. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  40667. var camera = this._scene.activeCamera;
  40668. if (!camera) {
  40669. return;
  40670. }
  40671. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  40672. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  40673. return;
  40674. }
  40675. var engine = this._scene.getEngine();
  40676. for (var index = 0, len = postProcesses.length; index < len; index++) {
  40677. var pp = postProcesses[index];
  40678. if (index < len - 1) {
  40679. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  40680. }
  40681. else {
  40682. if (targetTexture) {
  40683. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  40684. pp._outputTexture = targetTexture;
  40685. }
  40686. else {
  40687. engine.restoreDefaultFramebuffer();
  40688. pp._outputTexture = null;
  40689. }
  40690. }
  40691. if (doNotPresent) {
  40692. break;
  40693. }
  40694. var effect = pp.apply();
  40695. if (effect) {
  40696. pp.onBeforeRenderObservable.notifyObservers(effect);
  40697. // VBOs
  40698. this._prepareBuffers();
  40699. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  40700. // Draw order
  40701. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  40702. pp.onAfterRenderObservable.notifyObservers(effect);
  40703. }
  40704. }
  40705. // Restore states
  40706. engine.setDepthBuffer(true);
  40707. engine.setDepthWrite(true);
  40708. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  40709. };
  40710. /**
  40711. * Disposes of the post process manager.
  40712. */
  40713. PostProcessManager.prototype.dispose = function () {
  40714. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  40715. if (buffer) {
  40716. buffer.dispose();
  40717. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  40718. }
  40719. if (this._indexBuffer) {
  40720. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  40721. this._indexBuffer = null;
  40722. }
  40723. };
  40724. return PostProcessManager;
  40725. }());
  40726. BABYLON.PostProcessManager = PostProcessManager;
  40727. })(BABYLON || (BABYLON = {}));
  40728. //# sourceMappingURL=babylon.postProcessManager.js.map
  40729. var BABYLON;
  40730. (function (BABYLON) {
  40731. /**
  40732. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  40733. */
  40734. var PerformanceMonitor = /** @class */ (function () {
  40735. /**
  40736. * constructor
  40737. * @param frameSampleSize The number of samples required to saturate the sliding window
  40738. */
  40739. function PerformanceMonitor(frameSampleSize) {
  40740. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  40741. this._enabled = true;
  40742. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  40743. }
  40744. /**
  40745. * Samples current frame
  40746. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  40747. */
  40748. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  40749. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  40750. if (!this._enabled)
  40751. return;
  40752. if (this._lastFrameTimeMs != null) {
  40753. var dt = timeMs - this._lastFrameTimeMs;
  40754. this._rollingFrameTime.add(dt);
  40755. }
  40756. this._lastFrameTimeMs = timeMs;
  40757. };
  40758. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  40759. /**
  40760. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40761. * @return Average frame time in milliseconds
  40762. */
  40763. get: function () {
  40764. return this._rollingFrameTime.average;
  40765. },
  40766. enumerable: true,
  40767. configurable: true
  40768. });
  40769. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  40770. /**
  40771. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  40772. * @return Frame time variance in milliseconds squared
  40773. */
  40774. get: function () {
  40775. return this._rollingFrameTime.variance;
  40776. },
  40777. enumerable: true,
  40778. configurable: true
  40779. });
  40780. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  40781. /**
  40782. * Returns the frame time of the most recent frame
  40783. * @return Frame time in milliseconds
  40784. */
  40785. get: function () {
  40786. return this._rollingFrameTime.history(0);
  40787. },
  40788. enumerable: true,
  40789. configurable: true
  40790. });
  40791. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  40792. /**
  40793. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  40794. * @return Framerate in frames per second
  40795. */
  40796. get: function () {
  40797. return 1000.0 / this._rollingFrameTime.average;
  40798. },
  40799. enumerable: true,
  40800. configurable: true
  40801. });
  40802. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  40803. /**
  40804. * Returns the average framerate in frames per second using the most recent frame time
  40805. * @return Framerate in frames per second
  40806. */
  40807. get: function () {
  40808. var history = this._rollingFrameTime.history(0);
  40809. if (history === 0) {
  40810. return 0;
  40811. }
  40812. return 1000.0 / history;
  40813. },
  40814. enumerable: true,
  40815. configurable: true
  40816. });
  40817. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  40818. /**
  40819. * Returns true if enough samples have been taken to completely fill the sliding window
  40820. * @return true if saturated
  40821. */
  40822. get: function () {
  40823. return this._rollingFrameTime.isSaturated();
  40824. },
  40825. enumerable: true,
  40826. configurable: true
  40827. });
  40828. /**
  40829. * Enables contributions to the sliding window sample set
  40830. */
  40831. PerformanceMonitor.prototype.enable = function () {
  40832. this._enabled = true;
  40833. };
  40834. /**
  40835. * Disables contributions to the sliding window sample set
  40836. * Samples will not be interpolated over the disabled period
  40837. */
  40838. PerformanceMonitor.prototype.disable = function () {
  40839. this._enabled = false;
  40840. //clear last sample to avoid interpolating over the disabled period when next enabled
  40841. this._lastFrameTimeMs = null;
  40842. };
  40843. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  40844. /**
  40845. * Returns true if sampling is enabled
  40846. * @return true if enabled
  40847. */
  40848. get: function () {
  40849. return this._enabled;
  40850. },
  40851. enumerable: true,
  40852. configurable: true
  40853. });
  40854. /**
  40855. * Resets performance monitor
  40856. */
  40857. PerformanceMonitor.prototype.reset = function () {
  40858. //clear last sample to avoid interpolating over the disabled period when next enabled
  40859. this._lastFrameTimeMs = null;
  40860. //wipe record
  40861. this._rollingFrameTime.reset();
  40862. };
  40863. return PerformanceMonitor;
  40864. }());
  40865. BABYLON.PerformanceMonitor = PerformanceMonitor;
  40866. /**
  40867. * RollingAverage
  40868. *
  40869. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  40870. */
  40871. var RollingAverage = /** @class */ (function () {
  40872. /**
  40873. * constructor
  40874. * @param length The number of samples required to saturate the sliding window
  40875. */
  40876. function RollingAverage(length) {
  40877. this._samples = new Array(length);
  40878. this.reset();
  40879. }
  40880. /**
  40881. * Adds a sample to the sample set
  40882. * @param v The sample value
  40883. */
  40884. RollingAverage.prototype.add = function (v) {
  40885. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  40886. var delta;
  40887. //we need to check if we've already wrapped round
  40888. if (this.isSaturated()) {
  40889. //remove bottom of stack from mean
  40890. var bottomValue = this._samples[this._pos];
  40891. delta = bottomValue - this.average;
  40892. this.average -= delta / (this._sampleCount - 1);
  40893. this._m2 -= delta * (bottomValue - this.average);
  40894. }
  40895. else {
  40896. this._sampleCount++;
  40897. }
  40898. //add new value to mean
  40899. delta = v - this.average;
  40900. this.average += delta / (this._sampleCount);
  40901. this._m2 += delta * (v - this.average);
  40902. //set the new variance
  40903. this.variance = this._m2 / (this._sampleCount - 1);
  40904. this._samples[this._pos] = v;
  40905. this._pos++;
  40906. this._pos %= this._samples.length; //positive wrap around
  40907. };
  40908. /**
  40909. * Returns previously added values or null if outside of history or outside the sliding window domain
  40910. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  40911. * @return Value previously recorded with add() or null if outside of range
  40912. */
  40913. RollingAverage.prototype.history = function (i) {
  40914. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  40915. return 0;
  40916. }
  40917. var i0 = this._wrapPosition(this._pos - 1.0);
  40918. return this._samples[this._wrapPosition(i0 - i)];
  40919. };
  40920. /**
  40921. * Returns true if enough samples have been taken to completely fill the sliding window
  40922. * @return true if sample-set saturated
  40923. */
  40924. RollingAverage.prototype.isSaturated = function () {
  40925. return this._sampleCount >= this._samples.length;
  40926. };
  40927. /**
  40928. * Resets the rolling average (equivalent to 0 samples taken so far)
  40929. */
  40930. RollingAverage.prototype.reset = function () {
  40931. this.average = 0;
  40932. this.variance = 0;
  40933. this._sampleCount = 0;
  40934. this._pos = 0;
  40935. this._m2 = 0;
  40936. };
  40937. /**
  40938. * Wraps a value around the sample range boundaries
  40939. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  40940. * @return Wrapped position in sample range
  40941. */
  40942. RollingAverage.prototype._wrapPosition = function (i) {
  40943. var max = this._samples.length;
  40944. return ((i % max) + max) % max;
  40945. };
  40946. return RollingAverage;
  40947. }());
  40948. BABYLON.RollingAverage = RollingAverage;
  40949. })(BABYLON || (BABYLON = {}));
  40950. //# sourceMappingURL=babylon.performanceMonitor.js.map
  40951. var BABYLON;
  40952. (function (BABYLON) {
  40953. /**
  40954. * This groups together the common properties used for image processing either in direct forward pass
  40955. * or through post processing effect depending on the use of the image processing pipeline in your scene
  40956. * or not.
  40957. */
  40958. var ImageProcessingConfiguration = /** @class */ (function () {
  40959. function ImageProcessingConfiguration() {
  40960. /**
  40961. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  40962. */
  40963. this.colorCurves = new BABYLON.ColorCurves();
  40964. this._colorCurvesEnabled = false;
  40965. this._colorGradingEnabled = false;
  40966. this._colorGradingWithGreenDepth = true;
  40967. this._colorGradingBGR = true;
  40968. this._exposure = 1.0;
  40969. this._toneMappingEnabled = false;
  40970. this._contrast = 1.0;
  40971. /**
  40972. * Vignette stretch size.
  40973. */
  40974. this.vignetteStretch = 0;
  40975. /**
  40976. * Vignette centre X Offset.
  40977. */
  40978. this.vignetteCentreX = 0;
  40979. /**
  40980. * Vignette centre Y Offset.
  40981. */
  40982. this.vignetteCentreY = 0;
  40983. /**
  40984. * Vignette weight or intensity of the vignette effect.
  40985. */
  40986. this.vignetteWeight = 1.5;
  40987. /**
  40988. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  40989. * if vignetteEnabled is set to true.
  40990. */
  40991. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  40992. /**
  40993. * Camera field of view used by the Vignette effect.
  40994. */
  40995. this.vignetteCameraFov = 0.5;
  40996. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  40997. this._vignetteEnabled = false;
  40998. this._applyByPostProcess = false;
  40999. this._isEnabled = true;
  41000. /**
  41001. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  41002. */
  41003. this.onUpdateParameters = new BABYLON.Observable();
  41004. }
  41005. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  41006. /**
  41007. * Gets wether the color curves effect is enabled.
  41008. */
  41009. get: function () {
  41010. return this._colorCurvesEnabled;
  41011. },
  41012. /**
  41013. * Sets wether the color curves effect is enabled.
  41014. */
  41015. set: function (value) {
  41016. if (this._colorCurvesEnabled === value) {
  41017. return;
  41018. }
  41019. this._colorCurvesEnabled = value;
  41020. this._updateParameters();
  41021. },
  41022. enumerable: true,
  41023. configurable: true
  41024. });
  41025. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  41026. /**
  41027. * Gets wether the color grading effect is enabled.
  41028. */
  41029. get: function () {
  41030. return this._colorGradingEnabled;
  41031. },
  41032. /**
  41033. * Sets wether the color grading effect is enabled.
  41034. */
  41035. set: function (value) {
  41036. if (this._colorGradingEnabled === value) {
  41037. return;
  41038. }
  41039. this._colorGradingEnabled = value;
  41040. this._updateParameters();
  41041. },
  41042. enumerable: true,
  41043. configurable: true
  41044. });
  41045. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  41046. /**
  41047. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  41048. */
  41049. get: function () {
  41050. return this._colorGradingWithGreenDepth;
  41051. },
  41052. /**
  41053. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  41054. */
  41055. set: function (value) {
  41056. if (this._colorGradingWithGreenDepth === value) {
  41057. return;
  41058. }
  41059. this._colorGradingWithGreenDepth = value;
  41060. this._updateParameters();
  41061. },
  41062. enumerable: true,
  41063. configurable: true
  41064. });
  41065. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  41066. /**
  41067. * Gets wether the color grading texture contains BGR values.
  41068. */
  41069. get: function () {
  41070. return this._colorGradingBGR;
  41071. },
  41072. /**
  41073. * Sets wether the color grading texture contains BGR values.
  41074. */
  41075. set: function (value) {
  41076. if (this._colorGradingBGR === value) {
  41077. return;
  41078. }
  41079. this._colorGradingBGR = value;
  41080. this._updateParameters();
  41081. },
  41082. enumerable: true,
  41083. configurable: true
  41084. });
  41085. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  41086. /**
  41087. * Gets the Exposure used in the effect.
  41088. */
  41089. get: function () {
  41090. return this._exposure;
  41091. },
  41092. /**
  41093. * Sets the Exposure used in the effect.
  41094. */
  41095. set: function (value) {
  41096. if (this._exposure === value) {
  41097. return;
  41098. }
  41099. this._exposure = value;
  41100. this._updateParameters();
  41101. },
  41102. enumerable: true,
  41103. configurable: true
  41104. });
  41105. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  41106. /**
  41107. * Gets wether the tone mapping effect is enabled.
  41108. */
  41109. get: function () {
  41110. return this._toneMappingEnabled;
  41111. },
  41112. /**
  41113. * Sets wether the tone mapping effect is enabled.
  41114. */
  41115. set: function (value) {
  41116. if (this._toneMappingEnabled === value) {
  41117. return;
  41118. }
  41119. this._toneMappingEnabled = value;
  41120. this._updateParameters();
  41121. },
  41122. enumerable: true,
  41123. configurable: true
  41124. });
  41125. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  41126. /**
  41127. * Gets the contrast used in the effect.
  41128. */
  41129. get: function () {
  41130. return this._contrast;
  41131. },
  41132. /**
  41133. * Sets the contrast used in the effect.
  41134. */
  41135. set: function (value) {
  41136. if (this._contrast === value) {
  41137. return;
  41138. }
  41139. this._contrast = value;
  41140. this._updateParameters();
  41141. },
  41142. enumerable: true,
  41143. configurable: true
  41144. });
  41145. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  41146. /**
  41147. * Gets the vignette blend mode allowing different kind of effect.
  41148. */
  41149. get: function () {
  41150. return this._vignetteBlendMode;
  41151. },
  41152. /**
  41153. * Sets the vignette blend mode allowing different kind of effect.
  41154. */
  41155. set: function (value) {
  41156. if (this._vignetteBlendMode === value) {
  41157. return;
  41158. }
  41159. this._vignetteBlendMode = value;
  41160. this._updateParameters();
  41161. },
  41162. enumerable: true,
  41163. configurable: true
  41164. });
  41165. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  41166. /**
  41167. * Gets wether the vignette effect is enabled.
  41168. */
  41169. get: function () {
  41170. return this._vignetteEnabled;
  41171. },
  41172. /**
  41173. * Sets wether the vignette effect is enabled.
  41174. */
  41175. set: function (value) {
  41176. if (this._vignetteEnabled === value) {
  41177. return;
  41178. }
  41179. this._vignetteEnabled = value;
  41180. this._updateParameters();
  41181. },
  41182. enumerable: true,
  41183. configurable: true
  41184. });
  41185. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  41186. /**
  41187. * Gets wether the image processing is applied through a post process or not.
  41188. */
  41189. get: function () {
  41190. return this._applyByPostProcess;
  41191. },
  41192. /**
  41193. * Sets wether the image processing is applied through a post process or not.
  41194. */
  41195. set: function (value) {
  41196. if (this._applyByPostProcess === value) {
  41197. return;
  41198. }
  41199. this._applyByPostProcess = value;
  41200. this._updateParameters();
  41201. },
  41202. enumerable: true,
  41203. configurable: true
  41204. });
  41205. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  41206. /**
  41207. * Gets wether the image processing is enabled or not.
  41208. */
  41209. get: function () {
  41210. return this._isEnabled;
  41211. },
  41212. /**
  41213. * Sets wether the image processing is enabled or not.
  41214. */
  41215. set: function (value) {
  41216. if (this._isEnabled === value) {
  41217. return;
  41218. }
  41219. this._isEnabled = value;
  41220. this._updateParameters();
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. /**
  41226. * Method called each time the image processing information changes requires to recompile the effect.
  41227. */
  41228. ImageProcessingConfiguration.prototype._updateParameters = function () {
  41229. this.onUpdateParameters.notifyObservers(this);
  41230. };
  41231. ImageProcessingConfiguration.prototype.getClassName = function () {
  41232. return "ImageProcessingConfiguration";
  41233. };
  41234. /**
  41235. * Prepare the list of uniforms associated with the Image Processing effects.
  41236. * @param uniformsList The list of uniforms used in the effect
  41237. * @param defines the list of defines currently in use
  41238. */
  41239. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  41240. if (defines.EXPOSURE) {
  41241. uniforms.push("exposureLinear");
  41242. }
  41243. if (defines.CONTRAST) {
  41244. uniforms.push("contrast");
  41245. }
  41246. if (defines.COLORGRADING) {
  41247. uniforms.push("colorTransformSettings");
  41248. }
  41249. if (defines.VIGNETTE) {
  41250. uniforms.push("vInverseScreenSize");
  41251. uniforms.push("vignetteSettings1");
  41252. uniforms.push("vignetteSettings2");
  41253. }
  41254. if (defines.COLORCURVES) {
  41255. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  41256. }
  41257. };
  41258. /**
  41259. * Prepare the list of samplers associated with the Image Processing effects.
  41260. * @param uniformsList The list of uniforms used in the effect
  41261. * @param defines the list of defines currently in use
  41262. */
  41263. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  41264. if (defines.COLORGRADING) {
  41265. samplersList.push("txColorTransform");
  41266. }
  41267. };
  41268. /**
  41269. * Prepare the list of defines associated to the shader.
  41270. * @param defines the list of defines to complete
  41271. */
  41272. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  41273. if (forPostProcess === void 0) { forPostProcess = false; }
  41274. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  41275. defines.VIGNETTE = false;
  41276. defines.TONEMAPPING = false;
  41277. defines.CONTRAST = false;
  41278. defines.EXPOSURE = false;
  41279. defines.COLORCURVES = false;
  41280. defines.COLORGRADING = false;
  41281. defines.COLORGRADING3D = false;
  41282. defines.IMAGEPROCESSING = false;
  41283. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  41284. return;
  41285. }
  41286. defines.VIGNETTE = this.vignetteEnabled;
  41287. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  41288. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  41289. defines.TONEMAPPING = this.toneMappingEnabled;
  41290. defines.CONTRAST = (this.contrast !== 1.0);
  41291. defines.EXPOSURE = (this.exposure !== 1.0);
  41292. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  41293. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  41294. if (defines.COLORGRADING) {
  41295. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  41296. }
  41297. else {
  41298. defines.COLORGRADING3D = false;
  41299. }
  41300. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  41301. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  41302. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  41303. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  41304. };
  41305. /**
  41306. * Returns true if all the image processing information are ready.
  41307. */
  41308. ImageProcessingConfiguration.prototype.isReady = function () {
  41309. // Color Grading texure can not be none blocking.
  41310. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  41311. };
  41312. /**
  41313. * Binds the image processing to the shader.
  41314. * @param effect The effect to bind to
  41315. */
  41316. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  41317. if (aspectRatio === void 0) { aspectRatio = 1; }
  41318. // Color Curves
  41319. if (this._colorCurvesEnabled && this.colorCurves) {
  41320. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  41321. }
  41322. // Vignette
  41323. if (this._vignetteEnabled) {
  41324. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  41325. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  41326. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  41327. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  41328. var vignetteScaleX = vignetteScaleY * aspectRatio;
  41329. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  41330. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  41331. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  41332. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  41333. var vignettePower = -2.0 * this.vignetteWeight;
  41334. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  41335. }
  41336. // Exposure
  41337. effect.setFloat("exposureLinear", this.exposure);
  41338. // Contrast
  41339. effect.setFloat("contrast", this.contrast);
  41340. // Color transform settings
  41341. if (this.colorGradingTexture) {
  41342. effect.setTexture("txColorTransform", this.colorGradingTexture);
  41343. var textureSize = this.colorGradingTexture.getSize().height;
  41344. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  41345. 0.5 / textureSize, // textureOffset
  41346. textureSize, // textureSize
  41347. this.colorGradingTexture.level // weight
  41348. );
  41349. }
  41350. };
  41351. /**
  41352. * Clones the current image processing instance.
  41353. * @return The cloned image processing
  41354. */
  41355. ImageProcessingConfiguration.prototype.clone = function () {
  41356. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  41357. };
  41358. /**
  41359. * Serializes the current image processing instance to a json representation.
  41360. * @return a JSON representation
  41361. */
  41362. ImageProcessingConfiguration.prototype.serialize = function () {
  41363. return BABYLON.SerializationHelper.Serialize(this);
  41364. };
  41365. /**
  41366. * Parses the image processing from a json representation.
  41367. * @param source the JSON source to parse
  41368. * @return The parsed image processing
  41369. */
  41370. ImageProcessingConfiguration.Parse = function (source) {
  41371. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  41372. };
  41373. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  41374. /**
  41375. * Used to apply the vignette as a mix with the pixel color.
  41376. */
  41377. get: function () {
  41378. return this._VIGNETTEMODE_MULTIPLY;
  41379. },
  41380. enumerable: true,
  41381. configurable: true
  41382. });
  41383. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  41384. /**
  41385. * Used to apply the vignette as a replacement of the pixel color.
  41386. */
  41387. get: function () {
  41388. return this._VIGNETTEMODE_OPAQUE;
  41389. },
  41390. enumerable: true,
  41391. configurable: true
  41392. });
  41393. // Static constants associated to the image processing.
  41394. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  41395. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  41396. __decorate([
  41397. BABYLON.serializeAsColorCurves()
  41398. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  41399. __decorate([
  41400. BABYLON.serialize()
  41401. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  41402. __decorate([
  41403. BABYLON.serializeAsTexture()
  41404. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  41405. __decorate([
  41406. BABYLON.serialize()
  41407. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  41408. __decorate([
  41409. BABYLON.serialize()
  41410. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  41411. __decorate([
  41412. BABYLON.serialize()
  41413. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  41414. __decorate([
  41415. BABYLON.serialize()
  41416. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  41417. __decorate([
  41418. BABYLON.serialize()
  41419. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  41420. __decorate([
  41421. BABYLON.serialize()
  41422. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  41423. __decorate([
  41424. BABYLON.serialize()
  41425. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  41426. __decorate([
  41427. BABYLON.serialize()
  41428. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  41429. __decorate([
  41430. BABYLON.serialize()
  41431. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  41432. __decorate([
  41433. BABYLON.serialize()
  41434. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  41435. __decorate([
  41436. BABYLON.serializeAsColor4()
  41437. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  41438. __decorate([
  41439. BABYLON.serialize()
  41440. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  41441. __decorate([
  41442. BABYLON.serialize()
  41443. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  41444. __decorate([
  41445. BABYLON.serialize()
  41446. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  41447. __decorate([
  41448. BABYLON.serialize()
  41449. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  41450. __decorate([
  41451. BABYLON.serialize()
  41452. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  41453. return ImageProcessingConfiguration;
  41454. }());
  41455. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  41456. })(BABYLON || (BABYLON = {}));
  41457. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  41458. var BABYLON;
  41459. (function (BABYLON) {
  41460. /**
  41461. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  41462. * It can help converting any input color in a desired output one. This can then be used to create effects
  41463. * from sepia, black and white to sixties or futuristic rendering...
  41464. *
  41465. * The only supported format is currently 3dl.
  41466. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  41467. */
  41468. var ColorGradingTexture = /** @class */ (function (_super) {
  41469. __extends(ColorGradingTexture, _super);
  41470. /**
  41471. * Instantiates a ColorGradingTexture from the following parameters.
  41472. *
  41473. * @param url The location of the color gradind data (currently only supporting 3dl)
  41474. * @param scene The scene the texture will be used in
  41475. */
  41476. function ColorGradingTexture(url, scene) {
  41477. var _this = _super.call(this, scene) || this;
  41478. if (!url) {
  41479. return _this;
  41480. }
  41481. _this._engine = scene.getEngine();
  41482. _this._textureMatrix = BABYLON.Matrix.Identity();
  41483. _this.name = url;
  41484. _this.url = url;
  41485. _this.hasAlpha = false;
  41486. _this.isCube = false;
  41487. _this.is3D = _this._engine.webGLVersion > 1;
  41488. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41489. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41490. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  41491. _this.anisotropicFilteringLevel = 1;
  41492. _this._texture = _this._getFromCache(url, true);
  41493. if (!_this._texture) {
  41494. if (!scene.useDelayedTextureLoading) {
  41495. _this.loadTexture();
  41496. }
  41497. else {
  41498. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  41499. }
  41500. }
  41501. return _this;
  41502. }
  41503. /**
  41504. * Returns the texture matrix used in most of the material.
  41505. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  41506. */
  41507. ColorGradingTexture.prototype.getTextureMatrix = function () {
  41508. return this._textureMatrix;
  41509. };
  41510. /**
  41511. * Occurs when the file being loaded is a .3dl LUT file.
  41512. */
  41513. ColorGradingTexture.prototype.load3dlTexture = function () {
  41514. var engine = this._engine;
  41515. var texture;
  41516. if (engine.webGLVersion === 1) {
  41517. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41518. }
  41519. else {
  41520. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  41521. }
  41522. this._texture = texture;
  41523. var callback = function (text) {
  41524. if (typeof text !== "string") {
  41525. return;
  41526. }
  41527. var data = null;
  41528. var tempData = null;
  41529. var line;
  41530. var lines = text.split('\n');
  41531. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  41532. var maxColor = 0;
  41533. for (var i = 0; i < lines.length; i++) {
  41534. line = lines[i];
  41535. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  41536. continue;
  41537. if (line.indexOf('#') === 0)
  41538. continue;
  41539. var words = line.split(" ");
  41540. if (size === 0) {
  41541. // Number of space + one
  41542. size = words.length;
  41543. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  41544. tempData = new Float32Array(size * size * size * 4);
  41545. continue;
  41546. }
  41547. if (size != 0) {
  41548. var r = Math.max(parseInt(words[0]), 0);
  41549. var g = Math.max(parseInt(words[1]), 0);
  41550. var b = Math.max(parseInt(words[2]), 0);
  41551. maxColor = Math.max(r, maxColor);
  41552. maxColor = Math.max(g, maxColor);
  41553. maxColor = Math.max(b, maxColor);
  41554. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  41555. if (tempData) {
  41556. tempData[pixelStorageIndex + 0] = r;
  41557. tempData[pixelStorageIndex + 1] = g;
  41558. tempData[pixelStorageIndex + 2] = b;
  41559. }
  41560. pixelIndexSlice++;
  41561. if (pixelIndexSlice % size == 0) {
  41562. pixelIndexH++;
  41563. pixelIndexSlice = 0;
  41564. if (pixelIndexH % size == 0) {
  41565. pixelIndexW++;
  41566. pixelIndexH = 0;
  41567. }
  41568. }
  41569. }
  41570. }
  41571. if (tempData && data) {
  41572. for (var i = 0; i < tempData.length; i++) {
  41573. if (i > 0 && (i + 1) % 4 === 0) {
  41574. data[i] = 255;
  41575. }
  41576. else {
  41577. var value = tempData[i];
  41578. data[i] = (value / maxColor * 255);
  41579. }
  41580. }
  41581. }
  41582. if (texture.is3D) {
  41583. texture.updateSize(size, size, size);
  41584. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41585. }
  41586. else {
  41587. texture.updateSize(size * size, size);
  41588. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  41589. }
  41590. };
  41591. var scene = this.getScene();
  41592. if (scene) {
  41593. scene._loadFile(this.url, callback);
  41594. }
  41595. else {
  41596. this._engine._loadFile(this.url, callback);
  41597. }
  41598. return this._texture;
  41599. };
  41600. /**
  41601. * Starts the loading process of the texture.
  41602. */
  41603. ColorGradingTexture.prototype.loadTexture = function () {
  41604. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  41605. this.load3dlTexture();
  41606. }
  41607. };
  41608. /**
  41609. * Clones the color gradind texture.
  41610. */
  41611. ColorGradingTexture.prototype.clone = function () {
  41612. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  41613. // Base texture
  41614. newTexture.level = this.level;
  41615. return newTexture;
  41616. };
  41617. /**
  41618. * Called during delayed load for textures.
  41619. */
  41620. ColorGradingTexture.prototype.delayLoad = function () {
  41621. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  41622. return;
  41623. }
  41624. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  41625. this._texture = this._getFromCache(this.url, true);
  41626. if (!this._texture) {
  41627. this.loadTexture();
  41628. }
  41629. };
  41630. /**
  41631. * Parses a color grading texture serialized by Babylon.
  41632. * @param parsedTexture The texture information being parsedTexture
  41633. * @param scene The scene to load the texture in
  41634. * @param rootUrl The root url of the data assets to load
  41635. * @return A color gradind texture
  41636. */
  41637. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  41638. var texture = null;
  41639. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  41640. texture = new ColorGradingTexture(parsedTexture.name, scene);
  41641. texture.name = parsedTexture.name;
  41642. texture.level = parsedTexture.level;
  41643. }
  41644. return texture;
  41645. };
  41646. /**
  41647. * Serializes the LUT texture to json format.
  41648. */
  41649. ColorGradingTexture.prototype.serialize = function () {
  41650. if (!this.name) {
  41651. return null;
  41652. }
  41653. var serializationObject = {};
  41654. serializationObject.name = this.name;
  41655. serializationObject.level = this.level;
  41656. serializationObject.customType = "BABYLON.ColorGradingTexture";
  41657. return serializationObject;
  41658. };
  41659. /**
  41660. * Empty line regex stored for GC.
  41661. */
  41662. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  41663. return ColorGradingTexture;
  41664. }(BABYLON.BaseTexture));
  41665. BABYLON.ColorGradingTexture = ColorGradingTexture;
  41666. })(BABYLON || (BABYLON = {}));
  41667. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  41668. var BABYLON;
  41669. (function (BABYLON) {
  41670. /**
  41671. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  41672. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  41673. * 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;
  41674. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  41675. */
  41676. var ColorCurves = /** @class */ (function () {
  41677. function ColorCurves() {
  41678. this._dirty = true;
  41679. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  41680. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  41681. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41682. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  41683. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  41684. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  41685. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  41686. this._globalHue = 30;
  41687. this._globalDensity = 0;
  41688. this._globalSaturation = 0;
  41689. this._globalExposure = 0;
  41690. this._highlightsHue = 30;
  41691. this._highlightsDensity = 0;
  41692. this._highlightsSaturation = 0;
  41693. this._highlightsExposure = 0;
  41694. this._midtonesHue = 30;
  41695. this._midtonesDensity = 0;
  41696. this._midtonesSaturation = 0;
  41697. this._midtonesExposure = 0;
  41698. this._shadowsHue = 30;
  41699. this._shadowsDensity = 0;
  41700. this._shadowsSaturation = 0;
  41701. this._shadowsExposure = 0;
  41702. }
  41703. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  41704. /**
  41705. * Gets the global Hue value.
  41706. * 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).
  41707. */
  41708. get: function () {
  41709. return this._globalHue;
  41710. },
  41711. /**
  41712. * Sets the global Hue value.
  41713. * 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).
  41714. */
  41715. set: function (value) {
  41716. this._globalHue = value;
  41717. this._dirty = true;
  41718. },
  41719. enumerable: true,
  41720. configurable: true
  41721. });
  41722. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  41723. /**
  41724. * Gets the global Density value.
  41725. * 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.
  41726. * Values less than zero provide a filter of opposite hue.
  41727. */
  41728. get: function () {
  41729. return this._globalDensity;
  41730. },
  41731. /**
  41732. * Sets the global Density value.
  41733. * 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.
  41734. * Values less than zero provide a filter of opposite hue.
  41735. */
  41736. set: function (value) {
  41737. this._globalDensity = value;
  41738. this._dirty = true;
  41739. },
  41740. enumerable: true,
  41741. configurable: true
  41742. });
  41743. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  41744. /**
  41745. * Gets the global Saturation value.
  41746. * 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.
  41747. */
  41748. get: function () {
  41749. return this._globalSaturation;
  41750. },
  41751. /**
  41752. * Sets the global Saturation value.
  41753. * 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.
  41754. */
  41755. set: function (value) {
  41756. this._globalSaturation = value;
  41757. this._dirty = true;
  41758. },
  41759. enumerable: true,
  41760. configurable: true
  41761. });
  41762. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  41763. /**
  41764. * Gets the highlights Hue value.
  41765. * 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).
  41766. */
  41767. get: function () {
  41768. return this._highlightsHue;
  41769. },
  41770. /**
  41771. * Sets the highlights Hue value.
  41772. * 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).
  41773. */
  41774. set: function (value) {
  41775. this._highlightsHue = value;
  41776. this._dirty = true;
  41777. },
  41778. enumerable: true,
  41779. configurable: true
  41780. });
  41781. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  41782. /**
  41783. * Gets the highlights Density value.
  41784. * 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.
  41785. * Values less than zero provide a filter of opposite hue.
  41786. */
  41787. get: function () {
  41788. return this._highlightsDensity;
  41789. },
  41790. /**
  41791. * Sets the highlights Density value.
  41792. * 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.
  41793. * Values less than zero provide a filter of opposite hue.
  41794. */
  41795. set: function (value) {
  41796. this._highlightsDensity = value;
  41797. this._dirty = true;
  41798. },
  41799. enumerable: true,
  41800. configurable: true
  41801. });
  41802. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  41803. /**
  41804. * Gets the highlights Saturation value.
  41805. * 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.
  41806. */
  41807. get: function () {
  41808. return this._highlightsSaturation;
  41809. },
  41810. /**
  41811. * Sets the highlights Saturation value.
  41812. * 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.
  41813. */
  41814. set: function (value) {
  41815. this._highlightsSaturation = value;
  41816. this._dirty = true;
  41817. },
  41818. enumerable: true,
  41819. configurable: true
  41820. });
  41821. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  41822. /**
  41823. * Gets the highlights Exposure value.
  41824. * 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.
  41825. */
  41826. get: function () {
  41827. return this._highlightsExposure;
  41828. },
  41829. /**
  41830. * Sets the highlights Exposure value.
  41831. * 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.
  41832. */
  41833. set: function (value) {
  41834. this._highlightsExposure = value;
  41835. this._dirty = true;
  41836. },
  41837. enumerable: true,
  41838. configurable: true
  41839. });
  41840. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  41841. /**
  41842. * Gets the midtones Hue value.
  41843. * 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).
  41844. */
  41845. get: function () {
  41846. return this._midtonesHue;
  41847. },
  41848. /**
  41849. * Sets the midtones Hue value.
  41850. * 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).
  41851. */
  41852. set: function (value) {
  41853. this._midtonesHue = value;
  41854. this._dirty = true;
  41855. },
  41856. enumerable: true,
  41857. configurable: true
  41858. });
  41859. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  41860. /**
  41861. * Gets the midtones Density value.
  41862. * 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.
  41863. * Values less than zero provide a filter of opposite hue.
  41864. */
  41865. get: function () {
  41866. return this._midtonesDensity;
  41867. },
  41868. /**
  41869. * Sets the midtones Density value.
  41870. * 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.
  41871. * Values less than zero provide a filter of opposite hue.
  41872. */
  41873. set: function (value) {
  41874. this._midtonesDensity = value;
  41875. this._dirty = true;
  41876. },
  41877. enumerable: true,
  41878. configurable: true
  41879. });
  41880. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  41881. /**
  41882. * Gets the midtones Saturation value.
  41883. * 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.
  41884. */
  41885. get: function () {
  41886. return this._midtonesSaturation;
  41887. },
  41888. /**
  41889. * Sets the midtones Saturation value.
  41890. * 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.
  41891. */
  41892. set: function (value) {
  41893. this._midtonesSaturation = value;
  41894. this._dirty = true;
  41895. },
  41896. enumerable: true,
  41897. configurable: true
  41898. });
  41899. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  41900. /**
  41901. * Gets the midtones Exposure value.
  41902. * 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.
  41903. */
  41904. get: function () {
  41905. return this._midtonesExposure;
  41906. },
  41907. /**
  41908. * Sets the midtones Exposure value.
  41909. * 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.
  41910. */
  41911. set: function (value) {
  41912. this._midtonesExposure = value;
  41913. this._dirty = true;
  41914. },
  41915. enumerable: true,
  41916. configurable: true
  41917. });
  41918. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  41919. /**
  41920. * Gets the shadows Hue value.
  41921. * 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).
  41922. */
  41923. get: function () {
  41924. return this._shadowsHue;
  41925. },
  41926. /**
  41927. * Sets the shadows Hue value.
  41928. * 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).
  41929. */
  41930. set: function (value) {
  41931. this._shadowsHue = value;
  41932. this._dirty = true;
  41933. },
  41934. enumerable: true,
  41935. configurable: true
  41936. });
  41937. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  41938. /**
  41939. * Gets the shadows Density value.
  41940. * 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.
  41941. * Values less than zero provide a filter of opposite hue.
  41942. */
  41943. get: function () {
  41944. return this._shadowsDensity;
  41945. },
  41946. /**
  41947. * Sets the shadows Density value.
  41948. * 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.
  41949. * Values less than zero provide a filter of opposite hue.
  41950. */
  41951. set: function (value) {
  41952. this._shadowsDensity = value;
  41953. this._dirty = true;
  41954. },
  41955. enumerable: true,
  41956. configurable: true
  41957. });
  41958. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  41959. /**
  41960. * Gets the shadows Saturation value.
  41961. * 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.
  41962. */
  41963. get: function () {
  41964. return this._shadowsSaturation;
  41965. },
  41966. /**
  41967. * Sets the shadows Saturation value.
  41968. * 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.
  41969. */
  41970. set: function (value) {
  41971. this._shadowsSaturation = value;
  41972. this._dirty = true;
  41973. },
  41974. enumerable: true,
  41975. configurable: true
  41976. });
  41977. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  41978. /**
  41979. * Gets the shadows Exposure value.
  41980. * 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.
  41981. */
  41982. get: function () {
  41983. return this._shadowsExposure;
  41984. },
  41985. /**
  41986. * Sets the shadows Exposure value.
  41987. * 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.
  41988. */
  41989. set: function (value) {
  41990. this._shadowsExposure = value;
  41991. this._dirty = true;
  41992. },
  41993. enumerable: true,
  41994. configurable: true
  41995. });
  41996. ColorCurves.prototype.getClassName = function () {
  41997. return "ColorCurves";
  41998. };
  41999. /**
  42000. * Binds the color curves to the shader.
  42001. * @param colorCurves The color curve to bind
  42002. * @param effect The effect to bind to
  42003. */
  42004. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  42005. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  42006. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  42007. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  42008. if (colorCurves._dirty) {
  42009. colorCurves._dirty = false;
  42010. // Fill in global info.
  42011. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  42012. // Compute highlights info.
  42013. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  42014. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  42015. // Compute midtones info.
  42016. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  42017. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  42018. // Compute shadows info.
  42019. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  42020. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  42021. // Compute deltas (neutral is midtones).
  42022. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  42023. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  42024. }
  42025. if (effect) {
  42026. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  42027. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  42028. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  42029. }
  42030. };
  42031. /**
  42032. * Prepare the list of uniforms associated with the ColorCurves effects.
  42033. * @param uniformsList The list of uniforms used in the effect
  42034. */
  42035. ColorCurves.PrepareUniforms = function (uniformsList) {
  42036. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  42037. };
  42038. /**
  42039. * Returns color grading data based on a hue, density, saturation and exposure value.
  42040. * @param filterHue The hue of the color filter.
  42041. * @param filterDensity The density of the color filter.
  42042. * @param saturation The saturation.
  42043. * @param exposure The exposure.
  42044. * @param result The result data container.
  42045. */
  42046. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  42047. if (hue == null) {
  42048. return;
  42049. }
  42050. hue = ColorCurves.clamp(hue, 0, 360);
  42051. density = ColorCurves.clamp(density, -100, 100);
  42052. saturation = ColorCurves.clamp(saturation, -100, 100);
  42053. exposure = ColorCurves.clamp(exposure, -100, 100);
  42054. // Remap the slider/config filter density with non-linear mapping and also scale by half
  42055. // so that the maximum filter density is only 50% control. This provides fine control
  42056. // for small values and reasonable range.
  42057. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  42058. density *= 0.5;
  42059. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  42060. if (density < 0) {
  42061. density *= -1;
  42062. hue = (hue + 180) % 360;
  42063. }
  42064. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  42065. result.scaleToRef(2, result);
  42066. result.a = 1 + 0.01 * saturation;
  42067. };
  42068. /**
  42069. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  42070. * @param value The input slider value in range [-100,100].
  42071. * @returns Adjusted value.
  42072. */
  42073. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  42074. value /= 100;
  42075. var x = Math.abs(value);
  42076. x = Math.pow(x, 2);
  42077. if (value < 0) {
  42078. x *= -1;
  42079. }
  42080. x *= 100;
  42081. return x;
  42082. };
  42083. /**
  42084. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  42085. * @param hue The hue (H) input.
  42086. * @param saturation The saturation (S) input.
  42087. * @param brightness The brightness (B) input.
  42088. * @result An RGBA color represented as Vector4.
  42089. */
  42090. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  42091. var h = ColorCurves.clamp(hue, 0, 360);
  42092. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  42093. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  42094. if (s === 0) {
  42095. result.r = v;
  42096. result.g = v;
  42097. result.b = v;
  42098. }
  42099. else {
  42100. // sector 0 to 5
  42101. h /= 60;
  42102. var i = Math.floor(h);
  42103. // fractional part of h
  42104. var f = h - i;
  42105. var p = v * (1 - s);
  42106. var q = v * (1 - s * f);
  42107. var t = v * (1 - s * (1 - f));
  42108. switch (i) {
  42109. case 0:
  42110. result.r = v;
  42111. result.g = t;
  42112. result.b = p;
  42113. break;
  42114. case 1:
  42115. result.r = q;
  42116. result.g = v;
  42117. result.b = p;
  42118. break;
  42119. case 2:
  42120. result.r = p;
  42121. result.g = v;
  42122. result.b = t;
  42123. break;
  42124. case 3:
  42125. result.r = p;
  42126. result.g = q;
  42127. result.b = v;
  42128. break;
  42129. case 4:
  42130. result.r = t;
  42131. result.g = p;
  42132. result.b = v;
  42133. break;
  42134. default: // case 5:
  42135. result.r = v;
  42136. result.g = p;
  42137. result.b = q;
  42138. break;
  42139. }
  42140. }
  42141. result.a = 1;
  42142. };
  42143. /**
  42144. * Returns a value clamped between min and max
  42145. * @param value The value to clamp
  42146. * @param min The minimum of value
  42147. * @param max The maximum of value
  42148. * @returns The clamped value.
  42149. */
  42150. ColorCurves.clamp = function (value, min, max) {
  42151. return Math.min(Math.max(value, min), max);
  42152. };
  42153. /**
  42154. * Clones the current color curve instance.
  42155. * @return The cloned curves
  42156. */
  42157. ColorCurves.prototype.clone = function () {
  42158. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  42159. };
  42160. /**
  42161. * Serializes the current color curve instance to a json representation.
  42162. * @return a JSON representation
  42163. */
  42164. ColorCurves.prototype.serialize = function () {
  42165. return BABYLON.SerializationHelper.Serialize(this);
  42166. };
  42167. /**
  42168. * Parses the color curve from a json representation.
  42169. * @param source the JSON source to parse
  42170. * @return The parsed curves
  42171. */
  42172. ColorCurves.Parse = function (source) {
  42173. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  42174. };
  42175. __decorate([
  42176. BABYLON.serialize()
  42177. ], ColorCurves.prototype, "_globalHue", void 0);
  42178. __decorate([
  42179. BABYLON.serialize()
  42180. ], ColorCurves.prototype, "_globalDensity", void 0);
  42181. __decorate([
  42182. BABYLON.serialize()
  42183. ], ColorCurves.prototype, "_globalSaturation", void 0);
  42184. __decorate([
  42185. BABYLON.serialize()
  42186. ], ColorCurves.prototype, "_globalExposure", void 0);
  42187. __decorate([
  42188. BABYLON.serialize()
  42189. ], ColorCurves.prototype, "_highlightsHue", void 0);
  42190. __decorate([
  42191. BABYLON.serialize()
  42192. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  42193. __decorate([
  42194. BABYLON.serialize()
  42195. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  42196. __decorate([
  42197. BABYLON.serialize()
  42198. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  42199. __decorate([
  42200. BABYLON.serialize()
  42201. ], ColorCurves.prototype, "_midtonesHue", void 0);
  42202. __decorate([
  42203. BABYLON.serialize()
  42204. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  42205. __decorate([
  42206. BABYLON.serialize()
  42207. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  42208. __decorate([
  42209. BABYLON.serialize()
  42210. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  42211. return ColorCurves;
  42212. }());
  42213. BABYLON.ColorCurves = ColorCurves;
  42214. })(BABYLON || (BABYLON = {}));
  42215. //# sourceMappingURL=babylon.colorCurves.js.map
  42216. //# sourceMappingURL=babylon.behavior.js.map
  42217. var BABYLON;
  42218. (function (BABYLON) {
  42219. /**
  42220. * "Static Class" containing the most commonly used helper while dealing with material for
  42221. * rendering purpose.
  42222. *
  42223. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  42224. *
  42225. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  42226. */
  42227. var MaterialHelper = /** @class */ (function () {
  42228. function MaterialHelper() {
  42229. }
  42230. /**
  42231. * Bind the current view position to an effect.
  42232. * @param effect The effect to be bound
  42233. * @param scene The scene the eyes position is used from
  42234. */
  42235. MaterialHelper.BindEyePosition = function (effect, scene) {
  42236. if (scene._forcedViewPosition) {
  42237. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  42238. return;
  42239. }
  42240. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  42241. };
  42242. /**
  42243. * Helps preparing the defines values about the UVs in used in the effect.
  42244. * UVs are shared as much as we can accross chanels in the shaders.
  42245. * @param texture The texture we are preparing the UVs for
  42246. * @param defines The defines to update
  42247. * @param key The chanel key "diffuse", "specular"... used in the shader
  42248. */
  42249. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  42250. defines._needUVs = true;
  42251. defines[key] = true;
  42252. if (texture.getTextureMatrix().isIdentity(true)) {
  42253. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  42254. if (texture.coordinatesIndex === 0) {
  42255. defines["MAINUV1"] = true;
  42256. }
  42257. else {
  42258. defines["MAINUV2"] = true;
  42259. }
  42260. }
  42261. else {
  42262. defines[key + "DIRECTUV"] = 0;
  42263. }
  42264. };
  42265. /**
  42266. * Binds a texture matrix value to its corrsponding uniform
  42267. * @param texture The texture to bind the matrix for
  42268. * @param uniformBuffer The uniform buffer receivin the data
  42269. * @param key The chanel key "diffuse", "specular"... used in the shader
  42270. */
  42271. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  42272. var matrix = texture.getTextureMatrix();
  42273. if (!matrix.isIdentity(true)) {
  42274. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  42275. }
  42276. };
  42277. /**
  42278. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  42279. * @param mesh defines the current mesh
  42280. * @param scene defines the current scene
  42281. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  42282. * @param pointsCloud defines if point cloud rendering has to be turned on
  42283. * @param fogEnabled defines if fog has to be turned on
  42284. * @param alphaTest defines if alpha testing has to be turned on
  42285. * @param defines defines the current list of defines
  42286. */
  42287. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  42288. if (defines._areMiscDirty) {
  42289. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  42290. defines["POINTSIZE"] = pointsCloud;
  42291. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  42292. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  42293. defines["ALPHATEST"] = alphaTest;
  42294. }
  42295. };
  42296. /**
  42297. * Helper used to prepare the list of defines associated with frame values for shader compilation
  42298. * @param scene defines the current scene
  42299. * @param engine defines the current engine
  42300. * @param defines specifies the list of active defines
  42301. * @param useInstances defines if instances have to be turned on
  42302. * @param useClipPlane defines if clip plane have to be turned on
  42303. */
  42304. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  42305. if (useClipPlane === void 0) { useClipPlane = null; }
  42306. var changed = false;
  42307. if (useClipPlane == null) {
  42308. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  42309. }
  42310. if (defines["CLIPPLANE"] !== useClipPlane) {
  42311. defines["CLIPPLANE"] = useClipPlane;
  42312. changed = true;
  42313. }
  42314. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  42315. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  42316. changed = true;
  42317. }
  42318. if (defines["INSTANCES"] !== useInstances) {
  42319. defines["INSTANCES"] = useInstances;
  42320. changed = true;
  42321. }
  42322. if (changed) {
  42323. defines.markAsUnprocessed();
  42324. }
  42325. };
  42326. /**
  42327. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  42328. * @param mesh The mesh containing the geometry data we will draw
  42329. * @param defines The defines to update
  42330. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  42331. * @param useBones Precise whether bones should be used or not (override mesh info)
  42332. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  42333. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  42334. * @returns false if defines are considered not dirty and have not been checked
  42335. */
  42336. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  42337. if (useMorphTargets === void 0) { useMorphTargets = false; }
  42338. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  42339. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  42340. return false;
  42341. }
  42342. defines._normals = defines._needNormals;
  42343. defines._uvs = defines._needUVs;
  42344. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  42345. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  42346. defines["TANGENT"] = true;
  42347. }
  42348. if (defines._needUVs) {
  42349. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  42350. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  42351. }
  42352. else {
  42353. defines["UV1"] = false;
  42354. defines["UV2"] = false;
  42355. }
  42356. if (useVertexColor) {
  42357. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  42358. defines["VERTEXCOLOR"] = hasVertexColors;
  42359. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  42360. }
  42361. if (useBones) {
  42362. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42363. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  42364. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  42365. }
  42366. else {
  42367. defines["NUM_BONE_INFLUENCERS"] = 0;
  42368. defines["BonesPerMesh"] = 0;
  42369. }
  42370. }
  42371. if (useMorphTargets) {
  42372. var manager = mesh.morphTargetManager;
  42373. if (manager) {
  42374. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  42375. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  42376. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  42377. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  42378. }
  42379. else {
  42380. defines["MORPHTARGETS_TANGENT"] = false;
  42381. defines["MORPHTARGETS_NORMAL"] = false;
  42382. defines["MORPHTARGETS"] = false;
  42383. defines["NUM_MORPH_INFLUENCERS"] = 0;
  42384. }
  42385. }
  42386. return true;
  42387. };
  42388. /**
  42389. * Prepares the defines related to the light information passed in parameter
  42390. * @param scene The scene we are intending to draw
  42391. * @param mesh The mesh the effect is compiling for
  42392. * @param defines The defines to update
  42393. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  42394. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  42395. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  42396. * @returns true if normals will be required for the rest of the effect
  42397. */
  42398. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  42399. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42400. if (disableLighting === void 0) { disableLighting = false; }
  42401. if (!defines._areLightsDirty) {
  42402. return defines._needNormals;
  42403. }
  42404. var lightIndex = 0;
  42405. var needNormals = false;
  42406. var needRebuild = false;
  42407. var lightmapMode = false;
  42408. var shadowEnabled = false;
  42409. var specularEnabled = false;
  42410. if (scene.lightsEnabled && !disableLighting) {
  42411. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  42412. var light = _a[_i];
  42413. needNormals = true;
  42414. if (defines["LIGHT" + lightIndex] === undefined) {
  42415. needRebuild = true;
  42416. }
  42417. defines["LIGHT" + lightIndex] = true;
  42418. defines["SPOTLIGHT" + lightIndex] = false;
  42419. defines["HEMILIGHT" + lightIndex] = false;
  42420. defines["POINTLIGHT" + lightIndex] = false;
  42421. defines["DIRLIGHT" + lightIndex] = false;
  42422. var type;
  42423. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  42424. type = "SPOTLIGHT" + lightIndex;
  42425. var spotLight = light;
  42426. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  42427. }
  42428. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  42429. type = "HEMILIGHT" + lightIndex;
  42430. }
  42431. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  42432. type = "POINTLIGHT" + lightIndex;
  42433. }
  42434. else {
  42435. type = "DIRLIGHT" + lightIndex;
  42436. }
  42437. defines[type] = true;
  42438. // Specular
  42439. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  42440. specularEnabled = true;
  42441. }
  42442. // Shadows
  42443. defines["SHADOW" + lightIndex] = false;
  42444. defines["SHADOWPCF" + lightIndex] = false;
  42445. defines["SHADOWPCSS" + lightIndex] = false;
  42446. defines["SHADOWPOISSON" + lightIndex] = false;
  42447. defines["SHADOWESM" + lightIndex] = false;
  42448. defines["SHADOWCUBE" + lightIndex] = false;
  42449. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  42450. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  42451. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  42452. var shadowGenerator = light.getShadowGenerator();
  42453. if (shadowGenerator) {
  42454. shadowEnabled = true;
  42455. shadowGenerator.prepareDefines(defines, lightIndex);
  42456. }
  42457. }
  42458. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  42459. lightmapMode = true;
  42460. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  42461. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  42462. }
  42463. else {
  42464. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  42465. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  42466. }
  42467. lightIndex++;
  42468. if (lightIndex === maxSimultaneousLights)
  42469. break;
  42470. }
  42471. }
  42472. defines["SPECULARTERM"] = specularEnabled;
  42473. defines["SHADOWS"] = shadowEnabled;
  42474. // Resetting all other lights if any
  42475. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  42476. if (defines["LIGHT" + index] !== undefined) {
  42477. defines["LIGHT" + index] = false;
  42478. defines["HEMILIGHT" + lightIndex] = false;
  42479. defines["POINTLIGHT" + lightIndex] = false;
  42480. defines["DIRLIGHT" + lightIndex] = false;
  42481. defines["SPOTLIGHT" + lightIndex] = false;
  42482. defines["SHADOW" + lightIndex] = false;
  42483. }
  42484. }
  42485. var caps = scene.getEngine().getCaps();
  42486. if (defines["SHADOWFLOAT"] === undefined) {
  42487. needRebuild = true;
  42488. }
  42489. defines["SHADOWFLOAT"] = shadowEnabled &&
  42490. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  42491. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  42492. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  42493. if (needRebuild) {
  42494. defines.rebuild();
  42495. }
  42496. return needNormals;
  42497. };
  42498. /**
  42499. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  42500. * that won t be acctive due to defines being turned off.
  42501. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  42502. * @param samplersList The samplers list
  42503. * @param defines The defines helping in the list generation
  42504. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  42505. */
  42506. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  42507. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42508. var uniformsList;
  42509. var uniformBuffersList = null;
  42510. if (uniformsListOrOptions.uniformsNames) {
  42511. var options = uniformsListOrOptions;
  42512. uniformsList = options.uniformsNames;
  42513. uniformBuffersList = options.uniformBuffersNames;
  42514. samplersList = options.samplers;
  42515. defines = options.defines;
  42516. maxSimultaneousLights = options.maxSimultaneousLights;
  42517. }
  42518. else {
  42519. uniformsList = uniformsListOrOptions;
  42520. if (!samplersList) {
  42521. samplersList = [];
  42522. }
  42523. }
  42524. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42525. if (!defines["LIGHT" + lightIndex]) {
  42526. break;
  42527. }
  42528. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  42529. if (uniformBuffersList) {
  42530. uniformBuffersList.push("Light" + lightIndex);
  42531. }
  42532. samplersList.push("shadowSampler" + lightIndex);
  42533. samplersList.push("depthSampler" + lightIndex);
  42534. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  42535. samplersList.push("projectionLightSampler" + lightIndex);
  42536. uniformsList.push("textureProjectionMatrix" + lightIndex);
  42537. }
  42538. }
  42539. if (defines["NUM_MORPH_INFLUENCERS"]) {
  42540. uniformsList.push("morphTargetInfluences");
  42541. }
  42542. };
  42543. /**
  42544. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  42545. * @param defines The defines to update while falling back
  42546. * @param fallbacks The authorized effect fallbacks
  42547. * @param maxSimultaneousLights The maximum number of lights allowed
  42548. * @param rank the current rank of the Effect
  42549. * @returns The newly affected rank
  42550. */
  42551. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  42552. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42553. if (rank === void 0) { rank = 0; }
  42554. var lightFallbackRank = 0;
  42555. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  42556. if (!defines["LIGHT" + lightIndex]) {
  42557. break;
  42558. }
  42559. if (lightIndex > 0) {
  42560. lightFallbackRank = rank + lightIndex;
  42561. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  42562. }
  42563. if (!defines["SHADOWS"]) {
  42564. if (defines["SHADOW" + lightIndex]) {
  42565. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  42566. }
  42567. if (defines["SHADOWPCF" + lightIndex]) {
  42568. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  42569. }
  42570. if (defines["SHADOWPCSS" + lightIndex]) {
  42571. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  42572. }
  42573. if (defines["SHADOWPOISSON" + lightIndex]) {
  42574. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  42575. }
  42576. if (defines["SHADOWESM" + lightIndex]) {
  42577. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  42578. }
  42579. }
  42580. }
  42581. return lightFallbackRank++;
  42582. };
  42583. /**
  42584. * Prepares the list of attributes required for morph targets according to the effect defines.
  42585. * @param attribs The current list of supported attribs
  42586. * @param mesh The mesh to prepare the morph targets attributes for
  42587. * @param defines The current Defines of the effect
  42588. */
  42589. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  42590. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  42591. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  42592. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  42593. var manager = mesh.morphTargetManager;
  42594. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  42595. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  42596. for (var index = 0; index < influencers; index++) {
  42597. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  42598. if (normal) {
  42599. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  42600. }
  42601. if (tangent) {
  42602. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  42603. }
  42604. if (attribs.length > maxAttributesCount) {
  42605. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  42606. }
  42607. }
  42608. }
  42609. };
  42610. /**
  42611. * Prepares the list of attributes required for bones according to the effect defines.
  42612. * @param attribs The current list of supported attribs
  42613. * @param mesh The mesh to prepare the bones attributes for
  42614. * @param defines The current Defines of the effect
  42615. * @param fallbacks The current efffect fallback strategy
  42616. */
  42617. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  42618. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  42619. fallbacks.addCPUSkinningFallback(0, mesh);
  42620. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  42621. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  42622. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  42623. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  42624. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  42625. }
  42626. }
  42627. };
  42628. /**
  42629. * Prepares the list of attributes required for instances according to the effect defines.
  42630. * @param attribs The current list of supported attribs
  42631. * @param defines The current Defines of the effect
  42632. */
  42633. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  42634. if (defines["INSTANCES"]) {
  42635. attribs.push("world0");
  42636. attribs.push("world1");
  42637. attribs.push("world2");
  42638. attribs.push("world3");
  42639. }
  42640. };
  42641. /**
  42642. * Binds the light shadow information to the effect for the given mesh.
  42643. * @param light The light containing the generator
  42644. * @param scene The scene the lights belongs to
  42645. * @param mesh The mesh we are binding the information to render
  42646. * @param lightIndex The light index in the effect used to render the mesh
  42647. * @param effect The effect we are binding the data to
  42648. */
  42649. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  42650. if (light.shadowEnabled && mesh.receiveShadows) {
  42651. var shadowGenerator = light.getShadowGenerator();
  42652. if (shadowGenerator) {
  42653. shadowGenerator.bindShadowLight(lightIndex, effect);
  42654. }
  42655. }
  42656. };
  42657. /**
  42658. * Binds the light information to the effect.
  42659. * @param light The light containing the generator
  42660. * @param effect The effect we are binding the data to
  42661. * @param lightIndex The light index in the effect used to render
  42662. */
  42663. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  42664. light.transferToEffect(effect, lightIndex + "");
  42665. };
  42666. /**
  42667. * Binds the lights information from the scene to the effect for the given mesh.
  42668. * @param scene The scene the lights belongs to
  42669. * @param mesh The mesh we are binding the information to render
  42670. * @param effect The effect we are binding the data to
  42671. * @param defines The generated defines for the effect
  42672. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  42673. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  42674. */
  42675. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  42676. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  42677. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  42678. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  42679. for (var i = 0; i < len; i++) {
  42680. var light = mesh._lightSources[i];
  42681. var iAsString = i.toString();
  42682. var scaledIntensity = light.getScaledIntensity();
  42683. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  42684. MaterialHelper.BindLightProperties(light, effect, i);
  42685. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  42686. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  42687. if (defines["SPECULARTERM"]) {
  42688. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  42689. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  42690. }
  42691. // Shadows
  42692. if (scene.shadowsEnabled) {
  42693. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  42694. }
  42695. light._uniformBuffer.update();
  42696. }
  42697. };
  42698. /**
  42699. * Binds the fog information from the scene to the effect for the given mesh.
  42700. * @param scene The scene the lights belongs to
  42701. * @param mesh The mesh we are binding the information to render
  42702. * @param effect The effect we are binding the data to
  42703. */
  42704. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  42705. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  42706. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  42707. effect.setColor3("vFogColor", scene.fogColor);
  42708. }
  42709. };
  42710. /**
  42711. * Binds the bones information from the mesh to the effect.
  42712. * @param mesh The mesh we are binding the information to render
  42713. * @param effect The effect we are binding the data to
  42714. */
  42715. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  42716. if (!effect || !mesh) {
  42717. return;
  42718. }
  42719. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  42720. mesh.computeBonesUsingShaders = false;
  42721. }
  42722. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  42723. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  42724. if (matrices) {
  42725. effect.setMatrices("mBones", matrices);
  42726. }
  42727. }
  42728. };
  42729. /**
  42730. * Binds the morph targets information from the mesh to the effect.
  42731. * @param abstractMesh The mesh we are binding the information to render
  42732. * @param effect The effect we are binding the data to
  42733. */
  42734. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  42735. var manager = abstractMesh.morphTargetManager;
  42736. if (!abstractMesh || !manager) {
  42737. return;
  42738. }
  42739. effect.setFloatArray("morphTargetInfluences", manager.influences);
  42740. };
  42741. /**
  42742. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  42743. * @param defines The generated defines used in the effect
  42744. * @param effect The effect we are binding the data to
  42745. * @param scene The scene we are willing to render with logarithmic scale for
  42746. */
  42747. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  42748. if (defines["LOGARITHMICDEPTH"]) {
  42749. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  42750. }
  42751. };
  42752. /**
  42753. * Binds the clip plane information from the scene to the effect.
  42754. * @param scene The scene the clip plane information are extracted from
  42755. * @param effect The effect we are binding the data to
  42756. */
  42757. MaterialHelper.BindClipPlane = function (effect, scene) {
  42758. if (scene.clipPlane) {
  42759. var clipPlane = scene.clipPlane;
  42760. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  42761. }
  42762. };
  42763. return MaterialHelper;
  42764. }());
  42765. BABYLON.MaterialHelper = MaterialHelper;
  42766. })(BABYLON || (BABYLON = {}));
  42767. //# sourceMappingURL=babylon.materialHelper.js.map
  42768. var BABYLON;
  42769. (function (BABYLON) {
  42770. var PushMaterial = /** @class */ (function (_super) {
  42771. __extends(PushMaterial, _super);
  42772. function PushMaterial(name, scene) {
  42773. var _this = _super.call(this, name, scene) || this;
  42774. _this._normalMatrix = new BABYLON.Matrix();
  42775. _this.storeEffectOnSubMeshes = true;
  42776. return _this;
  42777. }
  42778. PushMaterial.prototype.getEffect = function () {
  42779. return this._activeEffect;
  42780. };
  42781. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  42782. if (!mesh) {
  42783. return false;
  42784. }
  42785. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  42786. return true;
  42787. }
  42788. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  42789. };
  42790. /**
  42791. * Binds the given world matrix to the active effect
  42792. *
  42793. * @param world the matrix to bind
  42794. */
  42795. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  42796. this._activeEffect.setMatrix("world", world);
  42797. };
  42798. /**
  42799. * Binds the given normal matrix to the active effect
  42800. *
  42801. * @param normalMatrix the matrix to bind
  42802. */
  42803. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  42804. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  42805. };
  42806. PushMaterial.prototype.bind = function (world, mesh) {
  42807. if (!mesh) {
  42808. return;
  42809. }
  42810. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  42811. };
  42812. PushMaterial.prototype._afterBind = function (mesh, effect) {
  42813. if (effect === void 0) { effect = null; }
  42814. _super.prototype._afterBind.call(this, mesh);
  42815. this.getScene()._cachedEffect = effect;
  42816. };
  42817. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  42818. if (visibility === void 0) { visibility = 1; }
  42819. return scene.isCachedMaterialInvalid(this, effect, visibility);
  42820. };
  42821. return PushMaterial;
  42822. }(BABYLON.Material));
  42823. BABYLON.PushMaterial = PushMaterial;
  42824. })(BABYLON || (BABYLON = {}));
  42825. //# sourceMappingURL=babylon.pushMaterial.js.map
  42826. var BABYLON;
  42827. (function (BABYLON) {
  42828. /** @hidden */
  42829. var StandardMaterialDefines = /** @class */ (function (_super) {
  42830. __extends(StandardMaterialDefines, _super);
  42831. function StandardMaterialDefines() {
  42832. var _this = _super.call(this) || this;
  42833. _this.MAINUV1 = false;
  42834. _this.MAINUV2 = false;
  42835. _this.DIFFUSE = false;
  42836. _this.DIFFUSEDIRECTUV = 0;
  42837. _this.AMBIENT = false;
  42838. _this.AMBIENTDIRECTUV = 0;
  42839. _this.OPACITY = false;
  42840. _this.OPACITYDIRECTUV = 0;
  42841. _this.OPACITYRGB = false;
  42842. _this.REFLECTION = false;
  42843. _this.EMISSIVE = false;
  42844. _this.EMISSIVEDIRECTUV = 0;
  42845. _this.SPECULAR = false;
  42846. _this.SPECULARDIRECTUV = 0;
  42847. _this.BUMP = false;
  42848. _this.BUMPDIRECTUV = 0;
  42849. _this.PARALLAX = false;
  42850. _this.PARALLAXOCCLUSION = false;
  42851. _this.SPECULAROVERALPHA = false;
  42852. _this.CLIPPLANE = false;
  42853. _this.ALPHATEST = false;
  42854. _this.DEPTHPREPASS = false;
  42855. _this.ALPHAFROMDIFFUSE = false;
  42856. _this.POINTSIZE = false;
  42857. _this.FOG = false;
  42858. _this.SPECULARTERM = false;
  42859. _this.DIFFUSEFRESNEL = false;
  42860. _this.OPACITYFRESNEL = false;
  42861. _this.REFLECTIONFRESNEL = false;
  42862. _this.REFRACTIONFRESNEL = false;
  42863. _this.EMISSIVEFRESNEL = false;
  42864. _this.FRESNEL = false;
  42865. _this.NORMAL = false;
  42866. _this.UV1 = false;
  42867. _this.UV2 = false;
  42868. _this.VERTEXCOLOR = false;
  42869. _this.VERTEXALPHA = false;
  42870. _this.NUM_BONE_INFLUENCERS = 0;
  42871. _this.BonesPerMesh = 0;
  42872. _this.INSTANCES = false;
  42873. _this.GLOSSINESS = false;
  42874. _this.ROUGHNESS = false;
  42875. _this.EMISSIVEASILLUMINATION = false;
  42876. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42877. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42878. _this.LIGHTMAP = false;
  42879. _this.LIGHTMAPDIRECTUV = 0;
  42880. _this.OBJECTSPACE_NORMALMAP = false;
  42881. _this.USELIGHTMAPASSHADOWMAP = false;
  42882. _this.REFLECTIONMAP_3D = false;
  42883. _this.REFLECTIONMAP_SPHERICAL = false;
  42884. _this.REFLECTIONMAP_PLANAR = false;
  42885. _this.REFLECTIONMAP_CUBIC = false;
  42886. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42887. _this.REFLECTIONMAP_PROJECTION = false;
  42888. _this.REFLECTIONMAP_SKYBOX = false;
  42889. _this.REFLECTIONMAP_EXPLICIT = false;
  42890. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42891. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42892. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42893. _this.INVERTCUBICMAP = false;
  42894. _this.LOGARITHMICDEPTH = false;
  42895. _this.REFRACTION = false;
  42896. _this.REFRACTIONMAP_3D = false;
  42897. _this.REFLECTIONOVERALPHA = false;
  42898. _this.TWOSIDEDLIGHTING = false;
  42899. _this.SHADOWFLOAT = false;
  42900. _this.MORPHTARGETS = false;
  42901. _this.MORPHTARGETS_NORMAL = false;
  42902. _this.MORPHTARGETS_TANGENT = false;
  42903. _this.NUM_MORPH_INFLUENCERS = 0;
  42904. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42905. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42906. _this.IMAGEPROCESSING = false;
  42907. _this.VIGNETTE = false;
  42908. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42909. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42910. _this.TONEMAPPING = false;
  42911. _this.CONTRAST = false;
  42912. _this.COLORCURVES = false;
  42913. _this.COLORGRADING = false;
  42914. _this.COLORGRADING3D = false;
  42915. _this.SAMPLER3DGREENDEPTH = false;
  42916. _this.SAMPLER3DBGRMAP = false;
  42917. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42918. /**
  42919. * If the reflection texture on this material is in linear color space
  42920. * @hidden
  42921. */
  42922. _this.IS_REFLECTION_LINEAR = false;
  42923. /**
  42924. * If the refraction texture on this material is in linear color space
  42925. * @hidden
  42926. */
  42927. _this.IS_REFRACTION_LINEAR = false;
  42928. _this.EXPOSURE = false;
  42929. _this.rebuild();
  42930. return _this;
  42931. }
  42932. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42933. var modes = [
  42934. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42935. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42936. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42937. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42938. ];
  42939. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42940. var mode = modes_1[_i];
  42941. this[mode] = (mode === modeToEnable);
  42942. }
  42943. };
  42944. return StandardMaterialDefines;
  42945. }(BABYLON.MaterialDefines));
  42946. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42947. var StandardMaterial = /** @class */ (function (_super) {
  42948. __extends(StandardMaterial, _super);
  42949. function StandardMaterial(name, scene) {
  42950. var _this = _super.call(this, name, scene) || this;
  42951. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42952. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42953. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42954. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42955. _this.specularPower = 64;
  42956. _this._useAlphaFromDiffuseTexture = false;
  42957. _this._useEmissiveAsIllumination = false;
  42958. _this._linkEmissiveWithDiffuse = false;
  42959. _this._useSpecularOverAlpha = false;
  42960. _this._useReflectionOverAlpha = false;
  42961. _this._disableLighting = false;
  42962. _this._useObjectSpaceNormalMap = false;
  42963. _this._useParallax = false;
  42964. _this._useParallaxOcclusion = false;
  42965. _this.parallaxScaleBias = 0.05;
  42966. _this._roughness = 0;
  42967. _this.indexOfRefraction = 0.98;
  42968. _this.invertRefractionY = true;
  42969. /**
  42970. * Defines the alpha limits in alpha test mode
  42971. */
  42972. _this.alphaCutOff = 0.4;
  42973. _this._useLightmapAsShadowmap = false;
  42974. _this._useReflectionFresnelFromSpecular = false;
  42975. _this._useGlossinessFromSpecularMapAlpha = false;
  42976. _this._maxSimultaneousLights = 4;
  42977. /**
  42978. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42979. */
  42980. _this._invertNormalMapX = false;
  42981. /**
  42982. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42983. */
  42984. _this._invertNormalMapY = false;
  42985. /**
  42986. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42987. */
  42988. _this._twoSidedLighting = false;
  42989. _this._renderTargets = new BABYLON.SmartArray(16);
  42990. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42991. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42992. // Setup the default processing configuration to the scene.
  42993. _this._attachImageProcessingConfiguration(null);
  42994. _this.getRenderTargetTextures = function () {
  42995. _this._renderTargets.reset();
  42996. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42997. _this._renderTargets.push(_this._reflectionTexture);
  42998. }
  42999. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43000. _this._renderTargets.push(_this._refractionTexture);
  43001. }
  43002. return _this._renderTargets;
  43003. };
  43004. return _this;
  43005. }
  43006. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  43007. /**
  43008. * Gets the image processing configuration used either in this material.
  43009. */
  43010. get: function () {
  43011. return this._imageProcessingConfiguration;
  43012. },
  43013. /**
  43014. * Sets the Default image processing configuration used either in the this material.
  43015. *
  43016. * If sets to null, the scene one is in use.
  43017. */
  43018. set: function (value) {
  43019. this._attachImageProcessingConfiguration(value);
  43020. // Ensure the effect will be rebuilt.
  43021. this._markAllSubMeshesAsTexturesDirty();
  43022. },
  43023. enumerable: true,
  43024. configurable: true
  43025. });
  43026. /**
  43027. * Attaches a new image processing configuration to the Standard Material.
  43028. * @param configuration
  43029. */
  43030. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43031. var _this = this;
  43032. if (configuration === this._imageProcessingConfiguration) {
  43033. return;
  43034. }
  43035. // Detaches observer.
  43036. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43037. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43038. }
  43039. // Pick the scene configuration if needed.
  43040. if (!configuration) {
  43041. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43042. }
  43043. else {
  43044. this._imageProcessingConfiguration = configuration;
  43045. }
  43046. // Attaches observer.
  43047. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43048. _this._markAllSubMeshesAsImageProcessingDirty();
  43049. });
  43050. };
  43051. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  43052. /**
  43053. * Gets wether the color curves effect is enabled.
  43054. */
  43055. get: function () {
  43056. return this.imageProcessingConfiguration.colorCurvesEnabled;
  43057. },
  43058. /**
  43059. * Sets wether the color curves effect is enabled.
  43060. */
  43061. set: function (value) {
  43062. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  43063. },
  43064. enumerable: true,
  43065. configurable: true
  43066. });
  43067. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  43068. /**
  43069. * Gets wether the color grading effect is enabled.
  43070. */
  43071. get: function () {
  43072. return this.imageProcessingConfiguration.colorGradingEnabled;
  43073. },
  43074. /**
  43075. * Gets wether the color grading effect is enabled.
  43076. */
  43077. set: function (value) {
  43078. this.imageProcessingConfiguration.colorGradingEnabled = value;
  43079. },
  43080. enumerable: true,
  43081. configurable: true
  43082. });
  43083. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  43084. /**
  43085. * Gets wether tonemapping is enabled or not.
  43086. */
  43087. get: function () {
  43088. return this._imageProcessingConfiguration.toneMappingEnabled;
  43089. },
  43090. /**
  43091. * Sets wether tonemapping is enabled or not
  43092. */
  43093. set: function (value) {
  43094. this._imageProcessingConfiguration.toneMappingEnabled = value;
  43095. },
  43096. enumerable: true,
  43097. configurable: true
  43098. });
  43099. ;
  43100. ;
  43101. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  43102. /**
  43103. * The camera exposure used on this material.
  43104. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43105. * This corresponds to a photographic exposure.
  43106. */
  43107. get: function () {
  43108. return this._imageProcessingConfiguration.exposure;
  43109. },
  43110. /**
  43111. * The camera exposure used on this material.
  43112. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  43113. * This corresponds to a photographic exposure.
  43114. */
  43115. set: function (value) {
  43116. this._imageProcessingConfiguration.exposure = value;
  43117. },
  43118. enumerable: true,
  43119. configurable: true
  43120. });
  43121. ;
  43122. ;
  43123. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  43124. /**
  43125. * Gets The camera contrast used on this material.
  43126. */
  43127. get: function () {
  43128. return this._imageProcessingConfiguration.contrast;
  43129. },
  43130. /**
  43131. * Sets The camera contrast used on this material.
  43132. */
  43133. set: function (value) {
  43134. this._imageProcessingConfiguration.contrast = value;
  43135. },
  43136. enumerable: true,
  43137. configurable: true
  43138. });
  43139. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  43140. /**
  43141. * Gets the Color Grading 2D Lookup Texture.
  43142. */
  43143. get: function () {
  43144. return this._imageProcessingConfiguration.colorGradingTexture;
  43145. },
  43146. /**
  43147. * Sets the Color Grading 2D Lookup Texture.
  43148. */
  43149. set: function (value) {
  43150. this._imageProcessingConfiguration.colorGradingTexture = value;
  43151. },
  43152. enumerable: true,
  43153. configurable: true
  43154. });
  43155. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  43156. /**
  43157. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43158. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43159. * 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;
  43160. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43161. */
  43162. get: function () {
  43163. return this._imageProcessingConfiguration.colorCurves;
  43164. },
  43165. /**
  43166. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  43167. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  43168. * 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;
  43169. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  43170. */
  43171. set: function (value) {
  43172. this._imageProcessingConfiguration.colorCurves = value;
  43173. },
  43174. enumerable: true,
  43175. configurable: true
  43176. });
  43177. StandardMaterial.prototype.getClassName = function () {
  43178. return "StandardMaterial";
  43179. };
  43180. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  43181. get: function () {
  43182. return this._useLogarithmicDepth;
  43183. },
  43184. set: function (value) {
  43185. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43186. this._markAllSubMeshesAsMiscDirty();
  43187. },
  43188. enumerable: true,
  43189. configurable: true
  43190. });
  43191. StandardMaterial.prototype.needAlphaBlending = function () {
  43192. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  43193. };
  43194. StandardMaterial.prototype.needAlphaTesting = function () {
  43195. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  43196. };
  43197. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  43198. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  43199. };
  43200. StandardMaterial.prototype.getAlphaTestTexture = function () {
  43201. return this._diffuseTexture;
  43202. };
  43203. /**
  43204. * Child classes can use it to update shaders
  43205. */
  43206. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  43207. if (useInstances === void 0) { useInstances = false; }
  43208. if (subMesh.effect && this.isFrozen) {
  43209. if (this._wasPreviouslyReady && subMesh.effect) {
  43210. return true;
  43211. }
  43212. }
  43213. if (!subMesh._materialDefines) {
  43214. subMesh._materialDefines = new StandardMaterialDefines();
  43215. }
  43216. var scene = this.getScene();
  43217. var defines = subMesh._materialDefines;
  43218. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  43219. if (defines._renderId === scene.getRenderId()) {
  43220. return true;
  43221. }
  43222. }
  43223. var engine = scene.getEngine();
  43224. // Lights
  43225. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  43226. // Textures
  43227. if (defines._areTexturesDirty) {
  43228. defines._needUVs = false;
  43229. defines.MAINUV1 = false;
  43230. defines.MAINUV2 = false;
  43231. if (scene.texturesEnabled) {
  43232. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43233. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  43234. return false;
  43235. }
  43236. else {
  43237. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  43238. }
  43239. }
  43240. else {
  43241. defines.DIFFUSE = false;
  43242. }
  43243. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43244. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  43245. return false;
  43246. }
  43247. else {
  43248. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  43249. }
  43250. }
  43251. else {
  43252. defines.AMBIENT = false;
  43253. }
  43254. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43255. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  43256. return false;
  43257. }
  43258. else {
  43259. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  43260. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  43261. }
  43262. }
  43263. else {
  43264. defines.OPACITY = false;
  43265. }
  43266. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43267. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  43268. return false;
  43269. }
  43270. else {
  43271. defines._needNormals = true;
  43272. defines.REFLECTION = true;
  43273. defines.ROUGHNESS = (this._roughness > 0);
  43274. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  43275. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  43276. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  43277. switch (this._reflectionTexture.coordinatesMode) {
  43278. case BABYLON.Texture.EXPLICIT_MODE:
  43279. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  43280. break;
  43281. case BABYLON.Texture.PLANAR_MODE:
  43282. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  43283. break;
  43284. case BABYLON.Texture.PROJECTION_MODE:
  43285. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  43286. break;
  43287. case BABYLON.Texture.SKYBOX_MODE:
  43288. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  43289. break;
  43290. case BABYLON.Texture.SPHERICAL_MODE:
  43291. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  43292. break;
  43293. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  43294. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  43295. break;
  43296. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  43297. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  43298. break;
  43299. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  43300. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  43301. break;
  43302. case BABYLON.Texture.CUBIC_MODE:
  43303. case BABYLON.Texture.INVCUBIC_MODE:
  43304. default:
  43305. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  43306. break;
  43307. }
  43308. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  43309. }
  43310. }
  43311. else {
  43312. defines.REFLECTION = false;
  43313. }
  43314. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43315. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  43316. return false;
  43317. }
  43318. else {
  43319. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  43320. }
  43321. }
  43322. else {
  43323. defines.EMISSIVE = false;
  43324. }
  43325. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43326. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  43327. return false;
  43328. }
  43329. else {
  43330. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  43331. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  43332. }
  43333. }
  43334. else {
  43335. defines.LIGHTMAP = false;
  43336. }
  43337. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43338. if (!this._specularTexture.isReadyOrNotBlocking()) {
  43339. return false;
  43340. }
  43341. else {
  43342. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  43343. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  43344. }
  43345. }
  43346. else {
  43347. defines.SPECULAR = false;
  43348. }
  43349. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  43350. // Bump texure can not be not blocking.
  43351. if (!this._bumpTexture.isReady()) {
  43352. return false;
  43353. }
  43354. else {
  43355. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  43356. defines.PARALLAX = this._useParallax;
  43357. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  43358. }
  43359. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  43360. }
  43361. else {
  43362. defines.BUMP = false;
  43363. }
  43364. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43365. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  43366. return false;
  43367. }
  43368. else {
  43369. defines._needUVs = true;
  43370. defines.REFRACTION = true;
  43371. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  43372. }
  43373. }
  43374. else {
  43375. defines.REFRACTION = false;
  43376. }
  43377. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  43378. }
  43379. else {
  43380. defines.DIFFUSE = false;
  43381. defines.AMBIENT = false;
  43382. defines.OPACITY = false;
  43383. defines.REFLECTION = false;
  43384. defines.EMISSIVE = false;
  43385. defines.LIGHTMAP = false;
  43386. defines.BUMP = false;
  43387. defines.REFRACTION = false;
  43388. }
  43389. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  43390. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  43391. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  43392. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  43393. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  43394. }
  43395. if (defines._areImageProcessingDirty) {
  43396. if (!this._imageProcessingConfiguration.isReady()) {
  43397. return false;
  43398. }
  43399. this._imageProcessingConfiguration.prepareDefines(defines);
  43400. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  43401. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  43402. }
  43403. if (defines._areFresnelDirty) {
  43404. if (StandardMaterial.FresnelEnabled) {
  43405. // Fresnel
  43406. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  43407. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  43408. this._reflectionFresnelParameters) {
  43409. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  43410. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  43411. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  43412. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  43413. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  43414. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  43415. defines._needNormals = true;
  43416. defines.FRESNEL = true;
  43417. }
  43418. }
  43419. else {
  43420. defines.FRESNEL = false;
  43421. }
  43422. }
  43423. // Misc.
  43424. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  43425. // Attribs
  43426. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  43427. // Values that need to be evaluated on every frame
  43428. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  43429. // Get correct effect
  43430. if (defines.isDirty) {
  43431. defines.markAsProcessed();
  43432. scene.resetCachedMaterial();
  43433. // Fallbacks
  43434. var fallbacks = new BABYLON.EffectFallbacks();
  43435. if (defines.REFLECTION) {
  43436. fallbacks.addFallback(0, "REFLECTION");
  43437. }
  43438. if (defines.SPECULAR) {
  43439. fallbacks.addFallback(0, "SPECULAR");
  43440. }
  43441. if (defines.BUMP) {
  43442. fallbacks.addFallback(0, "BUMP");
  43443. }
  43444. if (defines.PARALLAX) {
  43445. fallbacks.addFallback(1, "PARALLAX");
  43446. }
  43447. if (defines.PARALLAXOCCLUSION) {
  43448. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  43449. }
  43450. if (defines.SPECULAROVERALPHA) {
  43451. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  43452. }
  43453. if (defines.FOG) {
  43454. fallbacks.addFallback(1, "FOG");
  43455. }
  43456. if (defines.POINTSIZE) {
  43457. fallbacks.addFallback(0, "POINTSIZE");
  43458. }
  43459. if (defines.LOGARITHMICDEPTH) {
  43460. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  43461. }
  43462. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  43463. if (defines.SPECULARTERM) {
  43464. fallbacks.addFallback(0, "SPECULARTERM");
  43465. }
  43466. if (defines.DIFFUSEFRESNEL) {
  43467. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  43468. }
  43469. if (defines.OPACITYFRESNEL) {
  43470. fallbacks.addFallback(2, "OPACITYFRESNEL");
  43471. }
  43472. if (defines.REFLECTIONFRESNEL) {
  43473. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  43474. }
  43475. if (defines.EMISSIVEFRESNEL) {
  43476. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  43477. }
  43478. if (defines.FRESNEL) {
  43479. fallbacks.addFallback(4, "FRESNEL");
  43480. }
  43481. //Attributes
  43482. var attribs = [BABYLON.VertexBuffer.PositionKind];
  43483. if (defines.NORMAL) {
  43484. attribs.push(BABYLON.VertexBuffer.NormalKind);
  43485. }
  43486. if (defines.UV1) {
  43487. attribs.push(BABYLON.VertexBuffer.UVKind);
  43488. }
  43489. if (defines.UV2) {
  43490. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  43491. }
  43492. if (defines.VERTEXCOLOR) {
  43493. attribs.push(BABYLON.VertexBuffer.ColorKind);
  43494. }
  43495. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  43496. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  43497. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  43498. var shaderName = "default";
  43499. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  43500. "vFogInfos", "vFogColor", "pointSize",
  43501. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  43502. "mBones",
  43503. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  43504. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  43505. "vReflectionPosition", "vReflectionSize",
  43506. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  43507. ];
  43508. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  43509. var uniformBuffers = ["Material", "Scene"];
  43510. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  43511. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  43512. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  43513. uniformsNames: uniforms,
  43514. uniformBuffersNames: uniformBuffers,
  43515. samplers: samplers,
  43516. defines: defines,
  43517. maxSimultaneousLights: this._maxSimultaneousLights
  43518. });
  43519. if (this.customShaderNameResolve) {
  43520. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  43521. }
  43522. var join = defines.toString();
  43523. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  43524. attributes: attribs,
  43525. uniformsNames: uniforms,
  43526. uniformBuffersNames: uniformBuffers,
  43527. samplers: samplers,
  43528. defines: join,
  43529. fallbacks: fallbacks,
  43530. onCompiled: this.onCompiled,
  43531. onError: this.onError,
  43532. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  43533. }, engine), defines);
  43534. this.buildUniformLayout();
  43535. }
  43536. if (!subMesh.effect || !subMesh.effect.isReady()) {
  43537. return false;
  43538. }
  43539. defines._renderId = scene.getRenderId();
  43540. this._wasPreviouslyReady = true;
  43541. return true;
  43542. };
  43543. StandardMaterial.prototype.buildUniformLayout = function () {
  43544. // Order is important !
  43545. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  43546. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  43547. this._uniformBuffer.addUniform("opacityParts", 4);
  43548. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  43549. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  43550. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  43551. this._uniformBuffer.addUniform("refractionRightColor", 4);
  43552. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  43553. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  43554. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  43555. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  43556. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  43557. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  43558. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  43559. this._uniformBuffer.addUniform("vReflectionSize", 3);
  43560. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  43561. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  43562. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  43563. this._uniformBuffer.addUniform("vBumpInfos", 3);
  43564. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  43565. this._uniformBuffer.addUniform("ambientMatrix", 16);
  43566. this._uniformBuffer.addUniform("opacityMatrix", 16);
  43567. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  43568. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  43569. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  43570. this._uniformBuffer.addUniform("specularMatrix", 16);
  43571. this._uniformBuffer.addUniform("bumpMatrix", 16);
  43572. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  43573. this._uniformBuffer.addUniform("refractionMatrix", 16);
  43574. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  43575. this._uniformBuffer.addUniform("vSpecularColor", 4);
  43576. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  43577. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  43578. this._uniformBuffer.addUniform("pointSize", 1);
  43579. this._uniformBuffer.create();
  43580. };
  43581. StandardMaterial.prototype.unbind = function () {
  43582. if (this._activeEffect) {
  43583. var needFlag = false;
  43584. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  43585. this._activeEffect.setTexture("reflection2DSampler", null);
  43586. needFlag = true;
  43587. }
  43588. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  43589. this._activeEffect.setTexture("refraction2DSampler", null);
  43590. needFlag = true;
  43591. }
  43592. if (needFlag) {
  43593. this._markAllSubMeshesAsTexturesDirty();
  43594. }
  43595. }
  43596. _super.prototype.unbind.call(this);
  43597. };
  43598. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  43599. var scene = this.getScene();
  43600. var defines = subMesh._materialDefines;
  43601. if (!defines) {
  43602. return;
  43603. }
  43604. var effect = subMesh.effect;
  43605. if (!effect) {
  43606. return;
  43607. }
  43608. this._activeEffect = effect;
  43609. // Matrices
  43610. this.bindOnlyWorldMatrix(world);
  43611. // Normal Matrix
  43612. if (defines.OBJECTSPACE_NORMALMAP) {
  43613. world.toNormalMatrix(this._normalMatrix);
  43614. this.bindOnlyNormalMatrix(this._normalMatrix);
  43615. }
  43616. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  43617. // Bones
  43618. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  43619. if (mustRebind) {
  43620. this._uniformBuffer.bindToEffect(effect, "Material");
  43621. this.bindViewProjection(effect);
  43622. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  43623. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  43624. // Fresnel
  43625. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  43626. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  43627. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  43628. }
  43629. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  43630. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  43631. }
  43632. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  43633. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  43634. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  43635. }
  43636. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  43637. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  43638. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  43639. }
  43640. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  43641. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  43642. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  43643. }
  43644. }
  43645. // Textures
  43646. if (scene.texturesEnabled) {
  43647. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43648. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  43649. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  43650. if (this._diffuseTexture.hasAlpha) {
  43651. effect.setFloat("alphaCutOff", this.alphaCutOff);
  43652. }
  43653. }
  43654. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43655. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  43656. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  43657. }
  43658. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43659. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  43660. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  43661. }
  43662. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43663. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  43664. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  43665. if (this._reflectionTexture.boundingBoxSize) {
  43666. var cubeTexture = this._reflectionTexture;
  43667. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  43668. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  43669. }
  43670. }
  43671. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43672. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  43673. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  43674. }
  43675. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43676. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  43677. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  43678. }
  43679. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43680. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  43681. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  43682. }
  43683. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43684. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  43685. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  43686. if (scene._mirroredCameraPosition) {
  43687. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  43688. }
  43689. else {
  43690. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  43691. }
  43692. }
  43693. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43694. var depth = 1.0;
  43695. if (!this._refractionTexture.isCube) {
  43696. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  43697. if (this._refractionTexture.depth) {
  43698. depth = this._refractionTexture.depth;
  43699. }
  43700. }
  43701. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  43702. }
  43703. }
  43704. // Point size
  43705. if (this.pointsCloud) {
  43706. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  43707. }
  43708. if (defines.SPECULARTERM) {
  43709. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  43710. }
  43711. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  43712. // Diffuse
  43713. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  43714. }
  43715. // Textures
  43716. if (scene.texturesEnabled) {
  43717. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  43718. effect.setTexture("diffuseSampler", this._diffuseTexture);
  43719. }
  43720. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  43721. effect.setTexture("ambientSampler", this._ambientTexture);
  43722. }
  43723. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  43724. effect.setTexture("opacitySampler", this._opacityTexture);
  43725. }
  43726. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  43727. if (this._reflectionTexture.isCube) {
  43728. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  43729. }
  43730. else {
  43731. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  43732. }
  43733. }
  43734. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  43735. effect.setTexture("emissiveSampler", this._emissiveTexture);
  43736. }
  43737. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  43738. effect.setTexture("lightmapSampler", this._lightmapTexture);
  43739. }
  43740. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  43741. effect.setTexture("specularSampler", this._specularTexture);
  43742. }
  43743. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  43744. effect.setTexture("bumpSampler", this._bumpTexture);
  43745. }
  43746. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  43747. var depth = 1.0;
  43748. if (this._refractionTexture.isCube) {
  43749. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  43750. }
  43751. else {
  43752. effect.setTexture("refraction2DSampler", this._refractionTexture);
  43753. }
  43754. }
  43755. }
  43756. // Clip plane
  43757. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  43758. // Colors
  43759. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  43760. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  43761. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  43762. }
  43763. if (mustRebind || !this.isFrozen) {
  43764. // Lights
  43765. if (scene.lightsEnabled && !this._disableLighting) {
  43766. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  43767. }
  43768. // View
  43769. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  43770. this.bindView(effect);
  43771. }
  43772. // Fog
  43773. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  43774. // Morph targets
  43775. if (defines.NUM_MORPH_INFLUENCERS) {
  43776. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  43777. }
  43778. // Log. depth
  43779. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  43780. // image processing
  43781. if (!this._imageProcessingConfiguration.applyByPostProcess) {
  43782. this._imageProcessingConfiguration.bind(this._activeEffect);
  43783. }
  43784. }
  43785. this._uniformBuffer.update();
  43786. this._afterBind(mesh, this._activeEffect);
  43787. };
  43788. StandardMaterial.prototype.getAnimatables = function () {
  43789. var results = [];
  43790. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  43791. results.push(this._diffuseTexture);
  43792. }
  43793. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  43794. results.push(this._ambientTexture);
  43795. }
  43796. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  43797. results.push(this._opacityTexture);
  43798. }
  43799. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  43800. results.push(this._reflectionTexture);
  43801. }
  43802. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  43803. results.push(this._emissiveTexture);
  43804. }
  43805. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  43806. results.push(this._specularTexture);
  43807. }
  43808. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  43809. results.push(this._bumpTexture);
  43810. }
  43811. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  43812. results.push(this._lightmapTexture);
  43813. }
  43814. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  43815. results.push(this._refractionTexture);
  43816. }
  43817. return results;
  43818. };
  43819. StandardMaterial.prototype.getActiveTextures = function () {
  43820. var activeTextures = _super.prototype.getActiveTextures.call(this);
  43821. if (this._diffuseTexture) {
  43822. activeTextures.push(this._diffuseTexture);
  43823. }
  43824. if (this._ambientTexture) {
  43825. activeTextures.push(this._ambientTexture);
  43826. }
  43827. if (this._opacityTexture) {
  43828. activeTextures.push(this._opacityTexture);
  43829. }
  43830. if (this._reflectionTexture) {
  43831. activeTextures.push(this._reflectionTexture);
  43832. }
  43833. if (this._emissiveTexture) {
  43834. activeTextures.push(this._emissiveTexture);
  43835. }
  43836. if (this._specularTexture) {
  43837. activeTextures.push(this._specularTexture);
  43838. }
  43839. if (this._bumpTexture) {
  43840. activeTextures.push(this._bumpTexture);
  43841. }
  43842. if (this._lightmapTexture) {
  43843. activeTextures.push(this._lightmapTexture);
  43844. }
  43845. if (this._refractionTexture) {
  43846. activeTextures.push(this._refractionTexture);
  43847. }
  43848. return activeTextures;
  43849. };
  43850. StandardMaterial.prototype.hasTexture = function (texture) {
  43851. if (_super.prototype.hasTexture.call(this, texture)) {
  43852. return true;
  43853. }
  43854. if (this._diffuseTexture === texture) {
  43855. return true;
  43856. }
  43857. if (this._ambientTexture === texture) {
  43858. return true;
  43859. }
  43860. if (this._opacityTexture === texture) {
  43861. return true;
  43862. }
  43863. if (this._reflectionTexture === texture) {
  43864. return true;
  43865. }
  43866. if (this._emissiveTexture === texture) {
  43867. return true;
  43868. }
  43869. if (this._specularTexture === texture) {
  43870. return true;
  43871. }
  43872. if (this._bumpTexture === texture) {
  43873. return true;
  43874. }
  43875. if (this._lightmapTexture === texture) {
  43876. return true;
  43877. }
  43878. if (this._refractionTexture === texture) {
  43879. return true;
  43880. }
  43881. return false;
  43882. };
  43883. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43884. if (forceDisposeTextures) {
  43885. if (this._diffuseTexture) {
  43886. this._diffuseTexture.dispose();
  43887. }
  43888. if (this._ambientTexture) {
  43889. this._ambientTexture.dispose();
  43890. }
  43891. if (this._opacityTexture) {
  43892. this._opacityTexture.dispose();
  43893. }
  43894. if (this._reflectionTexture) {
  43895. this._reflectionTexture.dispose();
  43896. }
  43897. if (this._emissiveTexture) {
  43898. this._emissiveTexture.dispose();
  43899. }
  43900. if (this._specularTexture) {
  43901. this._specularTexture.dispose();
  43902. }
  43903. if (this._bumpTexture) {
  43904. this._bumpTexture.dispose();
  43905. }
  43906. if (this._lightmapTexture) {
  43907. this._lightmapTexture.dispose();
  43908. }
  43909. if (this._refractionTexture) {
  43910. this._refractionTexture.dispose();
  43911. }
  43912. }
  43913. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43914. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43915. }
  43916. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43917. };
  43918. StandardMaterial.prototype.clone = function (name) {
  43919. var _this = this;
  43920. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43921. result.name = name;
  43922. result.id = name;
  43923. return result;
  43924. };
  43925. StandardMaterial.prototype.serialize = function () {
  43926. return BABYLON.SerializationHelper.Serialize(this);
  43927. };
  43928. // Statics
  43929. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43930. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43931. };
  43932. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43933. get: function () {
  43934. return StandardMaterial._DiffuseTextureEnabled;
  43935. },
  43936. set: function (value) {
  43937. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43938. return;
  43939. }
  43940. StandardMaterial._DiffuseTextureEnabled = value;
  43941. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43942. },
  43943. enumerable: true,
  43944. configurable: true
  43945. });
  43946. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43947. get: function () {
  43948. return StandardMaterial._AmbientTextureEnabled;
  43949. },
  43950. set: function (value) {
  43951. if (StandardMaterial._AmbientTextureEnabled === value) {
  43952. return;
  43953. }
  43954. StandardMaterial._AmbientTextureEnabled = value;
  43955. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43956. },
  43957. enumerable: true,
  43958. configurable: true
  43959. });
  43960. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43961. get: function () {
  43962. return StandardMaterial._OpacityTextureEnabled;
  43963. },
  43964. set: function (value) {
  43965. if (StandardMaterial._OpacityTextureEnabled === value) {
  43966. return;
  43967. }
  43968. StandardMaterial._OpacityTextureEnabled = value;
  43969. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43970. },
  43971. enumerable: true,
  43972. configurable: true
  43973. });
  43974. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43975. get: function () {
  43976. return StandardMaterial._ReflectionTextureEnabled;
  43977. },
  43978. set: function (value) {
  43979. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43980. return;
  43981. }
  43982. StandardMaterial._ReflectionTextureEnabled = value;
  43983. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43984. },
  43985. enumerable: true,
  43986. configurable: true
  43987. });
  43988. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43989. get: function () {
  43990. return StandardMaterial._EmissiveTextureEnabled;
  43991. },
  43992. set: function (value) {
  43993. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43994. return;
  43995. }
  43996. StandardMaterial._EmissiveTextureEnabled = value;
  43997. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43998. },
  43999. enumerable: true,
  44000. configurable: true
  44001. });
  44002. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  44003. get: function () {
  44004. return StandardMaterial._SpecularTextureEnabled;
  44005. },
  44006. set: function (value) {
  44007. if (StandardMaterial._SpecularTextureEnabled === value) {
  44008. return;
  44009. }
  44010. StandardMaterial._SpecularTextureEnabled = value;
  44011. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44012. },
  44013. enumerable: true,
  44014. configurable: true
  44015. });
  44016. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  44017. get: function () {
  44018. return StandardMaterial._BumpTextureEnabled;
  44019. },
  44020. set: function (value) {
  44021. if (StandardMaterial._BumpTextureEnabled === value) {
  44022. return;
  44023. }
  44024. StandardMaterial._BumpTextureEnabled = value;
  44025. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44026. },
  44027. enumerable: true,
  44028. configurable: true
  44029. });
  44030. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  44031. get: function () {
  44032. return StandardMaterial._LightmapTextureEnabled;
  44033. },
  44034. set: function (value) {
  44035. if (StandardMaterial._LightmapTextureEnabled === value) {
  44036. return;
  44037. }
  44038. StandardMaterial._LightmapTextureEnabled = value;
  44039. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44040. },
  44041. enumerable: true,
  44042. configurable: true
  44043. });
  44044. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  44045. get: function () {
  44046. return StandardMaterial._RefractionTextureEnabled;
  44047. },
  44048. set: function (value) {
  44049. if (StandardMaterial._RefractionTextureEnabled === value) {
  44050. return;
  44051. }
  44052. StandardMaterial._RefractionTextureEnabled = value;
  44053. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44054. },
  44055. enumerable: true,
  44056. configurable: true
  44057. });
  44058. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  44059. get: function () {
  44060. return StandardMaterial._ColorGradingTextureEnabled;
  44061. },
  44062. set: function (value) {
  44063. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  44064. return;
  44065. }
  44066. StandardMaterial._ColorGradingTextureEnabled = value;
  44067. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  44068. },
  44069. enumerable: true,
  44070. configurable: true
  44071. });
  44072. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  44073. get: function () {
  44074. return StandardMaterial._FresnelEnabled;
  44075. },
  44076. set: function (value) {
  44077. if (StandardMaterial._FresnelEnabled === value) {
  44078. return;
  44079. }
  44080. StandardMaterial._FresnelEnabled = value;
  44081. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  44082. },
  44083. enumerable: true,
  44084. configurable: true
  44085. });
  44086. // Flags used to enable or disable a type of texture for all Standard Materials
  44087. StandardMaterial._DiffuseTextureEnabled = true;
  44088. StandardMaterial._AmbientTextureEnabled = true;
  44089. StandardMaterial._OpacityTextureEnabled = true;
  44090. StandardMaterial._ReflectionTextureEnabled = true;
  44091. StandardMaterial._EmissiveTextureEnabled = true;
  44092. StandardMaterial._SpecularTextureEnabled = true;
  44093. StandardMaterial._BumpTextureEnabled = true;
  44094. StandardMaterial._LightmapTextureEnabled = true;
  44095. StandardMaterial._RefractionTextureEnabled = true;
  44096. StandardMaterial._ColorGradingTextureEnabled = true;
  44097. StandardMaterial._FresnelEnabled = true;
  44098. __decorate([
  44099. BABYLON.serializeAsTexture("diffuseTexture")
  44100. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  44101. __decorate([
  44102. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44103. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  44104. __decorate([
  44105. BABYLON.serializeAsTexture("ambientTexture")
  44106. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  44107. __decorate([
  44108. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44109. ], StandardMaterial.prototype, "ambientTexture", void 0);
  44110. __decorate([
  44111. BABYLON.serializeAsTexture("opacityTexture")
  44112. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  44113. __decorate([
  44114. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  44115. ], StandardMaterial.prototype, "opacityTexture", void 0);
  44116. __decorate([
  44117. BABYLON.serializeAsTexture("reflectionTexture")
  44118. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  44119. __decorate([
  44120. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44121. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  44122. __decorate([
  44123. BABYLON.serializeAsTexture("emissiveTexture")
  44124. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  44125. __decorate([
  44126. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44127. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  44128. __decorate([
  44129. BABYLON.serializeAsTexture("specularTexture")
  44130. ], StandardMaterial.prototype, "_specularTexture", void 0);
  44131. __decorate([
  44132. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44133. ], StandardMaterial.prototype, "specularTexture", void 0);
  44134. __decorate([
  44135. BABYLON.serializeAsTexture("bumpTexture")
  44136. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  44137. __decorate([
  44138. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44139. ], StandardMaterial.prototype, "bumpTexture", void 0);
  44140. __decorate([
  44141. BABYLON.serializeAsTexture("lightmapTexture")
  44142. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  44143. __decorate([
  44144. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44145. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  44146. __decorate([
  44147. BABYLON.serializeAsTexture("refractionTexture")
  44148. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  44149. __decorate([
  44150. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44151. ], StandardMaterial.prototype, "refractionTexture", void 0);
  44152. __decorate([
  44153. BABYLON.serializeAsColor3("ambient")
  44154. ], StandardMaterial.prototype, "ambientColor", void 0);
  44155. __decorate([
  44156. BABYLON.serializeAsColor3("diffuse")
  44157. ], StandardMaterial.prototype, "diffuseColor", void 0);
  44158. __decorate([
  44159. BABYLON.serializeAsColor3("specular")
  44160. ], StandardMaterial.prototype, "specularColor", void 0);
  44161. __decorate([
  44162. BABYLON.serializeAsColor3("emissive")
  44163. ], StandardMaterial.prototype, "emissiveColor", void 0);
  44164. __decorate([
  44165. BABYLON.serialize()
  44166. ], StandardMaterial.prototype, "specularPower", void 0);
  44167. __decorate([
  44168. BABYLON.serialize("useAlphaFromDiffuseTexture")
  44169. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  44170. __decorate([
  44171. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44172. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  44173. __decorate([
  44174. BABYLON.serialize("useEmissiveAsIllumination")
  44175. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  44176. __decorate([
  44177. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44178. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  44179. __decorate([
  44180. BABYLON.serialize("linkEmissiveWithDiffuse")
  44181. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  44182. __decorate([
  44183. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44184. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  44185. __decorate([
  44186. BABYLON.serialize("useSpecularOverAlpha")
  44187. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  44188. __decorate([
  44189. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44190. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  44191. __decorate([
  44192. BABYLON.serialize("useReflectionOverAlpha")
  44193. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  44194. __decorate([
  44195. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44196. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  44197. __decorate([
  44198. BABYLON.serialize("disableLighting")
  44199. ], StandardMaterial.prototype, "_disableLighting", void 0);
  44200. __decorate([
  44201. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44202. ], StandardMaterial.prototype, "disableLighting", void 0);
  44203. __decorate([
  44204. BABYLON.serialize("useObjectSpaceNormalMap")
  44205. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  44206. __decorate([
  44207. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44208. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  44209. __decorate([
  44210. BABYLON.serialize("useParallax")
  44211. ], StandardMaterial.prototype, "_useParallax", void 0);
  44212. __decorate([
  44213. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44214. ], StandardMaterial.prototype, "useParallax", void 0);
  44215. __decorate([
  44216. BABYLON.serialize("useParallaxOcclusion")
  44217. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  44218. __decorate([
  44219. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44220. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  44221. __decorate([
  44222. BABYLON.serialize()
  44223. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  44224. __decorate([
  44225. BABYLON.serialize("roughness")
  44226. ], StandardMaterial.prototype, "_roughness", void 0);
  44227. __decorate([
  44228. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44229. ], StandardMaterial.prototype, "roughness", void 0);
  44230. __decorate([
  44231. BABYLON.serialize()
  44232. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  44233. __decorate([
  44234. BABYLON.serialize()
  44235. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  44236. __decorate([
  44237. BABYLON.serialize()
  44238. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  44239. __decorate([
  44240. BABYLON.serialize("useLightmapAsShadowmap")
  44241. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  44242. __decorate([
  44243. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44244. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  44245. __decorate([
  44246. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  44247. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  44248. __decorate([
  44249. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44250. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  44251. __decorate([
  44252. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  44253. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  44254. __decorate([
  44255. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  44256. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  44257. __decorate([
  44258. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  44259. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  44260. __decorate([
  44261. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44262. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  44263. __decorate([
  44264. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  44265. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  44266. __decorate([
  44267. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44268. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  44269. __decorate([
  44270. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  44271. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  44272. __decorate([
  44273. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44274. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  44275. __decorate([
  44276. BABYLON.serialize("useReflectionFresnelFromSpecular")
  44277. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  44278. __decorate([
  44279. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  44280. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  44281. __decorate([
  44282. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  44283. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  44284. __decorate([
  44285. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44286. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  44287. __decorate([
  44288. BABYLON.serialize("maxSimultaneousLights")
  44289. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  44290. __decorate([
  44291. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  44292. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  44293. __decorate([
  44294. BABYLON.serialize("invertNormalMapX")
  44295. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  44296. __decorate([
  44297. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44298. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  44299. __decorate([
  44300. BABYLON.serialize("invertNormalMapY")
  44301. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  44302. __decorate([
  44303. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44304. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  44305. __decorate([
  44306. BABYLON.serialize("twoSidedLighting")
  44307. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  44308. __decorate([
  44309. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  44310. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  44311. __decorate([
  44312. BABYLON.serialize()
  44313. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  44314. return StandardMaterial;
  44315. }(BABYLON.PushMaterial));
  44316. BABYLON.StandardMaterial = StandardMaterial;
  44317. })(BABYLON || (BABYLON = {}));
  44318. //# sourceMappingURL=babylon.standardMaterial.js.map
  44319. var BABYLON;
  44320. (function (BABYLON) {
  44321. /**
  44322. * Manages the defines for the PBR Material.
  44323. * @hiddenChildren
  44324. */
  44325. var PBRMaterialDefines = /** @class */ (function (_super) {
  44326. __extends(PBRMaterialDefines, _super);
  44327. /**
  44328. * Initializes the PBR Material defines.
  44329. */
  44330. function PBRMaterialDefines() {
  44331. var _this = _super.call(this) || this;
  44332. _this.PBR = true;
  44333. _this.MAINUV1 = false;
  44334. _this.MAINUV2 = false;
  44335. _this.UV1 = false;
  44336. _this.UV2 = false;
  44337. _this.ALBEDO = false;
  44338. _this.ALBEDODIRECTUV = 0;
  44339. _this.VERTEXCOLOR = false;
  44340. _this.AMBIENT = false;
  44341. _this.AMBIENTDIRECTUV = 0;
  44342. _this.AMBIENTINGRAYSCALE = false;
  44343. _this.OPACITY = false;
  44344. _this.VERTEXALPHA = false;
  44345. _this.OPACITYDIRECTUV = 0;
  44346. _this.OPACITYRGB = false;
  44347. _this.ALPHATEST = false;
  44348. _this.DEPTHPREPASS = false;
  44349. _this.ALPHABLEND = false;
  44350. _this.ALPHAFROMALBEDO = false;
  44351. _this.ALPHATESTVALUE = "0.5";
  44352. _this.SPECULAROVERALPHA = false;
  44353. _this.RADIANCEOVERALPHA = false;
  44354. _this.ALPHAFRESNEL = false;
  44355. _this.LINEARALPHAFRESNEL = false;
  44356. _this.PREMULTIPLYALPHA = false;
  44357. _this.EMISSIVE = false;
  44358. _this.EMISSIVEDIRECTUV = 0;
  44359. _this.REFLECTIVITY = false;
  44360. _this.REFLECTIVITYDIRECTUV = 0;
  44361. _this.SPECULARTERM = false;
  44362. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  44363. _this.MICROSURFACEAUTOMATIC = false;
  44364. _this.LODBASEDMICROSFURACE = false;
  44365. _this.MICROSURFACEMAP = false;
  44366. _this.MICROSURFACEMAPDIRECTUV = 0;
  44367. _this.METALLICWORKFLOW = false;
  44368. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  44369. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  44370. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  44371. _this.AOSTOREINMETALMAPRED = false;
  44372. _this.ENVIRONMENTBRDF = false;
  44373. _this.NORMAL = false;
  44374. _this.TANGENT = false;
  44375. _this.BUMP = false;
  44376. _this.BUMPDIRECTUV = 0;
  44377. _this.OBJECTSPACE_NORMALMAP = false;
  44378. _this.PARALLAX = false;
  44379. _this.PARALLAXOCCLUSION = false;
  44380. _this.NORMALXYSCALE = true;
  44381. _this.LIGHTMAP = false;
  44382. _this.LIGHTMAPDIRECTUV = 0;
  44383. _this.USELIGHTMAPASSHADOWMAP = false;
  44384. _this.GAMMALIGHTMAP = false;
  44385. _this.REFLECTION = false;
  44386. _this.REFLECTIONMAP_3D = false;
  44387. _this.REFLECTIONMAP_SPHERICAL = false;
  44388. _this.REFLECTIONMAP_PLANAR = false;
  44389. _this.REFLECTIONMAP_CUBIC = false;
  44390. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44391. _this.REFLECTIONMAP_PROJECTION = false;
  44392. _this.REFLECTIONMAP_SKYBOX = false;
  44393. _this.REFLECTIONMAP_EXPLICIT = false;
  44394. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44395. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44396. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44397. _this.INVERTCUBICMAP = false;
  44398. _this.USESPHERICALFROMREFLECTIONMAP = false;
  44399. _this.USESPHERICALINVERTEX = false;
  44400. _this.REFLECTIONMAP_OPPOSITEZ = false;
  44401. _this.LODINREFLECTIONALPHA = false;
  44402. _this.GAMMAREFLECTION = false;
  44403. _this.RADIANCEOCCLUSION = false;
  44404. _this.HORIZONOCCLUSION = false;
  44405. _this.REFRACTION = false;
  44406. _this.REFRACTIONMAP_3D = false;
  44407. _this.REFRACTIONMAP_OPPOSITEZ = false;
  44408. _this.LODINREFRACTIONALPHA = false;
  44409. _this.GAMMAREFRACTION = false;
  44410. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  44411. _this.INSTANCES = false;
  44412. _this.NUM_BONE_INFLUENCERS = 0;
  44413. _this.BonesPerMesh = 0;
  44414. _this.NONUNIFORMSCALING = false;
  44415. _this.MORPHTARGETS = false;
  44416. _this.MORPHTARGETS_NORMAL = false;
  44417. _this.MORPHTARGETS_TANGENT = false;
  44418. _this.NUM_MORPH_INFLUENCERS = 0;
  44419. _this.IMAGEPROCESSING = false;
  44420. _this.VIGNETTE = false;
  44421. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  44422. _this.VIGNETTEBLENDMODEOPAQUE = false;
  44423. _this.TONEMAPPING = false;
  44424. _this.CONTRAST = false;
  44425. _this.COLORCURVES = false;
  44426. _this.COLORGRADING = false;
  44427. _this.COLORGRADING3D = false;
  44428. _this.SAMPLER3DGREENDEPTH = false;
  44429. _this.SAMPLER3DBGRMAP = false;
  44430. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  44431. _this.EXPOSURE = false;
  44432. _this.USEPHYSICALLIGHTFALLOFF = false;
  44433. _this.TWOSIDEDLIGHTING = false;
  44434. _this.SHADOWFLOAT = false;
  44435. _this.CLIPPLANE = false;
  44436. _this.POINTSIZE = false;
  44437. _this.FOG = false;
  44438. _this.LOGARITHMICDEPTH = false;
  44439. _this.FORCENORMALFORWARD = false;
  44440. _this.SPECULARAA = false;
  44441. _this.UNLIT = false;
  44442. _this.rebuild();
  44443. return _this;
  44444. }
  44445. /**
  44446. * Resets the PBR Material defines.
  44447. */
  44448. PBRMaterialDefines.prototype.reset = function () {
  44449. _super.prototype.reset.call(this);
  44450. this.ALPHATESTVALUE = "0.5";
  44451. this.PBR = true;
  44452. };
  44453. return PBRMaterialDefines;
  44454. }(BABYLON.MaterialDefines));
  44455. /**
  44456. * The Physically based material base class of BJS.
  44457. *
  44458. * This offers the main features of a standard PBR material.
  44459. * For more information, please refer to the documentation :
  44460. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  44461. */
  44462. var PBRBaseMaterial = /** @class */ (function (_super) {
  44463. __extends(PBRBaseMaterial, _super);
  44464. /**
  44465. * Instantiates a new PBRMaterial instance.
  44466. *
  44467. * @param name The material name
  44468. * @param scene The scene the material will be use in.
  44469. */
  44470. function PBRBaseMaterial(name, scene) {
  44471. var _this = _super.call(this, name, scene) || this;
  44472. /**
  44473. * Intensity of the direct lights e.g. the four lights available in your scene.
  44474. * This impacts both the direct diffuse and specular highlights.
  44475. */
  44476. _this._directIntensity = 1.0;
  44477. /**
  44478. * Intensity of the emissive part of the material.
  44479. * This helps controlling the emissive effect without modifying the emissive color.
  44480. */
  44481. _this._emissiveIntensity = 1.0;
  44482. /**
  44483. * Intensity of the environment e.g. how much the environment will light the object
  44484. * either through harmonics for rough material or through the refelction for shiny ones.
  44485. */
  44486. _this._environmentIntensity = 1.0;
  44487. /**
  44488. * This is a special control allowing the reduction of the specular highlights coming from the
  44489. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  44490. */
  44491. _this._specularIntensity = 1.0;
  44492. /**
  44493. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  44494. */
  44495. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  44496. /**
  44497. * Debug Control allowing disabling the bump map on this material.
  44498. */
  44499. _this._disableBumpMap = false;
  44500. /**
  44501. * AKA Occlusion Texture Intensity in other nomenclature.
  44502. */
  44503. _this._ambientTextureStrength = 1.0;
  44504. /**
  44505. * The color of a material in ambient lighting.
  44506. */
  44507. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  44508. /**
  44509. * AKA Diffuse Color in other nomenclature.
  44510. */
  44511. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  44512. /**
  44513. * AKA Specular Color in other nomenclature.
  44514. */
  44515. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  44516. /**
  44517. * The color applied when light is reflected from a material.
  44518. */
  44519. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  44520. /**
  44521. * The color applied when light is emitted from a material.
  44522. */
  44523. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  44524. /**
  44525. * AKA Glossiness in other nomenclature.
  44526. */
  44527. _this._microSurface = 0.9;
  44528. /**
  44529. * source material index of refraction (IOR)' / 'destination material IOR.
  44530. */
  44531. _this._indexOfRefraction = 0.66;
  44532. /**
  44533. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  44534. */
  44535. _this._invertRefractionY = false;
  44536. /**
  44537. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  44538. * Materials half opaque for instance using refraction could benefit from this control.
  44539. */
  44540. _this._linkRefractionWithTransparency = false;
  44541. /**
  44542. * Specifies that the material will use the light map as a show map.
  44543. */
  44544. _this._useLightmapAsShadowmap = false;
  44545. /**
  44546. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  44547. * makes the reflect vector face the model (under horizon).
  44548. */
  44549. _this._useHorizonOcclusion = true;
  44550. /**
  44551. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  44552. * too much the area relying on ambient texture to define their ambient occlusion.
  44553. */
  44554. _this._useRadianceOcclusion = true;
  44555. /**
  44556. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  44557. */
  44558. _this._useAlphaFromAlbedoTexture = false;
  44559. /**
  44560. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  44561. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  44562. */
  44563. _this._useSpecularOverAlpha = true;
  44564. /**
  44565. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  44566. */
  44567. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  44568. /**
  44569. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  44570. */
  44571. _this._useRoughnessFromMetallicTextureAlpha = true;
  44572. /**
  44573. * Specifies if the metallic texture contains the roughness information in its green channel.
  44574. */
  44575. _this._useRoughnessFromMetallicTextureGreen = false;
  44576. /**
  44577. * Specifies if the metallic texture contains the metallness information in its blue channel.
  44578. */
  44579. _this._useMetallnessFromMetallicTextureBlue = false;
  44580. /**
  44581. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  44582. */
  44583. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  44584. /**
  44585. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  44586. */
  44587. _this._useAmbientInGrayScale = false;
  44588. /**
  44589. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  44590. * The material will try to infer what glossiness each pixel should be.
  44591. */
  44592. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  44593. /**
  44594. * BJS is using an harcoded light falloff based on a manually sets up range.
  44595. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  44596. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  44597. */
  44598. _this._usePhysicalLightFalloff = true;
  44599. /**
  44600. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  44601. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  44602. */
  44603. _this._useRadianceOverAlpha = true;
  44604. /**
  44605. * Allows using an object space normal map (instead of tangent space).
  44606. */
  44607. _this._useObjectSpaceNormalMap = false;
  44608. /**
  44609. * Allows using the bump map in parallax mode.
  44610. */
  44611. _this._useParallax = false;
  44612. /**
  44613. * Allows using the bump map in parallax occlusion mode.
  44614. */
  44615. _this._useParallaxOcclusion = false;
  44616. /**
  44617. * Controls the scale bias of the parallax mode.
  44618. */
  44619. _this._parallaxScaleBias = 0.05;
  44620. /**
  44621. * If sets to true, disables all the lights affecting the material.
  44622. */
  44623. _this._disableLighting = false;
  44624. /**
  44625. * Number of Simultaneous lights allowed on the material.
  44626. */
  44627. _this._maxSimultaneousLights = 4;
  44628. /**
  44629. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  44630. */
  44631. _this._invertNormalMapX = false;
  44632. /**
  44633. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  44634. */
  44635. _this._invertNormalMapY = false;
  44636. /**
  44637. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44638. */
  44639. _this._twoSidedLighting = false;
  44640. /**
  44641. * Defines the alpha limits in alpha test mode.
  44642. */
  44643. _this._alphaCutOff = 0.4;
  44644. /**
  44645. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  44646. */
  44647. _this._forceAlphaTest = false;
  44648. /**
  44649. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44650. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  44651. */
  44652. _this._useAlphaFresnel = false;
  44653. /**
  44654. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  44655. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  44656. */
  44657. _this._useLinearAlphaFresnel = false;
  44658. /**
  44659. * The transparency mode of the material.
  44660. */
  44661. _this._transparencyMode = null;
  44662. /**
  44663. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  44664. * from cos thetav and roughness:
  44665. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  44666. */
  44667. _this._environmentBRDFTexture = null;
  44668. /**
  44669. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  44670. */
  44671. _this._forceIrradianceInFragment = false;
  44672. /**
  44673. * Force normal to face away from face.
  44674. */
  44675. _this._forceNormalForward = false;
  44676. /**
  44677. * Enables specular anti aliasing in the PBR shader.
  44678. * It will both interacts on the Geometry for analytical and IBL lighting.
  44679. * It also prefilter the roughness map based on the bump values.
  44680. */
  44681. _this._enableSpecularAntiAliasing = false;
  44682. /**
  44683. * Stores the available render targets.
  44684. */
  44685. _this._renderTargets = new BABYLON.SmartArray(16);
  44686. /**
  44687. * Sets the global ambient color for the material used in lighting calculations.
  44688. */
  44689. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  44690. /**
  44691. * If set to true, no lighting calculations will be applied.
  44692. */
  44693. _this._unlit = false;
  44694. // Setup the default processing configuration to the scene.
  44695. _this._attachImageProcessingConfiguration(null);
  44696. _this.getRenderTargetTextures = function () {
  44697. _this._renderTargets.reset();
  44698. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  44699. _this._renderTargets.push(_this._reflectionTexture);
  44700. }
  44701. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  44702. _this._renderTargets.push(_this._refractionTexture);
  44703. }
  44704. return _this._renderTargets;
  44705. };
  44706. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  44707. return _this;
  44708. }
  44709. /**
  44710. * Attaches a new image processing configuration to the PBR Material.
  44711. * @param configuration
  44712. */
  44713. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  44714. var _this = this;
  44715. if (configuration === this._imageProcessingConfiguration) {
  44716. return;
  44717. }
  44718. // Detaches observer.
  44719. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44720. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44721. }
  44722. // Pick the scene configuration if needed.
  44723. if (!configuration) {
  44724. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  44725. }
  44726. else {
  44727. this._imageProcessingConfiguration = configuration;
  44728. }
  44729. // Attaches observer.
  44730. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  44731. _this._markAllSubMeshesAsImageProcessingDirty();
  44732. });
  44733. };
  44734. /**
  44735. * Gets the name of the material class.
  44736. */
  44737. PBRBaseMaterial.prototype.getClassName = function () {
  44738. return "PBRBaseMaterial";
  44739. };
  44740. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  44741. /**
  44742. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44743. */
  44744. get: function () {
  44745. return this._useLogarithmicDepth;
  44746. },
  44747. /**
  44748. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  44749. */
  44750. set: function (value) {
  44751. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  44752. },
  44753. enumerable: true,
  44754. configurable: true
  44755. });
  44756. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  44757. /**
  44758. * Gets the current transparency mode.
  44759. */
  44760. get: function () {
  44761. return this._transparencyMode;
  44762. },
  44763. /**
  44764. * Sets the transparency mode of the material.
  44765. */
  44766. set: function (value) {
  44767. if (this._transparencyMode === value) {
  44768. return;
  44769. }
  44770. this._transparencyMode = value;
  44771. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  44772. this._markAllSubMeshesAsTexturesAndMiscDirty();
  44773. },
  44774. enumerable: true,
  44775. configurable: true
  44776. });
  44777. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  44778. /**
  44779. * Returns true if alpha blending should be disabled.
  44780. */
  44781. get: function () {
  44782. return (this._linkRefractionWithTransparency ||
  44783. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  44784. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44785. },
  44786. enumerable: true,
  44787. configurable: true
  44788. });
  44789. /**
  44790. * Specifies whether or not this material should be rendered in alpha blend mode.
  44791. */
  44792. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  44793. if (this._disableAlphaBlending) {
  44794. return false;
  44795. }
  44796. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  44797. };
  44798. /**
  44799. * Specifies if the mesh will require alpha blending.
  44800. * @param mesh - BJS mesh.
  44801. */
  44802. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  44803. if (this._disableAlphaBlending) {
  44804. return false;
  44805. }
  44806. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  44807. };
  44808. /**
  44809. * Specifies whether or not this material should be rendered in alpha test mode.
  44810. */
  44811. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  44812. if (this._forceAlphaTest) {
  44813. return true;
  44814. }
  44815. if (this._linkRefractionWithTransparency) {
  44816. return false;
  44817. }
  44818. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44819. };
  44820. /**
  44821. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44822. */
  44823. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44824. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44825. };
  44826. /**
  44827. * Gets the texture used for the alpha test.
  44828. */
  44829. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44830. return this._albedoTexture;
  44831. };
  44832. /**
  44833. * Specifies that the submesh is ready to be used.
  44834. * @param mesh - BJS mesh.
  44835. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44836. * @param useInstances - Specifies that instances should be used.
  44837. * @returns - boolean indicating that the submesh is ready or not.
  44838. */
  44839. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44840. if (subMesh.effect && this.isFrozen) {
  44841. if (this._wasPreviouslyReady) {
  44842. return true;
  44843. }
  44844. }
  44845. if (!subMesh._materialDefines) {
  44846. subMesh._materialDefines = new PBRMaterialDefines();
  44847. }
  44848. var defines = subMesh._materialDefines;
  44849. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44850. if (defines._renderId === this.getScene().getRenderId()) {
  44851. return true;
  44852. }
  44853. }
  44854. var scene = this.getScene();
  44855. var engine = scene.getEngine();
  44856. if (defines._areTexturesDirty) {
  44857. if (scene.texturesEnabled) {
  44858. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44859. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44860. return false;
  44861. }
  44862. }
  44863. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44864. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44865. return false;
  44866. }
  44867. }
  44868. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44869. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44870. return false;
  44871. }
  44872. }
  44873. var reflectionTexture = this._getReflectionTexture();
  44874. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44875. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44876. return false;
  44877. }
  44878. }
  44879. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44880. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44881. return false;
  44882. }
  44883. }
  44884. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44885. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44886. return false;
  44887. }
  44888. }
  44889. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44890. if (this._metallicTexture) {
  44891. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44892. return false;
  44893. }
  44894. }
  44895. else if (this._reflectivityTexture) {
  44896. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44897. return false;
  44898. }
  44899. }
  44900. if (this._microSurfaceTexture) {
  44901. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44902. return false;
  44903. }
  44904. }
  44905. }
  44906. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44907. // Bump texture cannot be not blocking.
  44908. if (!this._bumpTexture.isReady()) {
  44909. return false;
  44910. }
  44911. }
  44912. var refractionTexture = this._getRefractionTexture();
  44913. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44914. if (!refractionTexture.isReadyOrNotBlocking()) {
  44915. return false;
  44916. }
  44917. }
  44918. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44919. // This is blocking.
  44920. if (!this._environmentBRDFTexture.isReady()) {
  44921. return false;
  44922. }
  44923. }
  44924. }
  44925. }
  44926. if (defines._areImageProcessingDirty) {
  44927. if (!this._imageProcessingConfiguration.isReady()) {
  44928. return false;
  44929. }
  44930. }
  44931. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44932. mesh.createNormals(true);
  44933. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44934. }
  44935. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44936. if (effect) {
  44937. scene.resetCachedMaterial();
  44938. subMesh.setEffect(effect, defines);
  44939. this.buildUniformLayout();
  44940. }
  44941. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44942. return false;
  44943. }
  44944. defines._renderId = scene.getRenderId();
  44945. this._wasPreviouslyReady = true;
  44946. return true;
  44947. };
  44948. /**
  44949. * Specifies if the material uses metallic roughness workflow.
  44950. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44951. */
  44952. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44953. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44954. return true;
  44955. }
  44956. return false;
  44957. };
  44958. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44959. if (onCompiled === void 0) { onCompiled = null; }
  44960. if (onError === void 0) { onError = null; }
  44961. if (useInstances === void 0) { useInstances = null; }
  44962. if (useClipPlane === void 0) { useClipPlane = null; }
  44963. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44964. if (!defines.isDirty) {
  44965. return null;
  44966. }
  44967. defines.markAsProcessed();
  44968. var scene = this.getScene();
  44969. var engine = scene.getEngine();
  44970. // Fallbacks
  44971. var fallbacks = new BABYLON.EffectFallbacks();
  44972. var fallbackRank = 0;
  44973. if (defines.USESPHERICALINVERTEX) {
  44974. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44975. }
  44976. if (defines.FOG) {
  44977. fallbacks.addFallback(fallbackRank, "FOG");
  44978. }
  44979. if (defines.SPECULARAA) {
  44980. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44981. }
  44982. if (defines.POINTSIZE) {
  44983. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44984. }
  44985. if (defines.LOGARITHMICDEPTH) {
  44986. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44987. }
  44988. if (defines.PARALLAX) {
  44989. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44990. }
  44991. if (defines.PARALLAXOCCLUSION) {
  44992. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44993. }
  44994. if (defines.ENVIRONMENTBRDF) {
  44995. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44996. }
  44997. if (defines.TANGENT) {
  44998. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44999. }
  45000. if (defines.BUMP) {
  45001. fallbacks.addFallback(fallbackRank++, "BUMP");
  45002. }
  45003. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  45004. if (defines.SPECULARTERM) {
  45005. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  45006. }
  45007. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  45008. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  45009. }
  45010. if (defines.LIGHTMAP) {
  45011. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  45012. }
  45013. if (defines.NORMAL) {
  45014. fallbacks.addFallback(fallbackRank++, "NORMAL");
  45015. }
  45016. if (defines.AMBIENT) {
  45017. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  45018. }
  45019. if (defines.EMISSIVE) {
  45020. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  45021. }
  45022. if (defines.VERTEXCOLOR) {
  45023. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  45024. }
  45025. if (defines.NUM_BONE_INFLUENCERS > 0) {
  45026. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  45027. }
  45028. if (defines.MORPHTARGETS) {
  45029. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  45030. }
  45031. //Attributes
  45032. var attribs = [BABYLON.VertexBuffer.PositionKind];
  45033. if (defines.NORMAL) {
  45034. attribs.push(BABYLON.VertexBuffer.NormalKind);
  45035. }
  45036. if (defines.TANGENT) {
  45037. attribs.push(BABYLON.VertexBuffer.TangentKind);
  45038. }
  45039. if (defines.UV1) {
  45040. attribs.push(BABYLON.VertexBuffer.UVKind);
  45041. }
  45042. if (defines.UV2) {
  45043. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  45044. }
  45045. if (defines.VERTEXCOLOR) {
  45046. attribs.push(BABYLON.VertexBuffer.ColorKind);
  45047. }
  45048. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  45049. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  45050. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  45051. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  45052. "vFogInfos", "vFogColor", "pointSize",
  45053. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  45054. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  45055. "mBones",
  45056. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  45057. "vLightingIntensity",
  45058. "logarithmicDepthConstant",
  45059. "vSphericalX", "vSphericalY", "vSphericalZ",
  45060. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  45061. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  45062. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  45063. "vTangentSpaceParams"
  45064. ];
  45065. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  45066. "bumpSampler", "lightmapSampler", "opacitySampler",
  45067. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  45068. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  45069. "microSurfaceSampler", "environmentBrdfSampler"];
  45070. var uniformBuffers = ["Material", "Scene"];
  45071. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  45072. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  45073. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  45074. uniformsNames: uniforms,
  45075. uniformBuffersNames: uniformBuffers,
  45076. samplers: samplers,
  45077. defines: defines,
  45078. maxSimultaneousLights: this._maxSimultaneousLights
  45079. });
  45080. var join = defines.toString();
  45081. return engine.createEffect("pbr", {
  45082. attributes: attribs,
  45083. uniformsNames: uniforms,
  45084. uniformBuffersNames: uniformBuffers,
  45085. samplers: samplers,
  45086. defines: join,
  45087. fallbacks: fallbacks,
  45088. onCompiled: onCompiled,
  45089. onError: onError,
  45090. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  45091. }, engine);
  45092. };
  45093. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  45094. if (useInstances === void 0) { useInstances = null; }
  45095. if (useClipPlane === void 0) { useClipPlane = null; }
  45096. var scene = this.getScene();
  45097. var engine = scene.getEngine();
  45098. // Lights
  45099. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  45100. defines._needNormals = true;
  45101. // Textures
  45102. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  45103. if (defines._areTexturesDirty) {
  45104. defines._needUVs = false;
  45105. if (scene.texturesEnabled) {
  45106. if (scene.getEngine().getCaps().textureLOD) {
  45107. defines.LODBASEDMICROSFURACE = true;
  45108. }
  45109. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45110. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  45111. }
  45112. else {
  45113. defines.ALBEDO = false;
  45114. }
  45115. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45116. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  45117. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  45118. }
  45119. else {
  45120. defines.AMBIENT = false;
  45121. }
  45122. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45123. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  45124. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  45125. }
  45126. else {
  45127. defines.OPACITY = false;
  45128. }
  45129. var reflectionTexture = this._getReflectionTexture();
  45130. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45131. defines.REFLECTION = true;
  45132. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  45133. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  45134. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  45135. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  45136. defines.INVERTCUBICMAP = true;
  45137. }
  45138. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  45139. switch (reflectionTexture.coordinatesMode) {
  45140. case BABYLON.Texture.EXPLICIT_MODE:
  45141. defines.REFLECTIONMAP_EXPLICIT = true;
  45142. break;
  45143. case BABYLON.Texture.PLANAR_MODE:
  45144. defines.REFLECTIONMAP_PLANAR = true;
  45145. break;
  45146. case BABYLON.Texture.PROJECTION_MODE:
  45147. defines.REFLECTIONMAP_PROJECTION = true;
  45148. break;
  45149. case BABYLON.Texture.SKYBOX_MODE:
  45150. defines.REFLECTIONMAP_SKYBOX = true;
  45151. break;
  45152. case BABYLON.Texture.SPHERICAL_MODE:
  45153. defines.REFLECTIONMAP_SPHERICAL = true;
  45154. break;
  45155. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  45156. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  45157. break;
  45158. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  45159. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  45160. break;
  45161. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  45162. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  45163. break;
  45164. case BABYLON.Texture.CUBIC_MODE:
  45165. case BABYLON.Texture.INVCUBIC_MODE:
  45166. default:
  45167. defines.REFLECTIONMAP_CUBIC = true;
  45168. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  45169. break;
  45170. }
  45171. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  45172. if (reflectionTexture.sphericalPolynomial) {
  45173. defines.USESPHERICALFROMREFLECTIONMAP = true;
  45174. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  45175. defines.USESPHERICALINVERTEX = false;
  45176. }
  45177. else {
  45178. defines.USESPHERICALINVERTEX = true;
  45179. }
  45180. }
  45181. }
  45182. }
  45183. else {
  45184. defines.REFLECTION = false;
  45185. defines.REFLECTIONMAP_3D = false;
  45186. defines.REFLECTIONMAP_SPHERICAL = false;
  45187. defines.REFLECTIONMAP_PLANAR = false;
  45188. defines.REFLECTIONMAP_CUBIC = false;
  45189. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  45190. defines.REFLECTIONMAP_PROJECTION = false;
  45191. defines.REFLECTIONMAP_SKYBOX = false;
  45192. defines.REFLECTIONMAP_EXPLICIT = false;
  45193. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  45194. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  45195. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  45196. defines.INVERTCUBICMAP = false;
  45197. defines.USESPHERICALFROMREFLECTIONMAP = false;
  45198. defines.USESPHERICALINVERTEX = false;
  45199. defines.REFLECTIONMAP_OPPOSITEZ = false;
  45200. defines.LODINREFLECTIONALPHA = false;
  45201. defines.GAMMAREFLECTION = false;
  45202. }
  45203. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45204. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  45205. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  45206. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  45207. }
  45208. else {
  45209. defines.LIGHTMAP = false;
  45210. }
  45211. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45212. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  45213. }
  45214. else {
  45215. defines.EMISSIVE = false;
  45216. }
  45217. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45218. if (this._metallicTexture) {
  45219. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  45220. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  45221. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  45222. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  45223. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  45224. }
  45225. else if (this._reflectivityTexture) {
  45226. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  45227. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  45228. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  45229. }
  45230. else {
  45231. defines.REFLECTIVITY = false;
  45232. }
  45233. if (this._microSurfaceTexture) {
  45234. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  45235. }
  45236. else {
  45237. defines.MICROSURFACEMAP = false;
  45238. }
  45239. }
  45240. else {
  45241. defines.REFLECTIVITY = false;
  45242. defines.MICROSURFACEMAP = false;
  45243. }
  45244. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45245. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  45246. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45247. defines.PARALLAX = true;
  45248. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  45249. }
  45250. else {
  45251. defines.PARALLAX = false;
  45252. }
  45253. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  45254. }
  45255. else {
  45256. defines.BUMP = false;
  45257. }
  45258. var refractionTexture = this._getRefractionTexture();
  45259. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45260. defines.REFRACTION = true;
  45261. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  45262. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  45263. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  45264. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  45265. if (this._linkRefractionWithTransparency) {
  45266. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  45267. }
  45268. }
  45269. else {
  45270. defines.REFRACTION = false;
  45271. }
  45272. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45273. defines.ENVIRONMENTBRDF = true;
  45274. }
  45275. else {
  45276. defines.ENVIRONMENTBRDF = false;
  45277. }
  45278. if (this._shouldUseAlphaFromAlbedoTexture()) {
  45279. defines.ALPHAFROMALBEDO = true;
  45280. }
  45281. else {
  45282. defines.ALPHAFROMALBEDO = false;
  45283. }
  45284. }
  45285. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  45286. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  45287. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  45288. if (!this.backFaceCulling && this._twoSidedLighting) {
  45289. defines.TWOSIDEDLIGHTING = true;
  45290. }
  45291. else {
  45292. defines.TWOSIDEDLIGHTING = false;
  45293. }
  45294. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  45295. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  45296. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  45297. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  45298. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  45299. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  45300. }
  45301. if (defines._areImageProcessingDirty) {
  45302. this._imageProcessingConfiguration.prepareDefines(defines);
  45303. }
  45304. defines.FORCENORMALFORWARD = this._forceNormalForward;
  45305. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  45306. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  45307. // Misc.
  45308. if (defines._areMiscDirty) {
  45309. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  45310. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  45311. }
  45312. // Values that need to be evaluated on every frame
  45313. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  45314. // Attribs
  45315. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  45316. };
  45317. /**
  45318. * Force shader compilation
  45319. */
  45320. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  45321. var _this = this;
  45322. var localOptions = __assign({ clipPlane: false }, options);
  45323. var defines = new PBRMaterialDefines();
  45324. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  45325. if (effect.isReady()) {
  45326. if (onCompiled) {
  45327. onCompiled(this);
  45328. }
  45329. }
  45330. else {
  45331. effect.onCompileObservable.add(function () {
  45332. if (onCompiled) {
  45333. onCompiled(_this);
  45334. }
  45335. });
  45336. }
  45337. };
  45338. /**
  45339. * Initializes the uniform buffer layout for the shader.
  45340. */
  45341. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  45342. // Order is important !
  45343. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  45344. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  45345. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  45346. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  45347. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  45348. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  45349. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  45350. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  45351. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  45352. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  45353. this._uniformBuffer.addUniform("vReflectionSize", 3);
  45354. this._uniformBuffer.addUniform("vBumpInfos", 3);
  45355. this._uniformBuffer.addUniform("albedoMatrix", 16);
  45356. this._uniformBuffer.addUniform("ambientMatrix", 16);
  45357. this._uniformBuffer.addUniform("opacityMatrix", 16);
  45358. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  45359. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  45360. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  45361. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  45362. this._uniformBuffer.addUniform("bumpMatrix", 16);
  45363. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  45364. this._uniformBuffer.addUniform("refractionMatrix", 16);
  45365. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  45366. this._uniformBuffer.addUniform("vReflectionColor", 3);
  45367. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  45368. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  45369. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  45370. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  45371. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  45372. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  45373. this._uniformBuffer.addUniform("pointSize", 1);
  45374. this._uniformBuffer.create();
  45375. };
  45376. /**
  45377. * Unbinds the textures.
  45378. */
  45379. PBRBaseMaterial.prototype.unbind = function () {
  45380. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  45381. this._uniformBuffer.setTexture("reflectionSampler", null);
  45382. }
  45383. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  45384. this._uniformBuffer.setTexture("refractionSampler", null);
  45385. }
  45386. _super.prototype.unbind.call(this);
  45387. };
  45388. /**
  45389. * Binds the submesh data.
  45390. * @param world - The world matrix.
  45391. * @param mesh - The BJS mesh.
  45392. * @param subMesh - A submesh of the BJS mesh.
  45393. */
  45394. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  45395. var scene = this.getScene();
  45396. var defines = subMesh._materialDefines;
  45397. if (!defines) {
  45398. return;
  45399. }
  45400. var effect = subMesh.effect;
  45401. if (!effect) {
  45402. return;
  45403. }
  45404. this._activeEffect = effect;
  45405. // Matrices
  45406. this.bindOnlyWorldMatrix(world);
  45407. // Normal Matrix
  45408. if (defines.OBJECTSPACE_NORMALMAP) {
  45409. world.toNormalMatrix(this._normalMatrix);
  45410. this.bindOnlyNormalMatrix(this._normalMatrix);
  45411. }
  45412. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  45413. // Bones
  45414. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  45415. var reflectionTexture = null;
  45416. if (mustRebind) {
  45417. this._uniformBuffer.bindToEffect(effect, "Material");
  45418. this.bindViewProjection(effect);
  45419. reflectionTexture = this._getReflectionTexture();
  45420. var refractionTexture = this._getRefractionTexture();
  45421. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  45422. // Texture uniforms
  45423. if (scene.texturesEnabled) {
  45424. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45425. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  45426. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  45427. }
  45428. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45429. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  45430. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  45431. }
  45432. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45433. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  45434. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  45435. }
  45436. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45437. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  45438. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  45439. if (reflectionTexture.boundingBoxSize) {
  45440. var cubeTexture = reflectionTexture;
  45441. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  45442. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  45443. }
  45444. var polynomials = reflectionTexture.sphericalPolynomial;
  45445. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  45446. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  45447. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  45448. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  45449. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  45450. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  45451. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  45452. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  45453. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  45454. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  45455. }
  45456. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  45457. }
  45458. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45459. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  45460. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  45461. }
  45462. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45463. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  45464. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  45465. }
  45466. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45467. if (this._metallicTexture) {
  45468. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  45469. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  45470. }
  45471. else if (this._reflectivityTexture) {
  45472. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  45473. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  45474. }
  45475. if (this._microSurfaceTexture) {
  45476. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  45477. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  45478. }
  45479. }
  45480. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45481. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  45482. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  45483. if (scene._mirroredCameraPosition) {
  45484. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  45485. }
  45486. else {
  45487. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  45488. }
  45489. }
  45490. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45491. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  45492. var depth = 1.0;
  45493. if (!refractionTexture.isCube) {
  45494. if (refractionTexture.depth) {
  45495. depth = refractionTexture.depth;
  45496. }
  45497. }
  45498. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  45499. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  45500. }
  45501. }
  45502. // Point size
  45503. if (this.pointsCloud) {
  45504. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  45505. }
  45506. // Colors
  45507. if (defines.METALLICWORKFLOW) {
  45508. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  45509. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  45510. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  45511. }
  45512. else {
  45513. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  45514. }
  45515. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  45516. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  45517. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  45518. // Misc
  45519. this._lightingInfos.x = this._directIntensity;
  45520. this._lightingInfos.y = this._emissiveIntensity;
  45521. this._lightingInfos.z = this._environmentIntensity;
  45522. this._lightingInfos.w = this._specularIntensity;
  45523. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  45524. }
  45525. // Textures
  45526. if (scene.texturesEnabled) {
  45527. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  45528. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  45529. }
  45530. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  45531. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  45532. }
  45533. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  45534. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  45535. }
  45536. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  45537. if (defines.LODBASEDMICROSFURACE) {
  45538. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  45539. }
  45540. else {
  45541. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  45542. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  45543. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  45544. }
  45545. }
  45546. if (defines.ENVIRONMENTBRDF) {
  45547. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  45548. }
  45549. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  45550. if (defines.LODBASEDMICROSFURACE) {
  45551. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  45552. }
  45553. else {
  45554. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  45555. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  45556. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  45557. }
  45558. }
  45559. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  45560. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  45561. }
  45562. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  45563. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  45564. }
  45565. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  45566. if (this._metallicTexture) {
  45567. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  45568. }
  45569. else if (this._reflectivityTexture) {
  45570. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  45571. }
  45572. if (this._microSurfaceTexture) {
  45573. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  45574. }
  45575. }
  45576. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  45577. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  45578. }
  45579. }
  45580. // Clip plane
  45581. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  45582. // Colors
  45583. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  45584. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  45585. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  45586. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  45587. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  45588. }
  45589. if (mustRebind || !this.isFrozen) {
  45590. // Lights
  45591. if (scene.lightsEnabled && !this._disableLighting) {
  45592. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  45593. }
  45594. // View
  45595. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  45596. this.bindView(effect);
  45597. }
  45598. // Fog
  45599. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  45600. // Morph targets
  45601. if (defines.NUM_MORPH_INFLUENCERS) {
  45602. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  45603. }
  45604. // image processing
  45605. this._imageProcessingConfiguration.bind(this._activeEffect);
  45606. // Log. depth
  45607. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  45608. }
  45609. this._uniformBuffer.update();
  45610. this._afterBind(mesh, this._activeEffect);
  45611. };
  45612. /**
  45613. * Returns the animatable textures.
  45614. * @returns - Array of animatable textures.
  45615. */
  45616. PBRBaseMaterial.prototype.getAnimatables = function () {
  45617. var results = [];
  45618. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  45619. results.push(this._albedoTexture);
  45620. }
  45621. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  45622. results.push(this._ambientTexture);
  45623. }
  45624. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  45625. results.push(this._opacityTexture);
  45626. }
  45627. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  45628. results.push(this._reflectionTexture);
  45629. }
  45630. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  45631. results.push(this._emissiveTexture);
  45632. }
  45633. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  45634. results.push(this._metallicTexture);
  45635. }
  45636. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  45637. results.push(this._reflectivityTexture);
  45638. }
  45639. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  45640. results.push(this._bumpTexture);
  45641. }
  45642. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  45643. results.push(this._lightmapTexture);
  45644. }
  45645. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  45646. results.push(this._refractionTexture);
  45647. }
  45648. return results;
  45649. };
  45650. /**
  45651. * Returns the texture used for reflections.
  45652. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  45653. */
  45654. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  45655. if (this._reflectionTexture) {
  45656. return this._reflectionTexture;
  45657. }
  45658. return this.getScene().environmentTexture;
  45659. };
  45660. /**
  45661. * Returns the texture used for refraction or null if none is used.
  45662. * @returns - Refection texture if present. If no refraction texture and refraction
  45663. * is linked with transparency, returns environment texture. Otherwise, returns null.
  45664. */
  45665. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  45666. if (this._refractionTexture) {
  45667. return this._refractionTexture;
  45668. }
  45669. if (this._linkRefractionWithTransparency) {
  45670. return this.getScene().environmentTexture;
  45671. }
  45672. return null;
  45673. };
  45674. /**
  45675. * Disposes the resources of the material.
  45676. * @param forceDisposeEffect - Forces the disposal of effects.
  45677. * @param forceDisposeTextures - Forces the disposal of all textures.
  45678. */
  45679. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  45680. if (forceDisposeTextures) {
  45681. if (this._albedoTexture) {
  45682. this._albedoTexture.dispose();
  45683. }
  45684. if (this._ambientTexture) {
  45685. this._ambientTexture.dispose();
  45686. }
  45687. if (this._opacityTexture) {
  45688. this._opacityTexture.dispose();
  45689. }
  45690. if (this._reflectionTexture) {
  45691. this._reflectionTexture.dispose();
  45692. }
  45693. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  45694. this._environmentBRDFTexture.dispose();
  45695. }
  45696. if (this._emissiveTexture) {
  45697. this._emissiveTexture.dispose();
  45698. }
  45699. if (this._metallicTexture) {
  45700. this._metallicTexture.dispose();
  45701. }
  45702. if (this._reflectivityTexture) {
  45703. this._reflectivityTexture.dispose();
  45704. }
  45705. if (this._bumpTexture) {
  45706. this._bumpTexture.dispose();
  45707. }
  45708. if (this._lightmapTexture) {
  45709. this._lightmapTexture.dispose();
  45710. }
  45711. if (this._refractionTexture) {
  45712. this._refractionTexture.dispose();
  45713. }
  45714. }
  45715. this._renderTargets.dispose();
  45716. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  45717. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  45718. }
  45719. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  45720. };
  45721. /**
  45722. * Stores the reflectivity values based on metallic roughness workflow.
  45723. */
  45724. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  45725. __decorate([
  45726. BABYLON.serializeAsImageProcessingConfiguration()
  45727. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  45728. __decorate([
  45729. BABYLON.serialize()
  45730. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  45731. __decorate([
  45732. BABYLON.serialize()
  45733. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  45734. return PBRBaseMaterial;
  45735. }(BABYLON.PushMaterial));
  45736. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  45737. })(BABYLON || (BABYLON = {}));
  45738. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  45739. var BABYLON;
  45740. (function (BABYLON) {
  45741. /**
  45742. * The Physically based simple base material of BJS.
  45743. *
  45744. * This enables better naming and convention enforcements on top of the pbrMaterial.
  45745. * It is used as the base class for both the specGloss and metalRough conventions.
  45746. */
  45747. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  45748. __extends(PBRBaseSimpleMaterial, _super);
  45749. /**
  45750. * Instantiates a new PBRMaterial instance.
  45751. *
  45752. * @param name The material name
  45753. * @param scene The scene the material will be use in.
  45754. */
  45755. function PBRBaseSimpleMaterial(name, scene) {
  45756. var _this = _super.call(this, name, scene) || this;
  45757. /**
  45758. * Number of Simultaneous lights allowed on the material.
  45759. */
  45760. _this.maxSimultaneousLights = 4;
  45761. /**
  45762. * If sets to true, disables all the lights affecting the material.
  45763. */
  45764. _this.disableLighting = false;
  45765. /**
  45766. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45767. */
  45768. _this.invertNormalMapX = false;
  45769. /**
  45770. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45771. */
  45772. _this.invertNormalMapY = false;
  45773. /**
  45774. * Emissivie color used to self-illuminate the model.
  45775. */
  45776. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45777. /**
  45778. * Occlusion Channel Strenght.
  45779. */
  45780. _this.occlusionStrength = 1.0;
  45781. _this.useLightmapAsShadowmap = false;
  45782. _this._useAlphaFromAlbedoTexture = true;
  45783. _this._useAmbientInGrayScale = true;
  45784. return _this;
  45785. }
  45786. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  45787. /**
  45788. * Gets the current double sided mode.
  45789. */
  45790. get: function () {
  45791. return this._twoSidedLighting;
  45792. },
  45793. /**
  45794. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45795. */
  45796. set: function (value) {
  45797. if (this._twoSidedLighting === value) {
  45798. return;
  45799. }
  45800. this._twoSidedLighting = value;
  45801. this.backFaceCulling = !value;
  45802. this._markAllSubMeshesAsTexturesDirty();
  45803. },
  45804. enumerable: true,
  45805. configurable: true
  45806. });
  45807. /**
  45808. * Return the active textures of the material.
  45809. */
  45810. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45811. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45812. if (this.environmentTexture) {
  45813. activeTextures.push(this.environmentTexture);
  45814. }
  45815. if (this.normalTexture) {
  45816. activeTextures.push(this.normalTexture);
  45817. }
  45818. if (this.emissiveTexture) {
  45819. activeTextures.push(this.emissiveTexture);
  45820. }
  45821. if (this.occlusionTexture) {
  45822. activeTextures.push(this.occlusionTexture);
  45823. }
  45824. if (this.lightmapTexture) {
  45825. activeTextures.push(this.lightmapTexture);
  45826. }
  45827. return activeTextures;
  45828. };
  45829. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45830. if (_super.prototype.hasTexture.call(this, texture)) {
  45831. return true;
  45832. }
  45833. if (this.lightmapTexture === texture) {
  45834. return true;
  45835. }
  45836. return false;
  45837. };
  45838. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45839. return "PBRBaseSimpleMaterial";
  45840. };
  45841. __decorate([
  45842. BABYLON.serialize(),
  45843. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45844. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45845. __decorate([
  45846. BABYLON.serialize(),
  45847. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45848. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45849. __decorate([
  45850. BABYLON.serializeAsTexture(),
  45851. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45852. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45853. __decorate([
  45854. BABYLON.serialize(),
  45855. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45856. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45857. __decorate([
  45858. BABYLON.serialize(),
  45859. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45860. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45861. __decorate([
  45862. BABYLON.serializeAsTexture(),
  45863. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45864. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45865. __decorate([
  45866. BABYLON.serializeAsColor3("emissive"),
  45867. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45868. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45869. __decorate([
  45870. BABYLON.serializeAsTexture(),
  45871. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45872. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45873. __decorate([
  45874. BABYLON.serialize(),
  45875. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45876. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45877. __decorate([
  45878. BABYLON.serializeAsTexture(),
  45879. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45880. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45881. __decorate([
  45882. BABYLON.serialize(),
  45883. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45884. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45885. __decorate([
  45886. BABYLON.serialize()
  45887. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45888. __decorate([
  45889. BABYLON.serializeAsTexture(),
  45890. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45891. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45892. __decorate([
  45893. BABYLON.serialize(),
  45894. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45895. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45896. return PBRBaseSimpleMaterial;
  45897. }(BABYLON.PBRBaseMaterial));
  45898. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45899. })(BABYLON || (BABYLON = {}));
  45900. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45901. var BABYLON;
  45902. (function (BABYLON) {
  45903. /**
  45904. * The Physically based material of BJS.
  45905. *
  45906. * This offers the main features of a standard PBR material.
  45907. * For more information, please refer to the documentation :
  45908. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45909. */
  45910. var PBRMaterial = /** @class */ (function (_super) {
  45911. __extends(PBRMaterial, _super);
  45912. /**
  45913. * Instantiates a new PBRMaterial instance.
  45914. *
  45915. * @param name The material name
  45916. * @param scene The scene the material will be use in.
  45917. */
  45918. function PBRMaterial(name, scene) {
  45919. var _this = _super.call(this, name, scene) || this;
  45920. /**
  45921. * Intensity of the direct lights e.g. the four lights available in your scene.
  45922. * This impacts both the direct diffuse and specular highlights.
  45923. */
  45924. _this.directIntensity = 1.0;
  45925. /**
  45926. * Intensity of the emissive part of the material.
  45927. * This helps controlling the emissive effect without modifying the emissive color.
  45928. */
  45929. _this.emissiveIntensity = 1.0;
  45930. /**
  45931. * Intensity of the environment e.g. how much the environment will light the object
  45932. * either through harmonics for rough material or through the refelction for shiny ones.
  45933. */
  45934. _this.environmentIntensity = 1.0;
  45935. /**
  45936. * This is a special control allowing the reduction of the specular highlights coming from the
  45937. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45938. */
  45939. _this.specularIntensity = 1.0;
  45940. /**
  45941. * Debug Control allowing disabling the bump map on this material.
  45942. */
  45943. _this.disableBumpMap = false;
  45944. /**
  45945. * AKA Occlusion Texture Intensity in other nomenclature.
  45946. */
  45947. _this.ambientTextureStrength = 1.0;
  45948. /**
  45949. * The color of a material in ambient lighting.
  45950. */
  45951. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45952. /**
  45953. * AKA Diffuse Color in other nomenclature.
  45954. */
  45955. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45956. /**
  45957. * AKA Specular Color in other nomenclature.
  45958. */
  45959. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45960. /**
  45961. * The color reflected from the material.
  45962. */
  45963. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45964. /**
  45965. * The color emitted from the material.
  45966. */
  45967. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45968. /**
  45969. * AKA Glossiness in other nomenclature.
  45970. */
  45971. _this.microSurface = 1.0;
  45972. /**
  45973. * source material index of refraction (IOR)' / 'destination material IOR.
  45974. */
  45975. _this.indexOfRefraction = 0.66;
  45976. /**
  45977. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45978. */
  45979. _this.invertRefractionY = false;
  45980. /**
  45981. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45982. * Materials half opaque for instance using refraction could benefit from this control.
  45983. */
  45984. _this.linkRefractionWithTransparency = false;
  45985. _this.useLightmapAsShadowmap = false;
  45986. /**
  45987. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45988. */
  45989. _this.useAlphaFromAlbedoTexture = false;
  45990. /**
  45991. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45992. */
  45993. _this.forceAlphaTest = false;
  45994. /**
  45995. * Defines the alpha limits in alpha test mode.
  45996. */
  45997. _this.alphaCutOff = 0.4;
  45998. /**
  45999. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  46000. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  46001. */
  46002. _this.useSpecularOverAlpha = true;
  46003. /**
  46004. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  46005. */
  46006. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  46007. /**
  46008. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  46009. */
  46010. _this.useRoughnessFromMetallicTextureAlpha = true;
  46011. /**
  46012. * Specifies if the metallic texture contains the roughness information in its green channel.
  46013. */
  46014. _this.useRoughnessFromMetallicTextureGreen = false;
  46015. /**
  46016. * Specifies if the metallic texture contains the metallness information in its blue channel.
  46017. */
  46018. _this.useMetallnessFromMetallicTextureBlue = false;
  46019. /**
  46020. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  46021. */
  46022. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  46023. /**
  46024. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  46025. */
  46026. _this.useAmbientInGrayScale = false;
  46027. /**
  46028. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  46029. * The material will try to infer what glossiness each pixel should be.
  46030. */
  46031. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  46032. /**
  46033. * BJS is using an harcoded light falloff based on a manually sets up range.
  46034. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  46035. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  46036. */
  46037. _this.usePhysicalLightFalloff = true;
  46038. /**
  46039. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  46040. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  46041. */
  46042. _this.useRadianceOverAlpha = true;
  46043. /**
  46044. * Allows using an object space normal map (instead of tangent space).
  46045. */
  46046. _this.useObjectSpaceNormalMap = false;
  46047. /**
  46048. * Allows using the bump map in parallax mode.
  46049. */
  46050. _this.useParallax = false;
  46051. /**
  46052. * Allows using the bump map in parallax occlusion mode.
  46053. */
  46054. _this.useParallaxOcclusion = false;
  46055. /**
  46056. * Controls the scale bias of the parallax mode.
  46057. */
  46058. _this.parallaxScaleBias = 0.05;
  46059. /**
  46060. * If sets to true, disables all the lights affecting the material.
  46061. */
  46062. _this.disableLighting = false;
  46063. /**
  46064. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  46065. */
  46066. _this.forceIrradianceInFragment = false;
  46067. /**
  46068. * Number of Simultaneous lights allowed on the material.
  46069. */
  46070. _this.maxSimultaneousLights = 4;
  46071. /**
  46072. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  46073. */
  46074. _this.invertNormalMapX = false;
  46075. /**
  46076. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  46077. */
  46078. _this.invertNormalMapY = false;
  46079. /**
  46080. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  46081. */
  46082. _this.twoSidedLighting = false;
  46083. /**
  46084. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46085. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  46086. */
  46087. _this.useAlphaFresnel = false;
  46088. /**
  46089. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46090. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  46091. */
  46092. _this.useLinearAlphaFresnel = false;
  46093. /**
  46094. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  46095. * And/Or occlude the blended part.
  46096. */
  46097. _this.environmentBRDFTexture = null;
  46098. /**
  46099. * Force normal to face away from face.
  46100. */
  46101. _this.forceNormalForward = false;
  46102. /**
  46103. * Enables specular anti aliasing in the PBR shader.
  46104. * It will both interacts on the Geometry for analytical and IBL lighting.
  46105. * It also prefilter the roughness map based on the bump values.
  46106. */
  46107. _this.enableSpecularAntiAliasing = false;
  46108. /**
  46109. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  46110. * makes the reflect vector face the model (under horizon).
  46111. */
  46112. _this.useHorizonOcclusion = true;
  46113. /**
  46114. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  46115. * too much the area relying on ambient texture to define their ambient occlusion.
  46116. */
  46117. _this.useRadianceOcclusion = true;
  46118. /**
  46119. * If set to true, no lighting calculations will be applied.
  46120. */
  46121. _this.unlit = false;
  46122. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  46123. return _this;
  46124. }
  46125. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  46126. /**
  46127. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  46128. */
  46129. get: function () {
  46130. return this._PBRMATERIAL_OPAQUE;
  46131. },
  46132. enumerable: true,
  46133. configurable: true
  46134. });
  46135. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  46136. /**
  46137. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46138. */
  46139. get: function () {
  46140. return this._PBRMATERIAL_ALPHATEST;
  46141. },
  46142. enumerable: true,
  46143. configurable: true
  46144. });
  46145. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  46146. /**
  46147. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46148. */
  46149. get: function () {
  46150. return this._PBRMATERIAL_ALPHABLEND;
  46151. },
  46152. enumerable: true,
  46153. configurable: true
  46154. });
  46155. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  46156. /**
  46157. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46158. * They are also discarded below the alpha cutoff threshold to improve performances.
  46159. */
  46160. get: function () {
  46161. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  46162. },
  46163. enumerable: true,
  46164. configurable: true
  46165. });
  46166. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  46167. /**
  46168. * Gets the image processing configuration used either in this material.
  46169. */
  46170. get: function () {
  46171. return this._imageProcessingConfiguration;
  46172. },
  46173. /**
  46174. * Sets the Default image processing configuration used either in the this material.
  46175. *
  46176. * If sets to null, the scene one is in use.
  46177. */
  46178. set: function (value) {
  46179. this._attachImageProcessingConfiguration(value);
  46180. // Ensure the effect will be rebuilt.
  46181. this._markAllSubMeshesAsTexturesDirty();
  46182. },
  46183. enumerable: true,
  46184. configurable: true
  46185. });
  46186. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  46187. /**
  46188. * Gets wether the color curves effect is enabled.
  46189. */
  46190. get: function () {
  46191. return this.imageProcessingConfiguration.colorCurvesEnabled;
  46192. },
  46193. /**
  46194. * Sets wether the color curves effect is enabled.
  46195. */
  46196. set: function (value) {
  46197. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  46198. },
  46199. enumerable: true,
  46200. configurable: true
  46201. });
  46202. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  46203. /**
  46204. * Gets wether the color grading effect is enabled.
  46205. */
  46206. get: function () {
  46207. return this.imageProcessingConfiguration.colorGradingEnabled;
  46208. },
  46209. /**
  46210. * Gets wether the color grading effect is enabled.
  46211. */
  46212. set: function (value) {
  46213. this.imageProcessingConfiguration.colorGradingEnabled = value;
  46214. },
  46215. enumerable: true,
  46216. configurable: true
  46217. });
  46218. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  46219. /**
  46220. * Gets wether tonemapping is enabled or not.
  46221. */
  46222. get: function () {
  46223. return this._imageProcessingConfiguration.toneMappingEnabled;
  46224. },
  46225. /**
  46226. * Sets wether tonemapping is enabled or not
  46227. */
  46228. set: function (value) {
  46229. this._imageProcessingConfiguration.toneMappingEnabled = value;
  46230. },
  46231. enumerable: true,
  46232. configurable: true
  46233. });
  46234. ;
  46235. ;
  46236. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  46237. /**
  46238. * The camera exposure used on this material.
  46239. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46240. * This corresponds to a photographic exposure.
  46241. */
  46242. get: function () {
  46243. return this._imageProcessingConfiguration.exposure;
  46244. },
  46245. /**
  46246. * The camera exposure used on this material.
  46247. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  46248. * This corresponds to a photographic exposure.
  46249. */
  46250. set: function (value) {
  46251. this._imageProcessingConfiguration.exposure = value;
  46252. },
  46253. enumerable: true,
  46254. configurable: true
  46255. });
  46256. ;
  46257. ;
  46258. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  46259. /**
  46260. * Gets The camera contrast used on this material.
  46261. */
  46262. get: function () {
  46263. return this._imageProcessingConfiguration.contrast;
  46264. },
  46265. /**
  46266. * Sets The camera contrast used on this material.
  46267. */
  46268. set: function (value) {
  46269. this._imageProcessingConfiguration.contrast = value;
  46270. },
  46271. enumerable: true,
  46272. configurable: true
  46273. });
  46274. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  46275. /**
  46276. * Gets the Color Grading 2D Lookup Texture.
  46277. */
  46278. get: function () {
  46279. return this._imageProcessingConfiguration.colorGradingTexture;
  46280. },
  46281. /**
  46282. * Sets the Color Grading 2D Lookup Texture.
  46283. */
  46284. set: function (value) {
  46285. this._imageProcessingConfiguration.colorGradingTexture = value;
  46286. },
  46287. enumerable: true,
  46288. configurable: true
  46289. });
  46290. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  46291. /**
  46292. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46293. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46294. * 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;
  46295. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46296. */
  46297. get: function () {
  46298. return this._imageProcessingConfiguration.colorCurves;
  46299. },
  46300. /**
  46301. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  46302. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  46303. * 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;
  46304. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  46305. */
  46306. set: function (value) {
  46307. this._imageProcessingConfiguration.colorCurves = value;
  46308. },
  46309. enumerable: true,
  46310. configurable: true
  46311. });
  46312. /**
  46313. * Returns the name of this material class.
  46314. */
  46315. PBRMaterial.prototype.getClassName = function () {
  46316. return "PBRMaterial";
  46317. };
  46318. /**
  46319. * Returns an array of the actively used textures.
  46320. * @returns - Array of BaseTextures
  46321. */
  46322. PBRMaterial.prototype.getActiveTextures = function () {
  46323. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46324. if (this._albedoTexture) {
  46325. activeTextures.push(this._albedoTexture);
  46326. }
  46327. if (this._ambientTexture) {
  46328. activeTextures.push(this._ambientTexture);
  46329. }
  46330. if (this._opacityTexture) {
  46331. activeTextures.push(this._opacityTexture);
  46332. }
  46333. if (this._reflectionTexture) {
  46334. activeTextures.push(this._reflectionTexture);
  46335. }
  46336. if (this._emissiveTexture) {
  46337. activeTextures.push(this._emissiveTexture);
  46338. }
  46339. if (this._reflectivityTexture) {
  46340. activeTextures.push(this._reflectivityTexture);
  46341. }
  46342. if (this._metallicTexture) {
  46343. activeTextures.push(this._metallicTexture);
  46344. }
  46345. if (this._microSurfaceTexture) {
  46346. activeTextures.push(this._microSurfaceTexture);
  46347. }
  46348. if (this._bumpTexture) {
  46349. activeTextures.push(this._bumpTexture);
  46350. }
  46351. if (this._lightmapTexture) {
  46352. activeTextures.push(this._lightmapTexture);
  46353. }
  46354. if (this._refractionTexture) {
  46355. activeTextures.push(this._refractionTexture);
  46356. }
  46357. return activeTextures;
  46358. };
  46359. /**
  46360. * Checks to see if a texture is used in the material.
  46361. * @param texture - Base texture to use.
  46362. * @returns - Boolean specifying if a texture is used in the material.
  46363. */
  46364. PBRMaterial.prototype.hasTexture = function (texture) {
  46365. if (_super.prototype.hasTexture.call(this, texture)) {
  46366. return true;
  46367. }
  46368. if (this._albedoTexture === texture) {
  46369. return true;
  46370. }
  46371. if (this._ambientTexture === texture) {
  46372. return true;
  46373. }
  46374. if (this._opacityTexture === texture) {
  46375. return true;
  46376. }
  46377. if (this._reflectionTexture === texture) {
  46378. return true;
  46379. }
  46380. if (this._reflectivityTexture === texture) {
  46381. return true;
  46382. }
  46383. if (this._metallicTexture === texture) {
  46384. return true;
  46385. }
  46386. if (this._microSurfaceTexture === texture) {
  46387. return true;
  46388. }
  46389. if (this._bumpTexture === texture) {
  46390. return true;
  46391. }
  46392. if (this._lightmapTexture === texture) {
  46393. return true;
  46394. }
  46395. if (this._refractionTexture === texture) {
  46396. return true;
  46397. }
  46398. return false;
  46399. };
  46400. /**
  46401. * Makes a duplicate of the current material.
  46402. * @param name - name to use for the new material.
  46403. */
  46404. PBRMaterial.prototype.clone = function (name) {
  46405. var _this = this;
  46406. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  46407. clone.id = name;
  46408. clone.name = name;
  46409. return clone;
  46410. };
  46411. /**
  46412. * Serializes this PBR Material.
  46413. * @returns - An object with the serialized material.
  46414. */
  46415. PBRMaterial.prototype.serialize = function () {
  46416. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46417. serializationObject.customType = "BABYLON.PBRMaterial";
  46418. return serializationObject;
  46419. };
  46420. // Statics
  46421. /**
  46422. * Parses a PBR Material from a serialized object.
  46423. * @param source - Serialized object.
  46424. * @param scene - BJS scene instance.
  46425. * @param rootUrl - url for the scene object
  46426. * @returns - PBRMaterial
  46427. */
  46428. PBRMaterial.Parse = function (source, scene, rootUrl) {
  46429. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  46430. };
  46431. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  46432. /**
  46433. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  46434. */
  46435. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  46436. /**
  46437. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  46438. */
  46439. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  46440. /**
  46441. * 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.
  46442. * They are also discarded below the alpha cutoff threshold to improve performances.
  46443. */
  46444. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  46445. __decorate([
  46446. BABYLON.serialize(),
  46447. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46448. ], PBRMaterial.prototype, "directIntensity", void 0);
  46449. __decorate([
  46450. BABYLON.serialize(),
  46451. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46452. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  46453. __decorate([
  46454. BABYLON.serialize(),
  46455. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46456. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  46457. __decorate([
  46458. BABYLON.serialize(),
  46459. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46460. ], PBRMaterial.prototype, "specularIntensity", void 0);
  46461. __decorate([
  46462. BABYLON.serialize(),
  46463. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46464. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  46465. __decorate([
  46466. BABYLON.serializeAsTexture(),
  46467. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46468. ], PBRMaterial.prototype, "albedoTexture", void 0);
  46469. __decorate([
  46470. BABYLON.serializeAsTexture(),
  46471. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46472. ], PBRMaterial.prototype, "ambientTexture", void 0);
  46473. __decorate([
  46474. BABYLON.serialize(),
  46475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46476. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  46477. __decorate([
  46478. BABYLON.serializeAsTexture(),
  46479. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46480. ], PBRMaterial.prototype, "opacityTexture", void 0);
  46481. __decorate([
  46482. BABYLON.serializeAsTexture(),
  46483. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46484. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  46485. __decorate([
  46486. BABYLON.serializeAsTexture(),
  46487. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46488. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  46489. __decorate([
  46490. BABYLON.serializeAsTexture(),
  46491. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46492. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  46493. __decorate([
  46494. BABYLON.serializeAsTexture(),
  46495. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46496. ], PBRMaterial.prototype, "metallicTexture", void 0);
  46497. __decorate([
  46498. BABYLON.serialize(),
  46499. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46500. ], PBRMaterial.prototype, "metallic", void 0);
  46501. __decorate([
  46502. BABYLON.serialize(),
  46503. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46504. ], PBRMaterial.prototype, "roughness", void 0);
  46505. __decorate([
  46506. BABYLON.serializeAsTexture(),
  46507. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46508. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  46509. __decorate([
  46510. BABYLON.serializeAsTexture(),
  46511. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46512. ], PBRMaterial.prototype, "bumpTexture", void 0);
  46513. __decorate([
  46514. BABYLON.serializeAsTexture(),
  46515. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  46516. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  46517. __decorate([
  46518. BABYLON.serializeAsTexture(),
  46519. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46520. ], PBRMaterial.prototype, "refractionTexture", void 0);
  46521. __decorate([
  46522. BABYLON.serializeAsColor3("ambient"),
  46523. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46524. ], PBRMaterial.prototype, "ambientColor", void 0);
  46525. __decorate([
  46526. BABYLON.serializeAsColor3("albedo"),
  46527. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46528. ], PBRMaterial.prototype, "albedoColor", void 0);
  46529. __decorate([
  46530. BABYLON.serializeAsColor3("reflectivity"),
  46531. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46532. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  46533. __decorate([
  46534. BABYLON.serializeAsColor3("reflection"),
  46535. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46536. ], PBRMaterial.prototype, "reflectionColor", void 0);
  46537. __decorate([
  46538. BABYLON.serializeAsColor3("emissive"),
  46539. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46540. ], PBRMaterial.prototype, "emissiveColor", void 0);
  46541. __decorate([
  46542. BABYLON.serialize(),
  46543. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46544. ], PBRMaterial.prototype, "microSurface", void 0);
  46545. __decorate([
  46546. BABYLON.serialize(),
  46547. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46548. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  46549. __decorate([
  46550. BABYLON.serialize(),
  46551. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46552. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  46553. __decorate([
  46554. BABYLON.serialize(),
  46555. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46556. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  46557. __decorate([
  46558. BABYLON.serialize(),
  46559. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46560. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  46561. __decorate([
  46562. BABYLON.serialize(),
  46563. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46564. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  46565. __decorate([
  46566. BABYLON.serialize(),
  46567. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46568. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  46569. __decorate([
  46570. BABYLON.serialize(),
  46571. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  46572. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  46573. __decorate([
  46574. BABYLON.serialize(),
  46575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46576. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  46577. __decorate([
  46578. BABYLON.serialize(),
  46579. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46580. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  46581. __decorate([
  46582. BABYLON.serialize(),
  46583. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46584. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  46585. __decorate([
  46586. BABYLON.serialize(),
  46587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46588. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  46589. __decorate([
  46590. BABYLON.serialize(),
  46591. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46592. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  46593. __decorate([
  46594. BABYLON.serialize(),
  46595. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46596. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  46597. __decorate([
  46598. BABYLON.serialize(),
  46599. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46600. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  46601. __decorate([
  46602. BABYLON.serialize(),
  46603. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46604. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  46605. __decorate([
  46606. BABYLON.serialize(),
  46607. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46608. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  46609. __decorate([
  46610. BABYLON.serialize(),
  46611. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46612. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  46613. __decorate([
  46614. BABYLON.serialize(),
  46615. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46616. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  46617. __decorate([
  46618. BABYLON.serialize(),
  46619. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46620. ], PBRMaterial.prototype, "useParallax", void 0);
  46621. __decorate([
  46622. BABYLON.serialize(),
  46623. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46624. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  46625. __decorate([
  46626. BABYLON.serialize(),
  46627. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46628. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  46629. __decorate([
  46630. BABYLON.serialize(),
  46631. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46632. ], PBRMaterial.prototype, "disableLighting", void 0);
  46633. __decorate([
  46634. BABYLON.serialize(),
  46635. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46636. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  46637. __decorate([
  46638. BABYLON.serialize(),
  46639. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46640. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  46641. __decorate([
  46642. BABYLON.serialize(),
  46643. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46644. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  46645. __decorate([
  46646. BABYLON.serialize(),
  46647. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46648. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  46649. __decorate([
  46650. BABYLON.serialize(),
  46651. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46652. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  46653. __decorate([
  46654. BABYLON.serialize(),
  46655. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46656. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  46657. __decorate([
  46658. BABYLON.serialize(),
  46659. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46660. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  46661. __decorate([
  46662. BABYLON.serializeAsTexture(),
  46663. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46664. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  46665. __decorate([
  46666. BABYLON.serialize(),
  46667. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46668. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  46669. __decorate([
  46670. BABYLON.serialize(),
  46671. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46672. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  46673. __decorate([
  46674. BABYLON.serialize(),
  46675. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46676. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  46677. __decorate([
  46678. BABYLON.serialize(),
  46679. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46680. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  46681. __decorate([
  46682. BABYLON.serialize(),
  46683. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  46684. ], PBRMaterial.prototype, "unlit", void 0);
  46685. return PBRMaterial;
  46686. }(BABYLON.PBRBaseMaterial));
  46687. BABYLON.PBRMaterial = PBRMaterial;
  46688. })(BABYLON || (BABYLON = {}));
  46689. //# sourceMappingURL=babylon.pbrMaterial.js.map
  46690. var BABYLON;
  46691. (function (BABYLON) {
  46692. /**
  46693. * The PBR material of BJS following the metal roughness convention.
  46694. *
  46695. * This fits to the PBR convention in the GLTF definition:
  46696. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  46697. */
  46698. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  46699. __extends(PBRMetallicRoughnessMaterial, _super);
  46700. /**
  46701. * Instantiates a new PBRMetalRoughnessMaterial instance.
  46702. *
  46703. * @param name The material name
  46704. * @param scene The scene the material will be use in.
  46705. */
  46706. function PBRMetallicRoughnessMaterial(name, scene) {
  46707. var _this = _super.call(this, name, scene) || this;
  46708. _this._useRoughnessFromMetallicTextureAlpha = false;
  46709. _this._useRoughnessFromMetallicTextureGreen = true;
  46710. _this._useMetallnessFromMetallicTextureBlue = true;
  46711. _this.metallic = 1.0;
  46712. _this.roughness = 1.0;
  46713. return _this;
  46714. }
  46715. /**
  46716. * Return the currrent class name of the material.
  46717. */
  46718. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  46719. return "PBRMetallicRoughnessMaterial";
  46720. };
  46721. /**
  46722. * Return the active textures of the material.
  46723. */
  46724. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  46725. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46726. if (this.baseTexture) {
  46727. activeTextures.push(this.baseTexture);
  46728. }
  46729. if (this.metallicRoughnessTexture) {
  46730. activeTextures.push(this.metallicRoughnessTexture);
  46731. }
  46732. return activeTextures;
  46733. };
  46734. /**
  46735. * Checks to see if a texture is used in the material.
  46736. * @param texture - Base texture to use.
  46737. * @returns - Boolean specifying if a texture is used in the material.
  46738. */
  46739. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  46740. if (_super.prototype.hasTexture.call(this, texture)) {
  46741. return true;
  46742. }
  46743. if (this.baseTexture === texture) {
  46744. return true;
  46745. }
  46746. if (this.metallicRoughnessTexture === texture) {
  46747. return true;
  46748. }
  46749. return false;
  46750. };
  46751. /**
  46752. * Makes a duplicate of the current material.
  46753. * @param name - name to use for the new material.
  46754. */
  46755. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  46756. var _this = this;
  46757. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  46758. clone.id = name;
  46759. clone.name = name;
  46760. return clone;
  46761. };
  46762. /**
  46763. * Serialize the material to a parsable JSON object.
  46764. */
  46765. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  46766. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46767. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  46768. return serializationObject;
  46769. };
  46770. /**
  46771. * Parses a JSON object correponding to the serialize function.
  46772. */
  46773. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  46774. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  46775. };
  46776. __decorate([
  46777. BABYLON.serializeAsColor3(),
  46778. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46779. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  46780. __decorate([
  46781. BABYLON.serializeAsTexture(),
  46782. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46783. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  46784. __decorate([
  46785. BABYLON.serialize(),
  46786. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46787. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  46788. __decorate([
  46789. BABYLON.serialize(),
  46790. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  46791. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  46792. __decorate([
  46793. BABYLON.serializeAsTexture(),
  46794. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  46795. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  46796. return PBRMetallicRoughnessMaterial;
  46797. }(BABYLON.PBRBaseSimpleMaterial));
  46798. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  46799. })(BABYLON || (BABYLON = {}));
  46800. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  46801. var BABYLON;
  46802. (function (BABYLON) {
  46803. /**
  46804. * The PBR material of BJS following the specular glossiness convention.
  46805. *
  46806. * This fits to the PBR convention in the GLTF definition:
  46807. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  46808. */
  46809. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  46810. __extends(PBRSpecularGlossinessMaterial, _super);
  46811. /**
  46812. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46813. *
  46814. * @param name The material name
  46815. * @param scene The scene the material will be use in.
  46816. */
  46817. function PBRSpecularGlossinessMaterial(name, scene) {
  46818. var _this = _super.call(this, name, scene) || this;
  46819. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46820. return _this;
  46821. }
  46822. /**
  46823. * Return the currrent class name of the material.
  46824. */
  46825. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46826. return "PBRSpecularGlossinessMaterial";
  46827. };
  46828. /**
  46829. * Return the active textures of the material.
  46830. */
  46831. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46832. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46833. if (this.diffuseTexture) {
  46834. activeTextures.push(this.diffuseTexture);
  46835. }
  46836. if (this.specularGlossinessTexture) {
  46837. activeTextures.push(this.specularGlossinessTexture);
  46838. }
  46839. return activeTextures;
  46840. };
  46841. /**
  46842. * Checks to see if a texture is used in the material.
  46843. * @param texture - Base texture to use.
  46844. * @returns - Boolean specifying if a texture is used in the material.
  46845. */
  46846. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46847. if (_super.prototype.hasTexture.call(this, texture)) {
  46848. return true;
  46849. }
  46850. if (this.diffuseTexture === texture) {
  46851. return true;
  46852. }
  46853. if (this.specularGlossinessTexture === texture) {
  46854. return true;
  46855. }
  46856. return false;
  46857. };
  46858. /**
  46859. * Makes a duplicate of the current material.
  46860. * @param name - name to use for the new material.
  46861. */
  46862. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46863. var _this = this;
  46864. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46865. clone.id = name;
  46866. clone.name = name;
  46867. return clone;
  46868. };
  46869. /**
  46870. * Serialize the material to a parsable JSON object.
  46871. */
  46872. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46873. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46874. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46875. return serializationObject;
  46876. };
  46877. /**
  46878. * Parses a JSON object correponding to the serialize function.
  46879. */
  46880. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46881. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46882. };
  46883. __decorate([
  46884. BABYLON.serializeAsColor3("diffuse"),
  46885. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46886. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46887. __decorate([
  46888. BABYLON.serializeAsTexture(),
  46889. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46890. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46891. __decorate([
  46892. BABYLON.serializeAsColor3("specular"),
  46893. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46894. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46895. __decorate([
  46896. BABYLON.serialize(),
  46897. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46898. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46899. __decorate([
  46900. BABYLON.serializeAsTexture(),
  46901. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46902. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46903. return PBRSpecularGlossinessMaterial;
  46904. }(BABYLON.PBRBaseSimpleMaterial));
  46905. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46906. })(BABYLON || (BABYLON = {}));
  46907. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46908. var BABYLON;
  46909. (function (BABYLON) {
  46910. BABYLON.CameraInputTypes = {};
  46911. var CameraInputsManager = /** @class */ (function () {
  46912. function CameraInputsManager(camera) {
  46913. this.attached = {};
  46914. this.camera = camera;
  46915. this.checkInputs = function () { };
  46916. }
  46917. /**
  46918. * Add an input method to a camera.
  46919. * builtin inputs example: camera.inputs.addGamepad();
  46920. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46921. * @param input camera input method
  46922. */
  46923. CameraInputsManager.prototype.add = function (input) {
  46924. var type = input.getSimpleName();
  46925. if (this.attached[type]) {
  46926. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46927. return;
  46928. }
  46929. this.attached[type] = input;
  46930. input.camera = this.camera;
  46931. //for checkInputs, we are dynamically creating a function
  46932. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46933. if (input.checkInputs) {
  46934. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46935. }
  46936. if (this.attachedElement) {
  46937. input.attachControl(this.attachedElement);
  46938. }
  46939. };
  46940. /**
  46941. * Remove a specific input method from a camera
  46942. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46943. * @param inputToRemove camera input method
  46944. */
  46945. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46946. for (var cam in this.attached) {
  46947. var input = this.attached[cam];
  46948. if (input === inputToRemove) {
  46949. input.detachControl(this.attachedElement);
  46950. input.camera = null;
  46951. delete this.attached[cam];
  46952. this.rebuildInputCheck();
  46953. }
  46954. }
  46955. };
  46956. CameraInputsManager.prototype.removeByType = function (inputType) {
  46957. for (var cam in this.attached) {
  46958. var input = this.attached[cam];
  46959. if (input.getClassName() === inputType) {
  46960. input.detachControl(this.attachedElement);
  46961. input.camera = null;
  46962. delete this.attached[cam];
  46963. this.rebuildInputCheck();
  46964. }
  46965. }
  46966. };
  46967. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46968. var current = this.checkInputs;
  46969. return function () {
  46970. current();
  46971. fn();
  46972. };
  46973. };
  46974. CameraInputsManager.prototype.attachInput = function (input) {
  46975. if (this.attachedElement) {
  46976. input.attachControl(this.attachedElement, this.noPreventDefault);
  46977. }
  46978. };
  46979. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46980. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46981. if (this.attachedElement) {
  46982. return;
  46983. }
  46984. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46985. this.attachedElement = element;
  46986. this.noPreventDefault = noPreventDefault;
  46987. for (var cam in this.attached) {
  46988. this.attached[cam].attachControl(element, noPreventDefault);
  46989. }
  46990. };
  46991. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46992. if (disconnect === void 0) { disconnect = false; }
  46993. if (this.attachedElement !== element) {
  46994. return;
  46995. }
  46996. for (var cam in this.attached) {
  46997. this.attached[cam].detachControl(element);
  46998. if (disconnect) {
  46999. this.attached[cam].camera = null;
  47000. }
  47001. }
  47002. this.attachedElement = null;
  47003. };
  47004. CameraInputsManager.prototype.rebuildInputCheck = function () {
  47005. this.checkInputs = function () { };
  47006. for (var cam in this.attached) {
  47007. var input = this.attached[cam];
  47008. if (input.checkInputs) {
  47009. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  47010. }
  47011. }
  47012. };
  47013. /**
  47014. * Remove all attached input methods from a camera
  47015. */
  47016. CameraInputsManager.prototype.clear = function () {
  47017. if (this.attachedElement) {
  47018. this.detachElement(this.attachedElement, true);
  47019. }
  47020. this.attached = {};
  47021. this.attachedElement = null;
  47022. this.checkInputs = function () { };
  47023. };
  47024. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  47025. var inputs = {};
  47026. for (var cam in this.attached) {
  47027. var input = this.attached[cam];
  47028. var res = BABYLON.SerializationHelper.Serialize(input);
  47029. inputs[input.getClassName()] = res;
  47030. }
  47031. serializedCamera.inputsmgr = inputs;
  47032. };
  47033. CameraInputsManager.prototype.parse = function (parsedCamera) {
  47034. var parsedInputs = parsedCamera.inputsmgr;
  47035. if (parsedInputs) {
  47036. this.clear();
  47037. for (var n in parsedInputs) {
  47038. var construct = BABYLON.CameraInputTypes[n];
  47039. if (construct) {
  47040. var parsedinput = parsedInputs[n];
  47041. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  47042. this.add(input);
  47043. }
  47044. }
  47045. }
  47046. else {
  47047. //2016-03-08 this part is for managing backward compatibility
  47048. for (var n in this.attached) {
  47049. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  47050. if (construct) {
  47051. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  47052. this.remove(this.attached[n]);
  47053. this.add(input);
  47054. }
  47055. }
  47056. }
  47057. };
  47058. return CameraInputsManager;
  47059. }());
  47060. BABYLON.CameraInputsManager = CameraInputsManager;
  47061. })(BABYLON || (BABYLON = {}));
  47062. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  47063. var BABYLON;
  47064. (function (BABYLON) {
  47065. var TargetCamera = /** @class */ (function (_super) {
  47066. __extends(TargetCamera, _super);
  47067. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47068. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47069. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47070. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47071. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  47072. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  47073. _this.speed = 2.0;
  47074. _this.noRotationConstraint = false;
  47075. _this.lockedTarget = null;
  47076. _this._currentTarget = BABYLON.Vector3.Zero();
  47077. _this._viewMatrix = BABYLON.Matrix.Zero();
  47078. _this._camMatrix = BABYLON.Matrix.Zero();
  47079. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  47080. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  47081. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  47082. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  47083. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  47084. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  47085. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  47086. return _this;
  47087. }
  47088. TargetCamera.prototype.getFrontPosition = function (distance) {
  47089. this.getWorldMatrix();
  47090. var direction = this.getTarget().subtract(this.position);
  47091. direction.normalize();
  47092. direction.scaleInPlace(distance);
  47093. return this.globalPosition.add(direction);
  47094. };
  47095. TargetCamera.prototype._getLockedTargetPosition = function () {
  47096. if (!this.lockedTarget) {
  47097. return null;
  47098. }
  47099. if (this.lockedTarget.absolutePosition) {
  47100. this.lockedTarget.computeWorldMatrix();
  47101. }
  47102. return this.lockedTarget.absolutePosition || this.lockedTarget;
  47103. };
  47104. TargetCamera.prototype.storeState = function () {
  47105. this._storedPosition = this.position.clone();
  47106. this._storedRotation = this.rotation.clone();
  47107. if (this.rotationQuaternion) {
  47108. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  47109. }
  47110. return _super.prototype.storeState.call(this);
  47111. };
  47112. /**
  47113. * Restored camera state. You must call storeState() first
  47114. */
  47115. TargetCamera.prototype._restoreStateValues = function () {
  47116. if (!_super.prototype._restoreStateValues.call(this)) {
  47117. return false;
  47118. }
  47119. this.position = this._storedPosition.clone();
  47120. this.rotation = this._storedRotation.clone();
  47121. if (this.rotationQuaternion) {
  47122. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  47123. }
  47124. this.cameraDirection.copyFromFloats(0, 0, 0);
  47125. this.cameraRotation.copyFromFloats(0, 0);
  47126. return true;
  47127. };
  47128. // Cache
  47129. TargetCamera.prototype._initCache = function () {
  47130. _super.prototype._initCache.call(this);
  47131. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47132. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47133. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  47134. };
  47135. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  47136. if (!ignoreParentClass) {
  47137. _super.prototype._updateCache.call(this);
  47138. }
  47139. var lockedTargetPosition = this._getLockedTargetPosition();
  47140. if (!lockedTargetPosition) {
  47141. this._cache.lockedTarget = null;
  47142. }
  47143. else {
  47144. if (!this._cache.lockedTarget) {
  47145. this._cache.lockedTarget = lockedTargetPosition.clone();
  47146. }
  47147. else {
  47148. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  47149. }
  47150. }
  47151. this._cache.rotation.copyFrom(this.rotation);
  47152. if (this.rotationQuaternion)
  47153. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47154. };
  47155. // Synchronized
  47156. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  47157. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  47158. return false;
  47159. }
  47160. var lockedTargetPosition = this._getLockedTargetPosition();
  47161. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  47162. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  47163. };
  47164. // Methods
  47165. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  47166. var engine = this.getEngine();
  47167. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  47168. };
  47169. // Target
  47170. TargetCamera.prototype.setTarget = function (target) {
  47171. this.upVector.normalize();
  47172. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  47173. this._camMatrix.invert();
  47174. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  47175. var vDir = target.subtract(this.position);
  47176. if (vDir.x >= 0.0) {
  47177. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  47178. }
  47179. else {
  47180. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  47181. }
  47182. this.rotation.z = 0;
  47183. if (isNaN(this.rotation.x)) {
  47184. this.rotation.x = 0;
  47185. }
  47186. if (isNaN(this.rotation.y)) {
  47187. this.rotation.y = 0;
  47188. }
  47189. if (isNaN(this.rotation.z)) {
  47190. this.rotation.z = 0;
  47191. }
  47192. if (this.rotationQuaternion) {
  47193. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47194. }
  47195. };
  47196. /**
  47197. * Return the current target position of the camera. This value is expressed in local space.
  47198. */
  47199. TargetCamera.prototype.getTarget = function () {
  47200. return this._currentTarget;
  47201. };
  47202. TargetCamera.prototype._decideIfNeedsToMove = function () {
  47203. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47204. };
  47205. TargetCamera.prototype._updatePosition = function () {
  47206. if (this.parent) {
  47207. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  47208. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  47209. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  47210. return;
  47211. }
  47212. this.position.addInPlace(this.cameraDirection);
  47213. };
  47214. TargetCamera.prototype._checkInputs = function () {
  47215. var needToMove = this._decideIfNeedsToMove();
  47216. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  47217. // Move
  47218. if (needToMove) {
  47219. this._updatePosition();
  47220. }
  47221. // Rotate
  47222. if (needToRotate) {
  47223. this.rotation.x += this.cameraRotation.x;
  47224. this.rotation.y += this.cameraRotation.y;
  47225. //rotate, if quaternion is set and rotation was used
  47226. if (this.rotationQuaternion) {
  47227. var len = this.rotation.lengthSquared();
  47228. if (len) {
  47229. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  47230. }
  47231. }
  47232. if (!this.noRotationConstraint) {
  47233. var limit = (Math.PI / 2) * 0.95;
  47234. if (this.rotation.x > limit)
  47235. this.rotation.x = limit;
  47236. if (this.rotation.x < -limit)
  47237. this.rotation.x = -limit;
  47238. }
  47239. }
  47240. // Inertia
  47241. if (needToMove) {
  47242. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  47243. this.cameraDirection.x = 0;
  47244. }
  47245. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  47246. this.cameraDirection.y = 0;
  47247. }
  47248. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  47249. this.cameraDirection.z = 0;
  47250. }
  47251. this.cameraDirection.scaleInPlace(this.inertia);
  47252. }
  47253. if (needToRotate) {
  47254. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  47255. this.cameraRotation.x = 0;
  47256. }
  47257. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  47258. this.cameraRotation.y = 0;
  47259. }
  47260. this.cameraRotation.scaleInPlace(this.inertia);
  47261. }
  47262. _super.prototype._checkInputs.call(this);
  47263. };
  47264. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  47265. if (this.rotationQuaternion) {
  47266. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  47267. }
  47268. else {
  47269. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  47270. }
  47271. //update the up vector!
  47272. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  47273. };
  47274. TargetCamera.prototype._getViewMatrix = function () {
  47275. if (this.lockedTarget) {
  47276. this.setTarget(this._getLockedTargetPosition());
  47277. }
  47278. // Compute
  47279. this._updateCameraRotationMatrix();
  47280. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  47281. // Computing target and final matrix
  47282. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  47283. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  47284. return this._viewMatrix;
  47285. };
  47286. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  47287. if (this.parent) {
  47288. var parentWorldMatrix = this.parent.getWorldMatrix();
  47289. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  47290. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  47291. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  47292. this._markSyncedWithParent();
  47293. }
  47294. else {
  47295. this._globalPosition.copyFrom(this.position);
  47296. this._globalCurrentTarget.copyFrom(target);
  47297. this._globalCurrentUpVector.copyFrom(up);
  47298. }
  47299. if (this.getScene().useRightHandedSystem) {
  47300. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47301. }
  47302. else {
  47303. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  47304. }
  47305. };
  47306. /**
  47307. * @override
  47308. * Override Camera.createRigCamera
  47309. */
  47310. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  47311. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  47312. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  47313. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  47314. if (!this.rotationQuaternion) {
  47315. this.rotationQuaternion = new BABYLON.Quaternion();
  47316. }
  47317. rigCamera._cameraRigParams = {};
  47318. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  47319. }
  47320. return rigCamera;
  47321. }
  47322. return null;
  47323. };
  47324. /**
  47325. * @override
  47326. * Override Camera._updateRigCameras
  47327. */
  47328. TargetCamera.prototype._updateRigCameras = function () {
  47329. var camLeft = this._rigCameras[0];
  47330. var camRight = this._rigCameras[1];
  47331. switch (this.cameraRigMode) {
  47332. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  47333. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  47334. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  47335. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  47336. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  47337. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  47338. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  47339. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  47340. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  47341. camLeft.setTarget(this.getTarget());
  47342. camRight.setTarget(this.getTarget());
  47343. break;
  47344. case BABYLON.Camera.RIG_MODE_VR:
  47345. if (camLeft.rotationQuaternion) {
  47346. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47347. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  47348. }
  47349. else {
  47350. camLeft.rotation.copyFrom(this.rotation);
  47351. camRight.rotation.copyFrom(this.rotation);
  47352. }
  47353. camLeft.position.copyFrom(this.position);
  47354. camRight.position.copyFrom(this.position);
  47355. break;
  47356. }
  47357. _super.prototype._updateRigCameras.call(this);
  47358. };
  47359. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  47360. if (!this._rigCamTransformMatrix) {
  47361. this._rigCamTransformMatrix = new BABYLON.Matrix();
  47362. }
  47363. var target = this.getTarget();
  47364. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  47365. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  47366. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  47367. };
  47368. TargetCamera.prototype.getClassName = function () {
  47369. return "TargetCamera";
  47370. };
  47371. __decorate([
  47372. BABYLON.serializeAsVector3()
  47373. ], TargetCamera.prototype, "rotation", void 0);
  47374. __decorate([
  47375. BABYLON.serialize()
  47376. ], TargetCamera.prototype, "speed", void 0);
  47377. __decorate([
  47378. BABYLON.serializeAsMeshReference("lockedTargetId")
  47379. ], TargetCamera.prototype, "lockedTarget", void 0);
  47380. return TargetCamera;
  47381. }(BABYLON.Camera));
  47382. BABYLON.TargetCamera = TargetCamera;
  47383. })(BABYLON || (BABYLON = {}));
  47384. //# sourceMappingURL=babylon.targetCamera.js.map
  47385. var BABYLON;
  47386. (function (BABYLON) {
  47387. var FreeCameraMouseInput = /** @class */ (function () {
  47388. function FreeCameraMouseInput(touchEnabled) {
  47389. if (touchEnabled === void 0) { touchEnabled = true; }
  47390. this.touchEnabled = touchEnabled;
  47391. this.buttons = [0, 1, 2];
  47392. this.angularSensibility = 2000.0;
  47393. this.previousPosition = null;
  47394. }
  47395. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  47396. var _this = this;
  47397. var engine = this.camera.getEngine();
  47398. if (!this._pointerInput) {
  47399. this._pointerInput = function (p, s) {
  47400. var evt = p.event;
  47401. if (engine.isInVRExclusivePointerMode) {
  47402. return;
  47403. }
  47404. if (!_this.touchEnabled && evt.pointerType === "touch") {
  47405. return;
  47406. }
  47407. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47408. return;
  47409. }
  47410. var srcElement = (evt.srcElement || evt.target);
  47411. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47412. try {
  47413. srcElement.setPointerCapture(evt.pointerId);
  47414. }
  47415. catch (e) {
  47416. //Nothing to do with the error. Execution will continue.
  47417. }
  47418. _this.previousPosition = {
  47419. x: evt.clientX,
  47420. y: evt.clientY
  47421. };
  47422. if (!noPreventDefault) {
  47423. evt.preventDefault();
  47424. element.focus();
  47425. }
  47426. }
  47427. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47428. try {
  47429. srcElement.releasePointerCapture(evt.pointerId);
  47430. }
  47431. catch (e) {
  47432. //Nothing to do with the error.
  47433. }
  47434. _this.previousPosition = null;
  47435. if (!noPreventDefault) {
  47436. evt.preventDefault();
  47437. }
  47438. }
  47439. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47440. if (!_this.previousPosition || engine.isPointerLock) {
  47441. return;
  47442. }
  47443. var offsetX = evt.clientX - _this.previousPosition.x;
  47444. if (_this.camera.getScene().useRightHandedSystem)
  47445. offsetX *= -1;
  47446. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47447. offsetX *= -1;
  47448. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47449. var offsetY = evt.clientY - _this.previousPosition.y;
  47450. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47451. _this.previousPosition = {
  47452. x: evt.clientX,
  47453. y: evt.clientY
  47454. };
  47455. if (!noPreventDefault) {
  47456. evt.preventDefault();
  47457. }
  47458. }
  47459. };
  47460. }
  47461. this._onMouseMove = function (evt) {
  47462. if (!engine.isPointerLock) {
  47463. return;
  47464. }
  47465. if (engine.isInVRExclusivePointerMode) {
  47466. return;
  47467. }
  47468. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47469. if (_this.camera.getScene().useRightHandedSystem)
  47470. offsetX *= -1;
  47471. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  47472. offsetX *= -1;
  47473. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  47474. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47475. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  47476. _this.previousPosition = null;
  47477. if (!noPreventDefault) {
  47478. evt.preventDefault();
  47479. }
  47480. };
  47481. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  47482. element.addEventListener("mousemove", this._onMouseMove, false);
  47483. };
  47484. FreeCameraMouseInput.prototype.detachControl = function (element) {
  47485. if (this._observer && element) {
  47486. this.camera.getScene().onPointerObservable.remove(this._observer);
  47487. if (this._onMouseMove) {
  47488. element.removeEventListener("mousemove", this._onMouseMove);
  47489. }
  47490. this._observer = null;
  47491. this._onMouseMove = null;
  47492. this.previousPosition = null;
  47493. }
  47494. };
  47495. FreeCameraMouseInput.prototype.getClassName = function () {
  47496. return "FreeCameraMouseInput";
  47497. };
  47498. FreeCameraMouseInput.prototype.getSimpleName = function () {
  47499. return "mouse";
  47500. };
  47501. __decorate([
  47502. BABYLON.serialize()
  47503. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  47504. __decorate([
  47505. BABYLON.serialize()
  47506. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  47507. return FreeCameraMouseInput;
  47508. }());
  47509. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  47510. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  47511. })(BABYLON || (BABYLON = {}));
  47512. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  47513. var BABYLON;
  47514. (function (BABYLON) {
  47515. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  47516. function FreeCameraKeyboardMoveInput() {
  47517. this._keys = new Array();
  47518. this.keysUp = [38];
  47519. this.keysDown = [40];
  47520. this.keysLeft = [37];
  47521. this.keysRight = [39];
  47522. }
  47523. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47524. var _this = this;
  47525. if (this._onCanvasBlurObserver) {
  47526. return;
  47527. }
  47528. this._scene = this.camera.getScene();
  47529. this._engine = this._scene.getEngine();
  47530. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47531. _this._keys = [];
  47532. });
  47533. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47534. var evt = info.event;
  47535. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47536. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47537. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47538. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47539. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47540. var index = _this._keys.indexOf(evt.keyCode);
  47541. if (index === -1) {
  47542. _this._keys.push(evt.keyCode);
  47543. }
  47544. if (!noPreventDefault) {
  47545. evt.preventDefault();
  47546. }
  47547. }
  47548. }
  47549. else {
  47550. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47551. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47552. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47553. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  47554. var index = _this._keys.indexOf(evt.keyCode);
  47555. if (index >= 0) {
  47556. _this._keys.splice(index, 1);
  47557. }
  47558. if (!noPreventDefault) {
  47559. evt.preventDefault();
  47560. }
  47561. }
  47562. }
  47563. });
  47564. };
  47565. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47566. if (this._scene) {
  47567. if (this._onKeyboardObserver) {
  47568. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47569. }
  47570. if (this._onCanvasBlurObserver) {
  47571. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47572. }
  47573. this._onKeyboardObserver = null;
  47574. this._onCanvasBlurObserver = null;
  47575. }
  47576. this._keys = [];
  47577. };
  47578. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47579. if (this._onKeyboardObserver) {
  47580. var camera = this.camera;
  47581. // Keyboard
  47582. for (var index = 0; index < this._keys.length; index++) {
  47583. var keyCode = this._keys[index];
  47584. var speed = camera._computeLocalCameraSpeed();
  47585. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47586. camera._localDirection.copyFromFloats(-speed, 0, 0);
  47587. }
  47588. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47589. camera._localDirection.copyFromFloats(0, 0, speed);
  47590. }
  47591. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47592. camera._localDirection.copyFromFloats(speed, 0, 0);
  47593. }
  47594. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47595. camera._localDirection.copyFromFloats(0, 0, -speed);
  47596. }
  47597. if (camera.getScene().useRightHandedSystem) {
  47598. camera._localDirection.z *= -1;
  47599. }
  47600. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  47601. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  47602. camera.cameraDirection.addInPlace(camera._transformedDirection);
  47603. }
  47604. }
  47605. };
  47606. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  47607. return "FreeCameraKeyboardMoveInput";
  47608. };
  47609. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  47610. this._keys = [];
  47611. };
  47612. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47613. return "keyboard";
  47614. };
  47615. __decorate([
  47616. BABYLON.serialize()
  47617. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47618. __decorate([
  47619. BABYLON.serialize()
  47620. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47621. __decorate([
  47622. BABYLON.serialize()
  47623. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47624. __decorate([
  47625. BABYLON.serialize()
  47626. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47627. return FreeCameraKeyboardMoveInput;
  47628. }());
  47629. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  47630. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  47631. })(BABYLON || (BABYLON = {}));
  47632. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  47633. var BABYLON;
  47634. (function (BABYLON) {
  47635. var FreeCameraInputsManager = /** @class */ (function (_super) {
  47636. __extends(FreeCameraInputsManager, _super);
  47637. function FreeCameraInputsManager(camera) {
  47638. return _super.call(this, camera) || this;
  47639. }
  47640. FreeCameraInputsManager.prototype.addKeyboard = function () {
  47641. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  47642. return this;
  47643. };
  47644. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  47645. if (touchEnabled === void 0) { touchEnabled = true; }
  47646. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  47647. return this;
  47648. };
  47649. FreeCameraInputsManager.prototype.addGamepad = function () {
  47650. this.add(new BABYLON.FreeCameraGamepadInput());
  47651. return this;
  47652. };
  47653. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  47654. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  47655. return this;
  47656. };
  47657. FreeCameraInputsManager.prototype.addTouch = function () {
  47658. this.add(new BABYLON.FreeCameraTouchInput());
  47659. return this;
  47660. };
  47661. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  47662. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  47663. return this;
  47664. };
  47665. return FreeCameraInputsManager;
  47666. }(BABYLON.CameraInputsManager));
  47667. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  47668. })(BABYLON || (BABYLON = {}));
  47669. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  47670. var BABYLON;
  47671. (function (BABYLON) {
  47672. var FreeCamera = /** @class */ (function (_super) {
  47673. __extends(FreeCamera, _super);
  47674. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  47675. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47676. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  47677. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  47678. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  47679. _this.checkCollisions = false;
  47680. _this.applyGravity = false;
  47681. _this._needMoveForGravity = false;
  47682. _this._oldPosition = BABYLON.Vector3.Zero();
  47683. _this._diffPosition = BABYLON.Vector3.Zero();
  47684. _this._newPosition = BABYLON.Vector3.Zero();
  47685. // Collisions
  47686. _this._collisionMask = -1;
  47687. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47688. if (collidedMesh === void 0) { collidedMesh = null; }
  47689. //TODO move this to the collision coordinator!
  47690. if (_this.getScene().workerCollisions)
  47691. newPosition.multiplyInPlace(_this._collider._radius);
  47692. var updatePosition = function (newPos) {
  47693. _this._newPosition.copyFrom(newPos);
  47694. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  47695. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  47696. _this.position.addInPlace(_this._diffPosition);
  47697. if (_this.onCollide && collidedMesh) {
  47698. _this.onCollide(collidedMesh);
  47699. }
  47700. }
  47701. };
  47702. updatePosition(newPosition);
  47703. };
  47704. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  47705. _this.inputs.addKeyboard().addMouse();
  47706. return _this;
  47707. }
  47708. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  47709. //-- begin properties for backward compatibility for inputs
  47710. /**
  47711. * Gets the input sensibility for a mouse input. (default is 2000.0)
  47712. * Higher values reduce sensitivity.
  47713. */
  47714. get: function () {
  47715. var mouse = this.inputs.attached["mouse"];
  47716. if (mouse)
  47717. return mouse.angularSensibility;
  47718. return 0;
  47719. },
  47720. /**
  47721. * Sets the input sensibility for a mouse input. (default is 2000.0)
  47722. * Higher values reduce sensitivity.
  47723. */
  47724. set: function (value) {
  47725. var mouse = this.inputs.attached["mouse"];
  47726. if (mouse)
  47727. mouse.angularSensibility = value;
  47728. },
  47729. enumerable: true,
  47730. configurable: true
  47731. });
  47732. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  47733. get: function () {
  47734. var keyboard = this.inputs.attached["keyboard"];
  47735. if (keyboard)
  47736. return keyboard.keysUp;
  47737. return [];
  47738. },
  47739. set: function (value) {
  47740. var keyboard = this.inputs.attached["keyboard"];
  47741. if (keyboard)
  47742. keyboard.keysUp = value;
  47743. },
  47744. enumerable: true,
  47745. configurable: true
  47746. });
  47747. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  47748. get: function () {
  47749. var keyboard = this.inputs.attached["keyboard"];
  47750. if (keyboard)
  47751. return keyboard.keysDown;
  47752. return [];
  47753. },
  47754. set: function (value) {
  47755. var keyboard = this.inputs.attached["keyboard"];
  47756. if (keyboard)
  47757. keyboard.keysDown = value;
  47758. },
  47759. enumerable: true,
  47760. configurable: true
  47761. });
  47762. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  47763. get: function () {
  47764. var keyboard = this.inputs.attached["keyboard"];
  47765. if (keyboard)
  47766. return keyboard.keysLeft;
  47767. return [];
  47768. },
  47769. set: function (value) {
  47770. var keyboard = this.inputs.attached["keyboard"];
  47771. if (keyboard)
  47772. keyboard.keysLeft = value;
  47773. },
  47774. enumerable: true,
  47775. configurable: true
  47776. });
  47777. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  47778. get: function () {
  47779. var keyboard = this.inputs.attached["keyboard"];
  47780. if (keyboard)
  47781. return keyboard.keysRight;
  47782. return [];
  47783. },
  47784. set: function (value) {
  47785. var keyboard = this.inputs.attached["keyboard"];
  47786. if (keyboard)
  47787. keyboard.keysRight = value;
  47788. },
  47789. enumerable: true,
  47790. configurable: true
  47791. });
  47792. // Controls
  47793. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  47794. this.inputs.attachElement(element, noPreventDefault);
  47795. };
  47796. FreeCamera.prototype.detachControl = function (element) {
  47797. this.inputs.detachElement(element);
  47798. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  47799. this.cameraRotation = new BABYLON.Vector2(0, 0);
  47800. };
  47801. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  47802. get: function () {
  47803. return this._collisionMask;
  47804. },
  47805. set: function (mask) {
  47806. this._collisionMask = !isNaN(mask) ? mask : -1;
  47807. },
  47808. enumerable: true,
  47809. configurable: true
  47810. });
  47811. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47812. var globalPosition;
  47813. if (this.parent) {
  47814. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47815. }
  47816. else {
  47817. globalPosition = this.position;
  47818. }
  47819. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47820. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47821. if (!this._collider) {
  47822. this._collider = new BABYLON.Collider();
  47823. }
  47824. this._collider._radius = this.ellipsoid;
  47825. this._collider.collisionMask = this._collisionMask;
  47826. //no need for clone, as long as gravity is not on.
  47827. var actualDisplacement = displacement;
  47828. //add gravity to the direction to prevent the dual-collision checking
  47829. if (this.applyGravity) {
  47830. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47831. actualDisplacement = displacement.add(this.getScene().gravity);
  47832. }
  47833. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47834. };
  47835. FreeCamera.prototype._checkInputs = function () {
  47836. if (!this._localDirection) {
  47837. this._localDirection = BABYLON.Vector3.Zero();
  47838. this._transformedDirection = BABYLON.Vector3.Zero();
  47839. }
  47840. this.inputs.checkInputs();
  47841. _super.prototype._checkInputs.call(this);
  47842. };
  47843. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47844. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47845. };
  47846. FreeCamera.prototype._updatePosition = function () {
  47847. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47848. this._collideWithWorld(this.cameraDirection);
  47849. }
  47850. else {
  47851. _super.prototype._updatePosition.call(this);
  47852. }
  47853. };
  47854. FreeCamera.prototype.dispose = function () {
  47855. this.inputs.clear();
  47856. _super.prototype.dispose.call(this);
  47857. };
  47858. FreeCamera.prototype.getClassName = function () {
  47859. return "FreeCamera";
  47860. };
  47861. __decorate([
  47862. BABYLON.serializeAsVector3()
  47863. ], FreeCamera.prototype, "ellipsoid", void 0);
  47864. __decorate([
  47865. BABYLON.serializeAsVector3()
  47866. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47867. __decorate([
  47868. BABYLON.serialize()
  47869. ], FreeCamera.prototype, "checkCollisions", void 0);
  47870. __decorate([
  47871. BABYLON.serialize()
  47872. ], FreeCamera.prototype, "applyGravity", void 0);
  47873. return FreeCamera;
  47874. }(BABYLON.TargetCamera));
  47875. BABYLON.FreeCamera = FreeCamera;
  47876. })(BABYLON || (BABYLON = {}));
  47877. //# sourceMappingURL=babylon.freeCamera.js.map
  47878. var BABYLON;
  47879. (function (BABYLON) {
  47880. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47881. function ArcRotateCameraKeyboardMoveInput() {
  47882. this._keys = new Array();
  47883. this.keysUp = [38];
  47884. this.keysDown = [40];
  47885. this.keysLeft = [37];
  47886. this.keysRight = [39];
  47887. this.keysReset = [220];
  47888. this.panningSensibility = 50.0;
  47889. this.zoomingSensibility = 25.0;
  47890. this.useAltToZoom = true;
  47891. }
  47892. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47893. var _this = this;
  47894. if (this._onCanvasBlurObserver) {
  47895. return;
  47896. }
  47897. this._scene = this.camera.getScene();
  47898. this._engine = this._scene.getEngine();
  47899. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47900. _this._keys = [];
  47901. });
  47902. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47903. var evt = info.event;
  47904. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47905. _this._ctrlPressed = evt.ctrlKey;
  47906. _this._altPressed = evt.altKey;
  47907. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47908. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47909. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47910. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47911. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47912. var index = _this._keys.indexOf(evt.keyCode);
  47913. if (index === -1) {
  47914. _this._keys.push(evt.keyCode);
  47915. }
  47916. if (evt.preventDefault) {
  47917. if (!noPreventDefault) {
  47918. evt.preventDefault();
  47919. }
  47920. }
  47921. }
  47922. }
  47923. else {
  47924. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47925. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47926. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47927. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47928. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47929. var index = _this._keys.indexOf(evt.keyCode);
  47930. if (index >= 0) {
  47931. _this._keys.splice(index, 1);
  47932. }
  47933. if (evt.preventDefault) {
  47934. if (!noPreventDefault) {
  47935. evt.preventDefault();
  47936. }
  47937. }
  47938. }
  47939. }
  47940. });
  47941. };
  47942. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47943. if (this._scene) {
  47944. if (this._onKeyboardObserver) {
  47945. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47946. }
  47947. if (this._onCanvasBlurObserver) {
  47948. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47949. }
  47950. this._onKeyboardObserver = null;
  47951. this._onCanvasBlurObserver = null;
  47952. }
  47953. this._keys = [];
  47954. };
  47955. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47956. if (this._onKeyboardObserver) {
  47957. var camera = this.camera;
  47958. for (var index = 0; index < this._keys.length; index++) {
  47959. var keyCode = this._keys[index];
  47960. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47961. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47962. camera.inertialPanningX -= 1 / this.panningSensibility;
  47963. }
  47964. else {
  47965. camera.inertialAlphaOffset -= 0.01;
  47966. }
  47967. }
  47968. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47969. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47970. camera.inertialPanningY += 1 / this.panningSensibility;
  47971. }
  47972. else if (this._altPressed && this.useAltToZoom) {
  47973. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47974. }
  47975. else {
  47976. camera.inertialBetaOffset -= 0.01;
  47977. }
  47978. }
  47979. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47980. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47981. camera.inertialPanningX += 1 / this.panningSensibility;
  47982. }
  47983. else {
  47984. camera.inertialAlphaOffset += 0.01;
  47985. }
  47986. }
  47987. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47988. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47989. camera.inertialPanningY -= 1 / this.panningSensibility;
  47990. }
  47991. else if (this._altPressed && this.useAltToZoom) {
  47992. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47993. }
  47994. else {
  47995. camera.inertialBetaOffset += 0.01;
  47996. }
  47997. }
  47998. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47999. camera.restoreState();
  48000. }
  48001. }
  48002. }
  48003. };
  48004. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  48005. return "ArcRotateCameraKeyboardMoveInput";
  48006. };
  48007. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  48008. return "keyboard";
  48009. };
  48010. __decorate([
  48011. BABYLON.serialize()
  48012. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  48013. __decorate([
  48014. BABYLON.serialize()
  48015. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  48016. __decorate([
  48017. BABYLON.serialize()
  48018. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  48019. __decorate([
  48020. BABYLON.serialize()
  48021. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  48022. __decorate([
  48023. BABYLON.serialize()
  48024. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  48025. __decorate([
  48026. BABYLON.serialize()
  48027. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  48028. __decorate([
  48029. BABYLON.serialize()
  48030. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  48031. __decorate([
  48032. BABYLON.serialize()
  48033. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  48034. return ArcRotateCameraKeyboardMoveInput;
  48035. }());
  48036. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  48037. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  48038. })(BABYLON || (BABYLON = {}));
  48039. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  48040. var BABYLON;
  48041. (function (BABYLON) {
  48042. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  48043. function ArcRotateCameraMouseWheelInput() {
  48044. this.wheelPrecision = 3.0;
  48045. /**
  48046. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  48047. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  48048. */
  48049. this.wheelDeltaPercentage = 0;
  48050. }
  48051. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  48052. var _this = this;
  48053. this._wheel = function (p, s) {
  48054. //sanity check - this should be a PointerWheel event.
  48055. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  48056. return;
  48057. var event = p.event;
  48058. var delta = 0;
  48059. if (event.wheelDelta) {
  48060. if (_this.wheelDeltaPercentage) {
  48061. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  48062. if (event.wheelDelta > 0) {
  48063. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  48064. }
  48065. else {
  48066. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  48067. }
  48068. }
  48069. else {
  48070. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  48071. }
  48072. }
  48073. else if (event.detail) {
  48074. delta = -event.detail / _this.wheelPrecision;
  48075. }
  48076. if (delta)
  48077. _this.camera.inertialRadiusOffset += delta;
  48078. if (event.preventDefault) {
  48079. if (!noPreventDefault) {
  48080. event.preventDefault();
  48081. }
  48082. }
  48083. };
  48084. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  48085. };
  48086. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  48087. if (this._observer && element) {
  48088. this.camera.getScene().onPointerObservable.remove(this._observer);
  48089. this._observer = null;
  48090. this._wheel = null;
  48091. }
  48092. };
  48093. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  48094. return "ArcRotateCameraMouseWheelInput";
  48095. };
  48096. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  48097. return "mousewheel";
  48098. };
  48099. __decorate([
  48100. BABYLON.serialize()
  48101. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  48102. __decorate([
  48103. BABYLON.serialize()
  48104. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  48105. return ArcRotateCameraMouseWheelInput;
  48106. }());
  48107. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  48108. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  48109. })(BABYLON || (BABYLON = {}));
  48110. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  48111. var BABYLON;
  48112. (function (BABYLON) {
  48113. var ArcRotateCameraPointersInput = /** @class */ (function () {
  48114. function ArcRotateCameraPointersInput() {
  48115. this.buttons = [0, 1, 2];
  48116. this.angularSensibilityX = 1000.0;
  48117. this.angularSensibilityY = 1000.0;
  48118. this.pinchPrecision = 12.0;
  48119. /**
  48120. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  48121. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  48122. */
  48123. this.pinchDeltaPercentage = 0;
  48124. this.panningSensibility = 1000.0;
  48125. this.multiTouchPanning = true;
  48126. this.multiTouchPanAndZoom = true;
  48127. this._isPanClick = false;
  48128. this.pinchInwards = true;
  48129. }
  48130. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  48131. var _this = this;
  48132. var engine = this.camera.getEngine();
  48133. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  48134. var pointA = null;
  48135. var pointB = null;
  48136. var previousPinchSquaredDistance = 0;
  48137. var initialDistance = 0;
  48138. var twoFingerActivityCount = 0;
  48139. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  48140. this._pointerInput = function (p, s) {
  48141. var evt = p.event;
  48142. var isTouch = p.event.pointerType === "touch";
  48143. if (engine.isInVRExclusivePointerMode) {
  48144. return;
  48145. }
  48146. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  48147. return;
  48148. }
  48149. var srcElement = (evt.srcElement || evt.target);
  48150. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  48151. try {
  48152. srcElement.setPointerCapture(evt.pointerId);
  48153. }
  48154. catch (e) {
  48155. //Nothing to do with the error. Execution will continue.
  48156. }
  48157. // Manage panning with pan button click
  48158. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  48159. // manage pointers
  48160. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  48161. if (pointA === null) {
  48162. pointA = cacheSoloPointer;
  48163. }
  48164. else if (pointB === null) {
  48165. pointB = cacheSoloPointer;
  48166. }
  48167. if (!noPreventDefault) {
  48168. evt.preventDefault();
  48169. element.focus();
  48170. }
  48171. }
  48172. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  48173. _this.camera.restoreState();
  48174. }
  48175. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  48176. try {
  48177. srcElement.releasePointerCapture(evt.pointerId);
  48178. }
  48179. catch (e) {
  48180. //Nothing to do with the error.
  48181. }
  48182. cacheSoloPointer = null;
  48183. previousPinchSquaredDistance = 0;
  48184. previousMultiTouchPanPosition.isPaning = false;
  48185. previousMultiTouchPanPosition.isPinching = false;
  48186. twoFingerActivityCount = 0;
  48187. initialDistance = 0;
  48188. if (!isTouch) {
  48189. pointB = null; // Mouse and pen are mono pointer
  48190. }
  48191. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  48192. //but emptying completly pointers collection is required to fix a bug on iPhone :
  48193. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  48194. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  48195. if (engine._badOS) {
  48196. pointA = pointB = null;
  48197. }
  48198. else {
  48199. //only remove the impacted pointer in case of multitouch allowing on most
  48200. //platforms switching from rotate to zoom and pan seamlessly.
  48201. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  48202. pointA = pointB;
  48203. pointB = null;
  48204. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48205. }
  48206. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  48207. pointB = null;
  48208. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  48209. }
  48210. else {
  48211. pointA = pointB = null;
  48212. }
  48213. }
  48214. if (!noPreventDefault) {
  48215. evt.preventDefault();
  48216. }
  48217. }
  48218. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  48219. if (!noPreventDefault) {
  48220. evt.preventDefault();
  48221. }
  48222. // One button down
  48223. if (pointA && pointB === null && cacheSoloPointer) {
  48224. if (_this.panningSensibility !== 0 &&
  48225. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  48226. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  48227. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  48228. }
  48229. else {
  48230. var offsetX = evt.clientX - cacheSoloPointer.x;
  48231. var offsetY = evt.clientY - cacheSoloPointer.y;
  48232. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48233. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48234. }
  48235. cacheSoloPointer.x = evt.clientX;
  48236. cacheSoloPointer.y = evt.clientY;
  48237. }
  48238. // Two buttons down: pinch/pan
  48239. else if (pointA && pointB) {
  48240. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  48241. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  48242. ed.x = evt.clientX;
  48243. ed.y = evt.clientY;
  48244. var direction = _this.pinchInwards ? 1 : -1;
  48245. var distX = pointA.x - pointB.x;
  48246. var distY = pointA.y - pointB.y;
  48247. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  48248. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  48249. if (previousPinchSquaredDistance === 0) {
  48250. initialDistance = pinchDistance;
  48251. previousPinchSquaredDistance = pinchSquaredDistance;
  48252. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  48253. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  48254. return;
  48255. }
  48256. if (_this.multiTouchPanAndZoom) {
  48257. if (_this.pinchDeltaPercentage) {
  48258. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48259. }
  48260. else {
  48261. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48262. (_this.pinchPrecision *
  48263. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48264. direction);
  48265. }
  48266. if (_this.panningSensibility !== 0) {
  48267. var pointersCenterX = (pointA.x + pointB.x) / 2;
  48268. var pointersCenterY = (pointA.y + pointB.y) / 2;
  48269. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  48270. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  48271. previousMultiTouchPanPosition.x = pointersCenterX;
  48272. previousMultiTouchPanPosition.y = pointersCenterY;
  48273. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  48274. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  48275. }
  48276. }
  48277. else {
  48278. twoFingerActivityCount++;
  48279. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  48280. if (_this.pinchDeltaPercentage) {
  48281. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  48282. }
  48283. else {
  48284. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  48285. (_this.pinchPrecision *
  48286. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  48287. direction);
  48288. }
  48289. previousMultiTouchPanPosition.isPaning = false;
  48290. previousMultiTouchPanPosition.isPinching = true;
  48291. }
  48292. else {
  48293. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  48294. if (!previousMultiTouchPanPosition.isPaning) {
  48295. previousMultiTouchPanPosition.isPaning = true;
  48296. previousMultiTouchPanPosition.isPinching = false;
  48297. previousMultiTouchPanPosition.x = ed.x;
  48298. previousMultiTouchPanPosition.y = ed.y;
  48299. return;
  48300. }
  48301. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  48302. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  48303. }
  48304. }
  48305. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  48306. previousMultiTouchPanPosition.x = ed.x;
  48307. previousMultiTouchPanPosition.y = ed.y;
  48308. }
  48309. }
  48310. previousPinchSquaredDistance = pinchSquaredDistance;
  48311. }
  48312. }
  48313. };
  48314. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  48315. this._onContextMenu = function (evt) {
  48316. evt.preventDefault();
  48317. };
  48318. if (!this.camera._useCtrlForPanning) {
  48319. element.addEventListener("contextmenu", this._onContextMenu, false);
  48320. }
  48321. this._onLostFocus = function () {
  48322. //this._keys = [];
  48323. pointA = pointB = null;
  48324. previousPinchSquaredDistance = 0;
  48325. previousMultiTouchPanPosition.isPaning = false;
  48326. previousMultiTouchPanPosition.isPinching = false;
  48327. twoFingerActivityCount = 0;
  48328. cacheSoloPointer = null;
  48329. initialDistance = 0;
  48330. };
  48331. this._onMouseMove = function (evt) {
  48332. if (!engine.isPointerLock) {
  48333. return;
  48334. }
  48335. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  48336. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  48337. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  48338. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  48339. if (!noPreventDefault) {
  48340. evt.preventDefault();
  48341. }
  48342. };
  48343. this._onGestureStart = function (e) {
  48344. if (window.MSGesture === undefined) {
  48345. return;
  48346. }
  48347. if (!_this._MSGestureHandler) {
  48348. _this._MSGestureHandler = new MSGesture();
  48349. _this._MSGestureHandler.target = element;
  48350. }
  48351. _this._MSGestureHandler.addPointer(e.pointerId);
  48352. };
  48353. this._onGesture = function (e) {
  48354. _this.camera.radius *= e.scale;
  48355. if (e.preventDefault) {
  48356. if (!noPreventDefault) {
  48357. e.stopPropagation();
  48358. e.preventDefault();
  48359. }
  48360. }
  48361. };
  48362. element.addEventListener("mousemove", this._onMouseMove, false);
  48363. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  48364. element.addEventListener("MSGestureChange", this._onGesture, false);
  48365. BABYLON.Tools.RegisterTopRootEvents([
  48366. { name: "blur", handler: this._onLostFocus }
  48367. ]);
  48368. };
  48369. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  48370. if (this._onLostFocus) {
  48371. BABYLON.Tools.UnregisterTopRootEvents([
  48372. { name: "blur", handler: this._onLostFocus }
  48373. ]);
  48374. }
  48375. if (element && this._observer) {
  48376. this.camera.getScene().onPointerObservable.remove(this._observer);
  48377. this._observer = null;
  48378. if (this._onContextMenu) {
  48379. element.removeEventListener("contextmenu", this._onContextMenu);
  48380. }
  48381. if (this._onMouseMove) {
  48382. element.removeEventListener("mousemove", this._onMouseMove);
  48383. }
  48384. if (this._onGestureStart) {
  48385. element.removeEventListener("MSPointerDown", this._onGestureStart);
  48386. }
  48387. if (this._onGesture) {
  48388. element.removeEventListener("MSGestureChange", this._onGesture);
  48389. }
  48390. this._isPanClick = false;
  48391. this.pinchInwards = true;
  48392. this._onMouseMove = null;
  48393. this._onGestureStart = null;
  48394. this._onGesture = null;
  48395. this._MSGestureHandler = null;
  48396. this._onLostFocus = null;
  48397. this._onContextMenu = null;
  48398. }
  48399. };
  48400. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  48401. return "ArcRotateCameraPointersInput";
  48402. };
  48403. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  48404. return "pointers";
  48405. };
  48406. __decorate([
  48407. BABYLON.serialize()
  48408. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  48409. __decorate([
  48410. BABYLON.serialize()
  48411. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  48412. __decorate([
  48413. BABYLON.serialize()
  48414. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  48415. __decorate([
  48416. BABYLON.serialize()
  48417. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  48418. __decorate([
  48419. BABYLON.serialize()
  48420. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  48421. __decorate([
  48422. BABYLON.serialize()
  48423. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  48424. __decorate([
  48425. BABYLON.serialize()
  48426. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  48427. __decorate([
  48428. BABYLON.serialize()
  48429. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  48430. return ArcRotateCameraPointersInput;
  48431. }());
  48432. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  48433. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  48434. })(BABYLON || (BABYLON = {}));
  48435. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  48436. var BABYLON;
  48437. (function (BABYLON) {
  48438. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  48439. __extends(ArcRotateCameraInputsManager, _super);
  48440. function ArcRotateCameraInputsManager(camera) {
  48441. return _super.call(this, camera) || this;
  48442. }
  48443. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  48444. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  48445. return this;
  48446. };
  48447. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  48448. this.add(new BABYLON.ArcRotateCameraPointersInput());
  48449. return this;
  48450. };
  48451. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  48452. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  48453. return this;
  48454. };
  48455. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  48456. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  48457. return this;
  48458. };
  48459. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  48460. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  48461. return this;
  48462. };
  48463. return ArcRotateCameraInputsManager;
  48464. }(BABYLON.CameraInputsManager));
  48465. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  48466. })(BABYLON || (BABYLON = {}));
  48467. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  48468. var BABYLON;
  48469. (function (BABYLON) {
  48470. var ArcRotateCamera = /** @class */ (function (_super) {
  48471. __extends(ArcRotateCamera, _super);
  48472. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  48473. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  48474. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  48475. _this.inertialAlphaOffset = 0;
  48476. _this.inertialBetaOffset = 0;
  48477. _this.inertialRadiusOffset = 0;
  48478. _this.lowerAlphaLimit = null;
  48479. _this.upperAlphaLimit = null;
  48480. _this.lowerBetaLimit = 0.01;
  48481. _this.upperBetaLimit = Math.PI;
  48482. _this.lowerRadiusLimit = null;
  48483. _this.upperRadiusLimit = null;
  48484. _this.inertialPanningX = 0;
  48485. _this.inertialPanningY = 0;
  48486. _this.pinchToPanMaxDistance = 20;
  48487. _this.panningDistanceLimit = null;
  48488. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  48489. _this.panningInertia = 0.9;
  48490. //-- end properties for backward compatibility for inputs
  48491. _this.zoomOnFactor = 1;
  48492. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  48493. _this.allowUpsideDown = true;
  48494. _this._viewMatrix = new BABYLON.Matrix();
  48495. // Panning
  48496. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  48497. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  48498. _this.checkCollisions = false;
  48499. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  48500. _this._previousPosition = BABYLON.Vector3.Zero();
  48501. _this._collisionVelocity = BABYLON.Vector3.Zero();
  48502. _this._newPosition = BABYLON.Vector3.Zero();
  48503. _this._computationVector = BABYLON.Vector3.Zero();
  48504. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  48505. if (collidedMesh === void 0) { collidedMesh = null; }
  48506. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  48507. newPosition.multiplyInPlace(_this._collider._radius);
  48508. }
  48509. if (!collidedMesh) {
  48510. _this._previousPosition.copyFrom(_this.position);
  48511. }
  48512. else {
  48513. _this.setPosition(newPosition);
  48514. if (_this.onCollide) {
  48515. _this.onCollide(collidedMesh);
  48516. }
  48517. }
  48518. // Recompute because of constraints
  48519. var cosa = Math.cos(_this.alpha);
  48520. var sina = Math.sin(_this.alpha);
  48521. var cosb = Math.cos(_this.beta);
  48522. var sinb = Math.sin(_this.beta);
  48523. if (sinb === 0) {
  48524. sinb = 0.0001;
  48525. }
  48526. var target = _this._getTargetPosition();
  48527. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  48528. target.addToRef(_this._computationVector, _this._newPosition);
  48529. _this.position.copyFrom(_this._newPosition);
  48530. var up = _this.upVector;
  48531. if (_this.allowUpsideDown && _this.beta < 0) {
  48532. up = up.clone();
  48533. up = up.negate();
  48534. }
  48535. BABYLON.Matrix.LookAtLHToRef(_this.position, target, up, _this._viewMatrix);
  48536. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  48537. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  48538. _this._collisionTriggered = false;
  48539. };
  48540. _this._target = BABYLON.Vector3.Zero();
  48541. if (target) {
  48542. _this.setTarget(target);
  48543. }
  48544. _this.alpha = alpha;
  48545. _this.beta = beta;
  48546. _this.radius = radius;
  48547. _this.getViewMatrix();
  48548. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  48549. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  48550. return _this;
  48551. }
  48552. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  48553. get: function () {
  48554. return this._target;
  48555. },
  48556. set: function (value) {
  48557. this.setTarget(value);
  48558. },
  48559. enumerable: true,
  48560. configurable: true
  48561. });
  48562. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  48563. //-- begin properties for backward compatibility for inputs
  48564. get: function () {
  48565. var pointers = this.inputs.attached["pointers"];
  48566. if (pointers)
  48567. return pointers.angularSensibilityX;
  48568. return 0;
  48569. },
  48570. set: function (value) {
  48571. var pointers = this.inputs.attached["pointers"];
  48572. if (pointers) {
  48573. pointers.angularSensibilityX = value;
  48574. }
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  48580. get: function () {
  48581. var pointers = this.inputs.attached["pointers"];
  48582. if (pointers)
  48583. return pointers.angularSensibilityY;
  48584. return 0;
  48585. },
  48586. set: function (value) {
  48587. var pointers = this.inputs.attached["pointers"];
  48588. if (pointers) {
  48589. pointers.angularSensibilityY = value;
  48590. }
  48591. },
  48592. enumerable: true,
  48593. configurable: true
  48594. });
  48595. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  48596. get: function () {
  48597. var pointers = this.inputs.attached["pointers"];
  48598. if (pointers)
  48599. return pointers.pinchPrecision;
  48600. return 0;
  48601. },
  48602. set: function (value) {
  48603. var pointers = this.inputs.attached["pointers"];
  48604. if (pointers) {
  48605. pointers.pinchPrecision = value;
  48606. }
  48607. },
  48608. enumerable: true,
  48609. configurable: true
  48610. });
  48611. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  48612. get: function () {
  48613. var pointers = this.inputs.attached["pointers"];
  48614. if (pointers)
  48615. return pointers.pinchDeltaPercentage;
  48616. return 0;
  48617. },
  48618. set: function (value) {
  48619. var pointers = this.inputs.attached["pointers"];
  48620. if (pointers) {
  48621. pointers.pinchDeltaPercentage = value;
  48622. }
  48623. },
  48624. enumerable: true,
  48625. configurable: true
  48626. });
  48627. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  48628. get: function () {
  48629. var pointers = this.inputs.attached["pointers"];
  48630. if (pointers)
  48631. return pointers.panningSensibility;
  48632. return 0;
  48633. },
  48634. set: function (value) {
  48635. var pointers = this.inputs.attached["pointers"];
  48636. if (pointers) {
  48637. pointers.panningSensibility = value;
  48638. }
  48639. },
  48640. enumerable: true,
  48641. configurable: true
  48642. });
  48643. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  48644. get: function () {
  48645. var keyboard = this.inputs.attached["keyboard"];
  48646. if (keyboard)
  48647. return keyboard.keysUp;
  48648. return [];
  48649. },
  48650. set: function (value) {
  48651. var keyboard = this.inputs.attached["keyboard"];
  48652. if (keyboard)
  48653. keyboard.keysUp = value;
  48654. },
  48655. enumerable: true,
  48656. configurable: true
  48657. });
  48658. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  48659. get: function () {
  48660. var keyboard = this.inputs.attached["keyboard"];
  48661. if (keyboard)
  48662. return keyboard.keysDown;
  48663. return [];
  48664. },
  48665. set: function (value) {
  48666. var keyboard = this.inputs.attached["keyboard"];
  48667. if (keyboard)
  48668. keyboard.keysDown = value;
  48669. },
  48670. enumerable: true,
  48671. configurable: true
  48672. });
  48673. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  48674. get: function () {
  48675. var keyboard = this.inputs.attached["keyboard"];
  48676. if (keyboard)
  48677. return keyboard.keysLeft;
  48678. return [];
  48679. },
  48680. set: function (value) {
  48681. var keyboard = this.inputs.attached["keyboard"];
  48682. if (keyboard)
  48683. keyboard.keysLeft = value;
  48684. },
  48685. enumerable: true,
  48686. configurable: true
  48687. });
  48688. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  48689. get: function () {
  48690. var keyboard = this.inputs.attached["keyboard"];
  48691. if (keyboard)
  48692. return keyboard.keysRight;
  48693. return [];
  48694. },
  48695. set: function (value) {
  48696. var keyboard = this.inputs.attached["keyboard"];
  48697. if (keyboard)
  48698. keyboard.keysRight = value;
  48699. },
  48700. enumerable: true,
  48701. configurable: true
  48702. });
  48703. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  48704. get: function () {
  48705. var mousewheel = this.inputs.attached["mousewheel"];
  48706. if (mousewheel)
  48707. return mousewheel.wheelPrecision;
  48708. return 0;
  48709. },
  48710. set: function (value) {
  48711. var mousewheel = this.inputs.attached["mousewheel"];
  48712. if (mousewheel)
  48713. mousewheel.wheelPrecision = value;
  48714. },
  48715. enumerable: true,
  48716. configurable: true
  48717. });
  48718. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  48719. get: function () {
  48720. var mousewheel = this.inputs.attached["mousewheel"];
  48721. if (mousewheel)
  48722. return mousewheel.wheelDeltaPercentage;
  48723. return 0;
  48724. },
  48725. set: function (value) {
  48726. var mousewheel = this.inputs.attached["mousewheel"];
  48727. if (mousewheel)
  48728. mousewheel.wheelDeltaPercentage = value;
  48729. },
  48730. enumerable: true,
  48731. configurable: true
  48732. });
  48733. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  48734. get: function () {
  48735. return this._bouncingBehavior;
  48736. },
  48737. enumerable: true,
  48738. configurable: true
  48739. });
  48740. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  48741. get: function () {
  48742. return this._bouncingBehavior != null;
  48743. },
  48744. set: function (value) {
  48745. if (value === this.useBouncingBehavior) {
  48746. return;
  48747. }
  48748. if (value) {
  48749. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  48750. this.addBehavior(this._bouncingBehavior);
  48751. }
  48752. else if (this._bouncingBehavior) {
  48753. this.removeBehavior(this._bouncingBehavior);
  48754. this._bouncingBehavior = null;
  48755. }
  48756. },
  48757. enumerable: true,
  48758. configurable: true
  48759. });
  48760. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  48761. get: function () {
  48762. return this._framingBehavior;
  48763. },
  48764. enumerable: true,
  48765. configurable: true
  48766. });
  48767. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  48768. get: function () {
  48769. return this._framingBehavior != null;
  48770. },
  48771. set: function (value) {
  48772. if (value === this.useFramingBehavior) {
  48773. return;
  48774. }
  48775. if (value) {
  48776. this._framingBehavior = new BABYLON.FramingBehavior();
  48777. this.addBehavior(this._framingBehavior);
  48778. }
  48779. else if (this._framingBehavior) {
  48780. this.removeBehavior(this._framingBehavior);
  48781. this._framingBehavior = null;
  48782. }
  48783. },
  48784. enumerable: true,
  48785. configurable: true
  48786. });
  48787. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  48788. get: function () {
  48789. return this._autoRotationBehavior;
  48790. },
  48791. enumerable: true,
  48792. configurable: true
  48793. });
  48794. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  48795. get: function () {
  48796. return this._autoRotationBehavior != null;
  48797. },
  48798. set: function (value) {
  48799. if (value === this.useAutoRotationBehavior) {
  48800. return;
  48801. }
  48802. if (value) {
  48803. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  48804. this.addBehavior(this._autoRotationBehavior);
  48805. }
  48806. else if (this._autoRotationBehavior) {
  48807. this.removeBehavior(this._autoRotationBehavior);
  48808. this._autoRotationBehavior = null;
  48809. }
  48810. },
  48811. enumerable: true,
  48812. configurable: true
  48813. });
  48814. // Cache
  48815. ArcRotateCamera.prototype._initCache = function () {
  48816. _super.prototype._initCache.call(this);
  48817. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48818. this._cache.alpha = undefined;
  48819. this._cache.beta = undefined;
  48820. this._cache.radius = undefined;
  48821. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48822. };
  48823. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48824. if (!ignoreParentClass) {
  48825. _super.prototype._updateCache.call(this);
  48826. }
  48827. this._cache._target.copyFrom(this._getTargetPosition());
  48828. this._cache.alpha = this.alpha;
  48829. this._cache.beta = this.beta;
  48830. this._cache.radius = this.radius;
  48831. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48832. };
  48833. ArcRotateCamera.prototype._getTargetPosition = function () {
  48834. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48835. var pos = this._targetHost.getAbsolutePosition();
  48836. if (this._targetBoundingCenter) {
  48837. pos.addToRef(this._targetBoundingCenter, this._target);
  48838. }
  48839. else {
  48840. this._target.copyFrom(pos);
  48841. }
  48842. }
  48843. var lockedTargetPosition = this._getLockedTargetPosition();
  48844. if (lockedTargetPosition) {
  48845. return lockedTargetPosition;
  48846. }
  48847. return this._target;
  48848. };
  48849. ArcRotateCamera.prototype.storeState = function () {
  48850. this._storedAlpha = this.alpha;
  48851. this._storedBeta = this.beta;
  48852. this._storedRadius = this.radius;
  48853. this._storedTarget = this._getTargetPosition().clone();
  48854. return _super.prototype.storeState.call(this);
  48855. };
  48856. /**
  48857. * Restored camera state. You must call storeState() first
  48858. */
  48859. ArcRotateCamera.prototype._restoreStateValues = function () {
  48860. if (!_super.prototype._restoreStateValues.call(this)) {
  48861. return false;
  48862. }
  48863. this.alpha = this._storedAlpha;
  48864. this.beta = this._storedBeta;
  48865. this.radius = this._storedRadius;
  48866. this.setTarget(this._storedTarget.clone());
  48867. this.inertialAlphaOffset = 0;
  48868. this.inertialBetaOffset = 0;
  48869. this.inertialRadiusOffset = 0;
  48870. this.inertialPanningX = 0;
  48871. this.inertialPanningY = 0;
  48872. return true;
  48873. };
  48874. // Synchronized
  48875. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48876. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48877. return false;
  48878. return this._cache._target.equals(this._getTargetPosition())
  48879. && this._cache.alpha === this.alpha
  48880. && this._cache.beta === this.beta
  48881. && this._cache.radius === this.radius
  48882. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48883. };
  48884. // Methods
  48885. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48886. var _this = this;
  48887. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48888. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48889. this._useCtrlForPanning = useCtrlForPanning;
  48890. this._panningMouseButton = panningMouseButton;
  48891. this.inputs.attachElement(element, noPreventDefault);
  48892. this._reset = function () {
  48893. _this.inertialAlphaOffset = 0;
  48894. _this.inertialBetaOffset = 0;
  48895. _this.inertialRadiusOffset = 0;
  48896. _this.inertialPanningX = 0;
  48897. _this.inertialPanningY = 0;
  48898. };
  48899. };
  48900. ArcRotateCamera.prototype.detachControl = function (element) {
  48901. this.inputs.detachElement(element);
  48902. if (this._reset) {
  48903. this._reset();
  48904. }
  48905. };
  48906. ArcRotateCamera.prototype._checkInputs = function () {
  48907. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48908. if (this._collisionTriggered) {
  48909. return;
  48910. }
  48911. this.inputs.checkInputs();
  48912. // Inertia
  48913. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48914. var inertialAlphaOffset = this.inertialAlphaOffset;
  48915. if (this.beta <= 0)
  48916. inertialAlphaOffset *= -1;
  48917. if (this.getScene().useRightHandedSystem)
  48918. inertialAlphaOffset *= -1;
  48919. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48920. inertialAlphaOffset *= -1;
  48921. this.alpha += inertialAlphaOffset;
  48922. this.beta += this.inertialBetaOffset;
  48923. this.radius -= this.inertialRadiusOffset;
  48924. this.inertialAlphaOffset *= this.inertia;
  48925. this.inertialBetaOffset *= this.inertia;
  48926. this.inertialRadiusOffset *= this.inertia;
  48927. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48928. this.inertialAlphaOffset = 0;
  48929. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48930. this.inertialBetaOffset = 0;
  48931. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48932. this.inertialRadiusOffset = 0;
  48933. }
  48934. // Panning inertia
  48935. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48936. if (!this._localDirection) {
  48937. this._localDirection = BABYLON.Vector3.Zero();
  48938. this._transformedDirection = BABYLON.Vector3.Zero();
  48939. }
  48940. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48941. this._localDirection.multiplyInPlace(this.panningAxis);
  48942. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48943. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48944. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48945. if (!this.panningAxis.y) {
  48946. this._transformedDirection.y = 0;
  48947. }
  48948. if (!this._targetHost) {
  48949. if (this.panningDistanceLimit) {
  48950. this._transformedDirection.addInPlace(this._target);
  48951. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48952. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48953. this._target.copyFrom(this._transformedDirection);
  48954. }
  48955. }
  48956. else {
  48957. this._target.addInPlace(this._transformedDirection);
  48958. }
  48959. }
  48960. this.inertialPanningX *= this.panningInertia;
  48961. this.inertialPanningY *= this.panningInertia;
  48962. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48963. this.inertialPanningX = 0;
  48964. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48965. this.inertialPanningY = 0;
  48966. }
  48967. // Limits
  48968. this._checkLimits();
  48969. _super.prototype._checkInputs.call(this);
  48970. };
  48971. ArcRotateCamera.prototype._checkLimits = function () {
  48972. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48973. if (this.allowUpsideDown && this.beta > Math.PI) {
  48974. this.beta = this.beta - (2 * Math.PI);
  48975. }
  48976. }
  48977. else {
  48978. if (this.beta < this.lowerBetaLimit) {
  48979. this.beta = this.lowerBetaLimit;
  48980. }
  48981. }
  48982. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48983. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48984. this.beta = this.beta + (2 * Math.PI);
  48985. }
  48986. }
  48987. else {
  48988. if (this.beta > this.upperBetaLimit) {
  48989. this.beta = this.upperBetaLimit;
  48990. }
  48991. }
  48992. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48993. this.alpha = this.lowerAlphaLimit;
  48994. }
  48995. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48996. this.alpha = this.upperAlphaLimit;
  48997. }
  48998. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48999. this.radius = this.lowerRadiusLimit;
  49000. }
  49001. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  49002. this.radius = this.upperRadiusLimit;
  49003. }
  49004. };
  49005. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  49006. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  49007. this.radius = this._computationVector.length();
  49008. if (this.radius === 0) {
  49009. this.radius = 0.0001; // Just to avoid division by zero
  49010. }
  49011. // Alpha
  49012. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  49013. if (this._computationVector.z < 0) {
  49014. this.alpha = 2 * Math.PI - this.alpha;
  49015. }
  49016. // Beta
  49017. this.beta = Math.acos(this._computationVector.y / this.radius);
  49018. this._checkLimits();
  49019. };
  49020. ArcRotateCamera.prototype.setPosition = function (position) {
  49021. if (this.position.equals(position)) {
  49022. return;
  49023. }
  49024. this.position.copyFrom(position);
  49025. this.rebuildAnglesAndRadius();
  49026. };
  49027. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  49028. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  49029. if (allowSamePosition === void 0) { allowSamePosition = false; }
  49030. if (target.getBoundingInfo) {
  49031. if (toBoundingCenter) {
  49032. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  49033. }
  49034. else {
  49035. this._targetBoundingCenter = null;
  49036. }
  49037. this._targetHost = target;
  49038. this._target = this._getTargetPosition();
  49039. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  49040. }
  49041. else {
  49042. var newTarget = target;
  49043. var currentTarget = this._getTargetPosition();
  49044. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  49045. return;
  49046. }
  49047. this._targetHost = null;
  49048. this._target = newTarget;
  49049. this._targetBoundingCenter = null;
  49050. this.onMeshTargetChangedObservable.notifyObservers(null);
  49051. }
  49052. this.rebuildAnglesAndRadius();
  49053. };
  49054. ArcRotateCamera.prototype._getViewMatrix = function () {
  49055. // Compute
  49056. var cosa = Math.cos(this.alpha);
  49057. var sina = Math.sin(this.alpha);
  49058. var cosb = Math.cos(this.beta);
  49059. var sinb = Math.sin(this.beta);
  49060. if (sinb === 0) {
  49061. sinb = 0.0001;
  49062. }
  49063. var target = this._getTargetPosition();
  49064. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  49065. target.addToRef(this._computationVector, this._newPosition);
  49066. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  49067. if (!this._collider) {
  49068. this._collider = new BABYLON.Collider();
  49069. }
  49070. this._collider._radius = this.collisionRadius;
  49071. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  49072. this._collisionTriggered = true;
  49073. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  49074. }
  49075. else {
  49076. this.position.copyFrom(this._newPosition);
  49077. var up = this.upVector;
  49078. if (this.allowUpsideDown && sinb < 0) {
  49079. up = up.clone();
  49080. up = up.negate();
  49081. }
  49082. this._computeViewMatrix(this.position, target, up);
  49083. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  49084. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  49085. }
  49086. this._currentTarget = target;
  49087. return this._viewMatrix;
  49088. };
  49089. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  49090. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49091. meshes = meshes || this.getScene().meshes;
  49092. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  49093. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  49094. this.radius = distance * this.zoomOnFactor;
  49095. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  49096. };
  49097. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  49098. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  49099. var meshesOrMinMaxVector;
  49100. var distance;
  49101. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  49102. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  49103. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  49104. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  49105. }
  49106. else { //minMaxVector and distance
  49107. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  49108. meshesOrMinMaxVector = minMaxVectorAndDistance;
  49109. distance = minMaxVectorAndDistance.distance;
  49110. }
  49111. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  49112. if (!doNotUpdateMaxZ) {
  49113. this.maxZ = distance * 2;
  49114. }
  49115. };
  49116. /**
  49117. * @override
  49118. * Override Camera.createRigCamera
  49119. */
  49120. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  49121. var alphaShift = 0;
  49122. switch (this.cameraRigMode) {
  49123. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49124. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49125. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49126. case BABYLON.Camera.RIG_MODE_VR:
  49127. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  49128. break;
  49129. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49130. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  49131. break;
  49132. }
  49133. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  49134. rigCam._cameraRigParams = {};
  49135. return rigCam;
  49136. };
  49137. /**
  49138. * @override
  49139. * Override Camera._updateRigCameras
  49140. */
  49141. ArcRotateCamera.prototype._updateRigCameras = function () {
  49142. var camLeft = this._rigCameras[0];
  49143. var camRight = this._rigCameras[1];
  49144. camLeft.beta = camRight.beta = this.beta;
  49145. camLeft.radius = camRight.radius = this.radius;
  49146. switch (this.cameraRigMode) {
  49147. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  49148. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  49149. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  49150. case BABYLON.Camera.RIG_MODE_VR:
  49151. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49152. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49153. break;
  49154. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  49155. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  49156. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  49157. break;
  49158. }
  49159. _super.prototype._updateRigCameras.call(this);
  49160. };
  49161. ArcRotateCamera.prototype.dispose = function () {
  49162. this.inputs.clear();
  49163. _super.prototype.dispose.call(this);
  49164. };
  49165. ArcRotateCamera.prototype.getClassName = function () {
  49166. return "ArcRotateCamera";
  49167. };
  49168. __decorate([
  49169. BABYLON.serialize()
  49170. ], ArcRotateCamera.prototype, "alpha", void 0);
  49171. __decorate([
  49172. BABYLON.serialize()
  49173. ], ArcRotateCamera.prototype, "beta", void 0);
  49174. __decorate([
  49175. BABYLON.serialize()
  49176. ], ArcRotateCamera.prototype, "radius", void 0);
  49177. __decorate([
  49178. BABYLON.serializeAsVector3("target")
  49179. ], ArcRotateCamera.prototype, "_target", void 0);
  49180. __decorate([
  49181. BABYLON.serialize()
  49182. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  49183. __decorate([
  49184. BABYLON.serialize()
  49185. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  49186. __decorate([
  49187. BABYLON.serialize()
  49188. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  49189. __decorate([
  49190. BABYLON.serialize()
  49191. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  49192. __decorate([
  49193. BABYLON.serialize()
  49194. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  49195. __decorate([
  49196. BABYLON.serialize()
  49197. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  49198. __decorate([
  49199. BABYLON.serialize()
  49200. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  49201. __decorate([
  49202. BABYLON.serialize()
  49203. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  49204. __decorate([
  49205. BABYLON.serialize()
  49206. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  49207. __decorate([
  49208. BABYLON.serialize()
  49209. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  49210. __decorate([
  49211. BABYLON.serialize()
  49212. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  49213. __decorate([
  49214. BABYLON.serialize()
  49215. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  49216. __decorate([
  49217. BABYLON.serialize()
  49218. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  49219. __decorate([
  49220. BABYLON.serializeAsVector3()
  49221. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  49222. __decorate([
  49223. BABYLON.serialize()
  49224. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  49225. __decorate([
  49226. BABYLON.serialize()
  49227. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  49228. __decorate([
  49229. BABYLON.serialize()
  49230. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  49231. return ArcRotateCamera;
  49232. }(BABYLON.TargetCamera));
  49233. BABYLON.ArcRotateCamera = ArcRotateCamera;
  49234. })(BABYLON || (BABYLON = {}));
  49235. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  49236. var BABYLON;
  49237. (function (BABYLON) {
  49238. /**
  49239. * The HemisphericLight simulates the ambient environment light,
  49240. * so the passed direction is the light reflection direction, not the incoming direction.
  49241. */
  49242. var HemisphericLight = /** @class */ (function (_super) {
  49243. __extends(HemisphericLight, _super);
  49244. /**
  49245. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  49246. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  49247. * The HemisphericLight can't cast shadows.
  49248. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49249. * @param name The friendly name of the light
  49250. * @param direction The direction of the light reflection
  49251. * @param scene The scene the light belongs to
  49252. */
  49253. function HemisphericLight(name, direction, scene) {
  49254. var _this = _super.call(this, name, scene) || this;
  49255. /**
  49256. * The groundColor is the light in the opposite direction to the one specified during creation.
  49257. * 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.
  49258. */
  49259. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  49260. _this.direction = direction || BABYLON.Vector3.Up();
  49261. return _this;
  49262. }
  49263. HemisphericLight.prototype._buildUniformLayout = function () {
  49264. this._uniformBuffer.addUniform("vLightData", 4);
  49265. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49266. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49267. this._uniformBuffer.addUniform("vLightGround", 3);
  49268. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49269. this._uniformBuffer.addUniform("depthValues", 2);
  49270. this._uniformBuffer.create();
  49271. };
  49272. /**
  49273. * Returns the string "HemisphericLight".
  49274. * @return The class name
  49275. */
  49276. HemisphericLight.prototype.getClassName = function () {
  49277. return "HemisphericLight";
  49278. };
  49279. /**
  49280. * Sets the HemisphericLight direction towards the passed target (Vector3).
  49281. * Returns the updated direction.
  49282. * @param target The target the direction should point to
  49283. * @return The computed direction
  49284. */
  49285. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  49286. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  49287. return this.direction;
  49288. };
  49289. /**
  49290. * Returns the shadow generator associated to the light.
  49291. * @returns Always null for hemispheric lights because it does not support shadows.
  49292. */
  49293. HemisphericLight.prototype.getShadowGenerator = function () {
  49294. return null;
  49295. };
  49296. /**
  49297. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  49298. * @param effect The effect to update
  49299. * @param lightIndex The index of the light in the effect to update
  49300. * @returns The hemispheric light
  49301. */
  49302. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  49303. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49304. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  49305. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  49306. return this;
  49307. };
  49308. /**
  49309. * @hidden internal use only.
  49310. */
  49311. HemisphericLight.prototype._getWorldMatrix = function () {
  49312. if (!this._worldMatrix) {
  49313. this._worldMatrix = BABYLON.Matrix.Identity();
  49314. }
  49315. return this._worldMatrix;
  49316. };
  49317. /**
  49318. * Returns the integer 3.
  49319. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49320. */
  49321. HemisphericLight.prototype.getTypeID = function () {
  49322. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  49323. };
  49324. __decorate([
  49325. BABYLON.serializeAsColor3()
  49326. ], HemisphericLight.prototype, "groundColor", void 0);
  49327. __decorate([
  49328. BABYLON.serializeAsVector3()
  49329. ], HemisphericLight.prototype, "direction", void 0);
  49330. return HemisphericLight;
  49331. }(BABYLON.Light));
  49332. BABYLON.HemisphericLight = HemisphericLight;
  49333. })(BABYLON || (BABYLON = {}));
  49334. //# sourceMappingURL=babylon.hemisphericLight.js.map
  49335. var BABYLON;
  49336. (function (BABYLON) {
  49337. /**
  49338. * Base implementation IShadowLight
  49339. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  49340. */
  49341. var ShadowLight = /** @class */ (function (_super) {
  49342. __extends(ShadowLight, _super);
  49343. function ShadowLight() {
  49344. var _this = _super !== null && _super.apply(this, arguments) || this;
  49345. _this._needProjectionMatrixCompute = true;
  49346. return _this;
  49347. }
  49348. ShadowLight.prototype._setPosition = function (value) {
  49349. this._position = value;
  49350. };
  49351. Object.defineProperty(ShadowLight.prototype, "position", {
  49352. /**
  49353. * Sets the position the shadow will be casted from. Also use as the light position for both
  49354. * point and spot lights.
  49355. */
  49356. get: function () {
  49357. return this._position;
  49358. },
  49359. /**
  49360. * Sets the position the shadow will be casted from. Also use as the light position for both
  49361. * point and spot lights.
  49362. */
  49363. set: function (value) {
  49364. this._setPosition(value);
  49365. },
  49366. enumerable: true,
  49367. configurable: true
  49368. });
  49369. ShadowLight.prototype._setDirection = function (value) {
  49370. this._direction = value;
  49371. };
  49372. Object.defineProperty(ShadowLight.prototype, "direction", {
  49373. /**
  49374. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  49375. * Also use as the light direction on spot and directional lights.
  49376. */
  49377. get: function () {
  49378. return this._direction;
  49379. },
  49380. /**
  49381. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  49382. * Also use as the light direction on spot and directional lights.
  49383. */
  49384. set: function (value) {
  49385. this._setDirection(value);
  49386. },
  49387. enumerable: true,
  49388. configurable: true
  49389. });
  49390. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  49391. /**
  49392. * Gets the shadow projection clipping minimum z value.
  49393. */
  49394. get: function () {
  49395. return this._shadowMinZ;
  49396. },
  49397. /**
  49398. * Sets the shadow projection clipping minimum z value.
  49399. */
  49400. set: function (value) {
  49401. this._shadowMinZ = value;
  49402. this.forceProjectionMatrixCompute();
  49403. },
  49404. enumerable: true,
  49405. configurable: true
  49406. });
  49407. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  49408. /**
  49409. * Sets the shadow projection clipping maximum z value.
  49410. */
  49411. get: function () {
  49412. return this._shadowMaxZ;
  49413. },
  49414. /**
  49415. * Gets the shadow projection clipping maximum z value.
  49416. */
  49417. set: function (value) {
  49418. this._shadowMaxZ = value;
  49419. this.forceProjectionMatrixCompute();
  49420. },
  49421. enumerable: true,
  49422. configurable: true
  49423. });
  49424. /**
  49425. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  49426. * @returns true if the information has been computed, false if it does not need to (no parenting)
  49427. */
  49428. ShadowLight.prototype.computeTransformedInformation = function () {
  49429. if (this.parent && this.parent.getWorldMatrix) {
  49430. if (!this.transformedPosition) {
  49431. this.transformedPosition = BABYLON.Vector3.Zero();
  49432. }
  49433. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  49434. // In case the direction is present.
  49435. if (this.direction) {
  49436. if (!this.transformedDirection) {
  49437. this.transformedDirection = BABYLON.Vector3.Zero();
  49438. }
  49439. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  49440. }
  49441. return true;
  49442. }
  49443. return false;
  49444. };
  49445. /**
  49446. * Return the depth scale used for the shadow map.
  49447. * @returns the depth scale.
  49448. */
  49449. ShadowLight.prototype.getDepthScale = function () {
  49450. return 50.0;
  49451. };
  49452. /**
  49453. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  49454. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49455. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49456. */
  49457. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  49458. return this.transformedDirection ? this.transformedDirection : this.direction;
  49459. };
  49460. /**
  49461. * Returns the ShadowLight absolute position in the World.
  49462. * @returns the position vector in world space
  49463. */
  49464. ShadowLight.prototype.getAbsolutePosition = function () {
  49465. return this.transformedPosition ? this.transformedPosition : this.position;
  49466. };
  49467. /**
  49468. * Sets the ShadowLight direction toward the passed target.
  49469. * @param target The point tot target in local space
  49470. * @returns the updated ShadowLight direction
  49471. */
  49472. ShadowLight.prototype.setDirectionToTarget = function (target) {
  49473. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  49474. return this.direction;
  49475. };
  49476. /**
  49477. * Returns the light rotation in euler definition.
  49478. * @returns the x y z rotation in local space.
  49479. */
  49480. ShadowLight.prototype.getRotation = function () {
  49481. this.direction.normalize();
  49482. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  49483. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  49484. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  49485. };
  49486. /**
  49487. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  49488. * @returns true if a cube texture needs to be use
  49489. */
  49490. ShadowLight.prototype.needCube = function () {
  49491. return false;
  49492. };
  49493. /**
  49494. * Detects if the projection matrix requires to be recomputed this frame.
  49495. * @returns true if it requires to be recomputed otherwise, false.
  49496. */
  49497. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  49498. return this._needProjectionMatrixCompute;
  49499. };
  49500. /**
  49501. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  49502. */
  49503. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  49504. this._needProjectionMatrixCompute = true;
  49505. };
  49506. /**
  49507. * Get the world matrix of the sahdow lights.
  49508. * @hidden Internal Use Only
  49509. */
  49510. ShadowLight.prototype._getWorldMatrix = function () {
  49511. if (!this._worldMatrix) {
  49512. this._worldMatrix = BABYLON.Matrix.Identity();
  49513. }
  49514. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  49515. return this._worldMatrix;
  49516. };
  49517. /**
  49518. * Gets the minZ used for shadow according to both the scene and the light.
  49519. * @param activeCamera The camera we are returning the min for
  49520. * @returns the depth min z
  49521. */
  49522. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  49523. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  49524. };
  49525. /**
  49526. * Gets the maxZ used for shadow according to both the scene and the light.
  49527. * @param activeCamera The camera we are returning the max for
  49528. * @returns the depth max z
  49529. */
  49530. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  49531. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  49532. };
  49533. /**
  49534. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  49535. * @param matrix The materix to updated with the projection information
  49536. * @param viewMatrix The transform matrix of the light
  49537. * @param renderList The list of mesh to render in the map
  49538. * @returns The current light
  49539. */
  49540. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49541. if (this.customProjectionMatrixBuilder) {
  49542. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  49543. }
  49544. else {
  49545. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49546. }
  49547. return this;
  49548. };
  49549. __decorate([
  49550. BABYLON.serializeAsVector3()
  49551. ], ShadowLight.prototype, "position", null);
  49552. __decorate([
  49553. BABYLON.serializeAsVector3()
  49554. ], ShadowLight.prototype, "direction", null);
  49555. __decorate([
  49556. BABYLON.serialize()
  49557. ], ShadowLight.prototype, "shadowMinZ", null);
  49558. __decorate([
  49559. BABYLON.serialize()
  49560. ], ShadowLight.prototype, "shadowMaxZ", null);
  49561. return ShadowLight;
  49562. }(BABYLON.Light));
  49563. BABYLON.ShadowLight = ShadowLight;
  49564. })(BABYLON || (BABYLON = {}));
  49565. //# sourceMappingURL=babylon.shadowLight.js.map
  49566. var BABYLON;
  49567. (function (BABYLON) {
  49568. /**
  49569. * A point light is a light defined by an unique point in world space.
  49570. * The light is emitted in every direction from this point.
  49571. * A good example of a point light is a standard light bulb.
  49572. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49573. */
  49574. var PointLight = /** @class */ (function (_super) {
  49575. __extends(PointLight, _super);
  49576. /**
  49577. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  49578. * A PointLight emits the light in every direction.
  49579. * It can cast shadows.
  49580. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  49581. * ```javascript
  49582. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  49583. * ```
  49584. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49585. * @param name The light friendly name
  49586. * @param position The position of the point light in the scene
  49587. * @param scene The scene the lights belongs to
  49588. */
  49589. function PointLight(name, position, scene) {
  49590. var _this = _super.call(this, name, scene) || this;
  49591. _this._shadowAngle = Math.PI / 2;
  49592. _this.position = position;
  49593. return _this;
  49594. }
  49595. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  49596. /**
  49597. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49598. * This specifies what angle the shadow will use to be created.
  49599. *
  49600. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49601. */
  49602. get: function () {
  49603. return this._shadowAngle;
  49604. },
  49605. /**
  49606. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49607. * This specifies what angle the shadow will use to be created.
  49608. *
  49609. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  49610. */
  49611. set: function (value) {
  49612. this._shadowAngle = value;
  49613. this.forceProjectionMatrixCompute();
  49614. },
  49615. enumerable: true,
  49616. configurable: true
  49617. });
  49618. Object.defineProperty(PointLight.prototype, "direction", {
  49619. /**
  49620. * Gets the direction if it has been set.
  49621. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49622. */
  49623. get: function () {
  49624. return this._direction;
  49625. },
  49626. /**
  49627. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  49628. */
  49629. set: function (value) {
  49630. var previousNeedCube = this.needCube();
  49631. this._direction = value;
  49632. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  49633. this._shadowGenerator.recreateShadowMap();
  49634. }
  49635. },
  49636. enumerable: true,
  49637. configurable: true
  49638. });
  49639. /**
  49640. * Returns the string "PointLight"
  49641. * @returns the class name
  49642. */
  49643. PointLight.prototype.getClassName = function () {
  49644. return "PointLight";
  49645. };
  49646. /**
  49647. * Returns the integer 0.
  49648. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49649. */
  49650. PointLight.prototype.getTypeID = function () {
  49651. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  49652. };
  49653. /**
  49654. * Specifies wether or not the shadowmap should be a cube texture.
  49655. * @returns true if the shadowmap needs to be a cube texture.
  49656. */
  49657. PointLight.prototype.needCube = function () {
  49658. return !this.direction;
  49659. };
  49660. /**
  49661. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  49662. * @param faceIndex The index of the face we are computed the direction to generate shadow
  49663. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  49664. */
  49665. PointLight.prototype.getShadowDirection = function (faceIndex) {
  49666. if (this.direction) {
  49667. return _super.prototype.getShadowDirection.call(this, faceIndex);
  49668. }
  49669. else {
  49670. switch (faceIndex) {
  49671. case 0:
  49672. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  49673. case 1:
  49674. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  49675. case 2:
  49676. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  49677. case 3:
  49678. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  49679. case 4:
  49680. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  49681. case 5:
  49682. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  49683. }
  49684. }
  49685. return BABYLON.Vector3.Zero();
  49686. };
  49687. /**
  49688. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  49689. * - fov = PI / 2
  49690. * - aspect ratio : 1.0
  49691. * - z-near and far equal to the active camera minZ and maxZ.
  49692. * Returns the PointLight.
  49693. */
  49694. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49695. var activeCamera = this.getScene().activeCamera;
  49696. if (!activeCamera) {
  49697. return;
  49698. }
  49699. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49700. };
  49701. PointLight.prototype._buildUniformLayout = function () {
  49702. this._uniformBuffer.addUniform("vLightData", 4);
  49703. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49704. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49705. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49706. this._uniformBuffer.addUniform("depthValues", 2);
  49707. this._uniformBuffer.create();
  49708. };
  49709. /**
  49710. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  49711. * @param effect The effect to update
  49712. * @param lightIndex The index of the light in the effect to update
  49713. * @returns The point light
  49714. */
  49715. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  49716. if (this.computeTransformedInformation()) {
  49717. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  49718. return this;
  49719. }
  49720. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  49721. return this;
  49722. };
  49723. __decorate([
  49724. BABYLON.serialize()
  49725. ], PointLight.prototype, "shadowAngle", null);
  49726. return PointLight;
  49727. }(BABYLON.ShadowLight));
  49728. BABYLON.PointLight = PointLight;
  49729. })(BABYLON || (BABYLON = {}));
  49730. //# sourceMappingURL=babylon.pointLight.js.map
  49731. var BABYLON;
  49732. (function (BABYLON) {
  49733. /**
  49734. * A directional light is defined by a direction (what a surprise!).
  49735. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  49736. * 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.
  49737. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49738. */
  49739. var DirectionalLight = /** @class */ (function (_super) {
  49740. __extends(DirectionalLight, _super);
  49741. /**
  49742. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  49743. * The directional light is emitted from everywhere in the given direction.
  49744. * It can cast shawdows.
  49745. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49746. * @param name The friendly name of the light
  49747. * @param direction The direction of the light
  49748. * @param scene The scene the light belongs to
  49749. */
  49750. function DirectionalLight(name, direction, scene) {
  49751. var _this = _super.call(this, name, scene) || this;
  49752. _this._shadowFrustumSize = 0;
  49753. _this._shadowOrthoScale = 0.1;
  49754. /**
  49755. * Automatically compute the projection matrix to best fit (including all the casters)
  49756. * on each frame.
  49757. */
  49758. _this.autoUpdateExtends = true;
  49759. // Cache
  49760. _this._orthoLeft = Number.MAX_VALUE;
  49761. _this._orthoRight = Number.MIN_VALUE;
  49762. _this._orthoTop = Number.MIN_VALUE;
  49763. _this._orthoBottom = Number.MAX_VALUE;
  49764. _this.position = direction.scale(-1.0);
  49765. _this.direction = direction;
  49766. return _this;
  49767. }
  49768. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  49769. /**
  49770. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  49771. */
  49772. get: function () {
  49773. return this._shadowFrustumSize;
  49774. },
  49775. /**
  49776. * Specifies a fix frustum size for the shadow generation.
  49777. */
  49778. set: function (value) {
  49779. this._shadowFrustumSize = value;
  49780. this.forceProjectionMatrixCompute();
  49781. },
  49782. enumerable: true,
  49783. configurable: true
  49784. });
  49785. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  49786. /**
  49787. * Gets the shadow projection scale against the optimal computed one.
  49788. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49789. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49790. */
  49791. get: function () {
  49792. return this._shadowOrthoScale;
  49793. },
  49794. /**
  49795. * Sets the shadow projection scale against the optimal computed one.
  49796. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  49797. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  49798. */
  49799. set: function (value) {
  49800. this._shadowOrthoScale = value;
  49801. this.forceProjectionMatrixCompute();
  49802. },
  49803. enumerable: true,
  49804. configurable: true
  49805. });
  49806. /**
  49807. * Returns the string "DirectionalLight".
  49808. * @return The class name
  49809. */
  49810. DirectionalLight.prototype.getClassName = function () {
  49811. return "DirectionalLight";
  49812. };
  49813. /**
  49814. * Returns the integer 1.
  49815. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49816. */
  49817. DirectionalLight.prototype.getTypeID = function () {
  49818. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49819. };
  49820. /**
  49821. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49822. * Returns the DirectionalLight Shadow projection matrix.
  49823. */
  49824. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49825. if (this.shadowFrustumSize > 0) {
  49826. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49827. }
  49828. else {
  49829. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49830. }
  49831. };
  49832. /**
  49833. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49834. * Returns the DirectionalLight Shadow projection matrix.
  49835. */
  49836. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49837. var activeCamera = this.getScene().activeCamera;
  49838. if (!activeCamera) {
  49839. return;
  49840. }
  49841. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49842. };
  49843. /**
  49844. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49845. * Returns the DirectionalLight Shadow projection matrix.
  49846. */
  49847. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49848. var activeCamera = this.getScene().activeCamera;
  49849. if (!activeCamera) {
  49850. return;
  49851. }
  49852. // Check extends
  49853. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49854. var tempVector3 = BABYLON.Vector3.Zero();
  49855. this._orthoLeft = Number.MAX_VALUE;
  49856. this._orthoRight = Number.MIN_VALUE;
  49857. this._orthoTop = Number.MIN_VALUE;
  49858. this._orthoBottom = Number.MAX_VALUE;
  49859. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49860. var mesh = renderList[meshIndex];
  49861. if (!mesh) {
  49862. continue;
  49863. }
  49864. var boundingInfo = mesh.getBoundingInfo();
  49865. var boundingBox = boundingInfo.boundingBox;
  49866. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49867. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49868. if (tempVector3.x < this._orthoLeft)
  49869. this._orthoLeft = tempVector3.x;
  49870. if (tempVector3.y < this._orthoBottom)
  49871. this._orthoBottom = tempVector3.y;
  49872. if (tempVector3.x > this._orthoRight)
  49873. this._orthoRight = tempVector3.x;
  49874. if (tempVector3.y > this._orthoTop)
  49875. this._orthoTop = tempVector3.y;
  49876. }
  49877. }
  49878. }
  49879. var xOffset = this._orthoRight - this._orthoLeft;
  49880. var yOffset = this._orthoTop - this._orthoBottom;
  49881. 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);
  49882. };
  49883. DirectionalLight.prototype._buildUniformLayout = function () {
  49884. this._uniformBuffer.addUniform("vLightData", 4);
  49885. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49886. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49887. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49888. this._uniformBuffer.addUniform("depthValues", 2);
  49889. this._uniformBuffer.create();
  49890. };
  49891. /**
  49892. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49893. * @param effect The effect to update
  49894. * @param lightIndex The index of the light in the effect to update
  49895. * @returns The directional light
  49896. */
  49897. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49898. if (this.computeTransformedInformation()) {
  49899. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49900. return this;
  49901. }
  49902. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49903. return this;
  49904. };
  49905. /**
  49906. * Gets the minZ used for shadow according to both the scene and the light.
  49907. *
  49908. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49909. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49910. * @param activeCamera The camera we are returning the min for
  49911. * @returns the depth min z
  49912. */
  49913. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49914. return 1;
  49915. };
  49916. /**
  49917. * Gets the maxZ used for shadow according to both the scene and the light.
  49918. *
  49919. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49920. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49921. * @param activeCamera The camera we are returning the max for
  49922. * @returns the depth max z
  49923. */
  49924. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49925. return 1;
  49926. };
  49927. __decorate([
  49928. BABYLON.serialize()
  49929. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49930. __decorate([
  49931. BABYLON.serialize()
  49932. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49933. __decorate([
  49934. BABYLON.serialize()
  49935. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49936. return DirectionalLight;
  49937. }(BABYLON.ShadowLight));
  49938. BABYLON.DirectionalLight = DirectionalLight;
  49939. })(BABYLON || (BABYLON = {}));
  49940. //# sourceMappingURL=babylon.directionalLight.js.map
  49941. var BABYLON;
  49942. (function (BABYLON) {
  49943. /**
  49944. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49945. * These values define a cone of light starting from the position, emitting toward the direction.
  49946. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49947. * and the exponent defines the speed of the decay of the light with distance (reach).
  49948. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49949. */
  49950. var SpotLight = /** @class */ (function (_super) {
  49951. __extends(SpotLight, _super);
  49952. /**
  49953. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49954. * It can cast shadows.
  49955. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49956. * @param name The light friendly name
  49957. * @param position The position of the spot light in the scene
  49958. * @param direction The direction of the light in the scene
  49959. * @param angle The cone angle of the light in Radians
  49960. * @param exponent The light decay speed with the distance from the emission spot
  49961. * @param scene The scene the lights belongs to
  49962. */
  49963. function SpotLight(name, position, direction, angle, exponent, scene) {
  49964. var _this = _super.call(this, name, scene) || this;
  49965. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49966. _this._projectionTextureLightNear = 1e-6;
  49967. _this._projectionTextureLightFar = 1000.0;
  49968. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49969. _this._projectionTextureViewLightDirty = true;
  49970. _this._projectionTextureProjectionLightDirty = true;
  49971. _this._projectionTextureDirty = true;
  49972. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49973. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49974. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49975. _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);
  49976. _this.position = position;
  49977. _this.direction = direction;
  49978. _this.angle = angle;
  49979. _this.exponent = exponent;
  49980. return _this;
  49981. }
  49982. Object.defineProperty(SpotLight.prototype, "angle", {
  49983. /**
  49984. * Gets the cone angle of the spot light in Radians.
  49985. */
  49986. get: function () {
  49987. return this._angle;
  49988. },
  49989. /**
  49990. * Sets the cone angle of the spot light in Radians.
  49991. */
  49992. set: function (value) {
  49993. this._angle = value;
  49994. this._projectionTextureProjectionLightDirty = true;
  49995. this.forceProjectionMatrixCompute();
  49996. },
  49997. enumerable: true,
  49998. configurable: true
  49999. });
  50000. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  50001. /**
  50002. * Allows scaling the angle of the light for shadow generation only.
  50003. */
  50004. get: function () {
  50005. return this._shadowAngleScale;
  50006. },
  50007. /**
  50008. * Allows scaling the angle of the light for shadow generation only.
  50009. */
  50010. set: function (value) {
  50011. this._shadowAngleScale = value;
  50012. this.forceProjectionMatrixCompute();
  50013. },
  50014. enumerable: true,
  50015. configurable: true
  50016. });
  50017. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  50018. /**
  50019. * Allows reading the projecton texture
  50020. */
  50021. get: function () {
  50022. return this._projectionTextureMatrix;
  50023. },
  50024. enumerable: true,
  50025. configurable: true
  50026. });
  50027. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  50028. /**
  50029. * Gets the near clip of the Spotlight for texture projection.
  50030. */
  50031. get: function () {
  50032. return this._projectionTextureLightNear;
  50033. },
  50034. /**
  50035. * Sets the near clip of the Spotlight for texture projection.
  50036. */
  50037. set: function (value) {
  50038. this._projectionTextureLightNear = value;
  50039. this._projectionTextureProjectionLightDirty = true;
  50040. },
  50041. enumerable: true,
  50042. configurable: true
  50043. });
  50044. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  50045. /**
  50046. * Gets the far clip of the Spotlight for texture projection.
  50047. */
  50048. get: function () {
  50049. return this._projectionTextureLightFar;
  50050. },
  50051. /**
  50052. * Sets the far clip of the Spotlight for texture projection.
  50053. */
  50054. set: function (value) {
  50055. this._projectionTextureLightFar = value;
  50056. this._projectionTextureProjectionLightDirty = true;
  50057. },
  50058. enumerable: true,
  50059. configurable: true
  50060. });
  50061. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  50062. /**
  50063. * Gets the Up vector of the Spotlight for texture projection.
  50064. */
  50065. get: function () {
  50066. return this._projectionTextureUpDirection;
  50067. },
  50068. /**
  50069. * Sets the Up vector of the Spotlight for texture projection.
  50070. */
  50071. set: function (value) {
  50072. this._projectionTextureUpDirection = value;
  50073. this._projectionTextureProjectionLightDirty = true;
  50074. },
  50075. enumerable: true,
  50076. configurable: true
  50077. });
  50078. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  50079. /**
  50080. * Gets the projection texture of the light.
  50081. */
  50082. get: function () {
  50083. return this._projectionTexture;
  50084. },
  50085. /**
  50086. * Sets the projection texture of the light.
  50087. */
  50088. set: function (value) {
  50089. this._projectionTexture = value;
  50090. this._projectionTextureDirty = true;
  50091. },
  50092. enumerable: true,
  50093. configurable: true
  50094. });
  50095. /**
  50096. * Returns the string "SpotLight".
  50097. * @returns the class name
  50098. */
  50099. SpotLight.prototype.getClassName = function () {
  50100. return "SpotLight";
  50101. };
  50102. /**
  50103. * Returns the integer 2.
  50104. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  50105. */
  50106. SpotLight.prototype.getTypeID = function () {
  50107. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  50108. };
  50109. /**
  50110. * Overrides the direction setter to recompute the projection texture view light Matrix.
  50111. */
  50112. SpotLight.prototype._setDirection = function (value) {
  50113. _super.prototype._setDirection.call(this, value);
  50114. this._projectionTextureViewLightDirty = true;
  50115. };
  50116. /**
  50117. * Overrides the position setter to recompute the projection texture view light Matrix.
  50118. */
  50119. SpotLight.prototype._setPosition = function (value) {
  50120. _super.prototype._setPosition.call(this, value);
  50121. this._projectionTextureViewLightDirty = true;
  50122. };
  50123. /**
  50124. * 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.
  50125. * Returns the SpotLight.
  50126. */
  50127. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  50128. var activeCamera = this.getScene().activeCamera;
  50129. if (!activeCamera) {
  50130. return;
  50131. }
  50132. this._shadowAngleScale = this._shadowAngleScale || 1;
  50133. var angle = this._shadowAngleScale * this._angle;
  50134. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  50135. };
  50136. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  50137. this._projectionTextureViewLightDirty = false;
  50138. this._projectionTextureDirty = true;
  50139. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  50140. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  50141. };
  50142. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  50143. this._projectionTextureProjectionLightDirty = false;
  50144. this._projectionTextureDirty = true;
  50145. var light_far = this.projectionTextureLightFar;
  50146. var light_near = this.projectionTextureLightNear;
  50147. var P = light_far / (light_far - light_near);
  50148. var Q = -P * light_near;
  50149. var S = 1.0 / Math.tan(this._angle / 2.0);
  50150. var A = 1.0;
  50151. 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);
  50152. };
  50153. /**
  50154. * Main function for light texture projection matrix computing.
  50155. */
  50156. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  50157. this._projectionTextureDirty = false;
  50158. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  50159. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  50160. };
  50161. SpotLight.prototype._buildUniformLayout = function () {
  50162. this._uniformBuffer.addUniform("vLightData", 4);
  50163. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  50164. this._uniformBuffer.addUniform("vLightSpecular", 3);
  50165. this._uniformBuffer.addUniform("vLightDirection", 3);
  50166. this._uniformBuffer.addUniform("shadowsInfo", 3);
  50167. this._uniformBuffer.addUniform("depthValues", 2);
  50168. this._uniformBuffer.create();
  50169. };
  50170. /**
  50171. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  50172. * @param effect The effect to update
  50173. * @param lightIndex The index of the light in the effect to update
  50174. * @returns The spot light
  50175. */
  50176. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  50177. var normalizeDirection;
  50178. if (this.computeTransformedInformation()) {
  50179. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  50180. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  50181. }
  50182. else {
  50183. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  50184. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  50185. }
  50186. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  50187. if (this.projectionTexture && this.projectionTexture.isReady()) {
  50188. if (this._projectionTextureViewLightDirty) {
  50189. this._computeProjectionTextureViewLightMatrix();
  50190. }
  50191. if (this._projectionTextureProjectionLightDirty) {
  50192. this._computeProjectionTextureProjectionLightMatrix();
  50193. }
  50194. if (this._projectionTextureDirty) {
  50195. this._computeProjectionTextureMatrix();
  50196. }
  50197. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  50198. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  50199. }
  50200. return this;
  50201. };
  50202. /**
  50203. * Disposes the light and the associated resources.
  50204. */
  50205. SpotLight.prototype.dispose = function () {
  50206. _super.prototype.dispose.call(this);
  50207. if (this._projectionTexture) {
  50208. this._projectionTexture.dispose();
  50209. }
  50210. };
  50211. __decorate([
  50212. BABYLON.serialize()
  50213. ], SpotLight.prototype, "angle", null);
  50214. __decorate([
  50215. BABYLON.serialize()
  50216. ], SpotLight.prototype, "shadowAngleScale", null);
  50217. __decorate([
  50218. BABYLON.serialize()
  50219. ], SpotLight.prototype, "exponent", void 0);
  50220. __decorate([
  50221. BABYLON.serialize()
  50222. ], SpotLight.prototype, "projectionTextureLightNear", null);
  50223. __decorate([
  50224. BABYLON.serialize()
  50225. ], SpotLight.prototype, "projectionTextureLightFar", null);
  50226. __decorate([
  50227. BABYLON.serialize()
  50228. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  50229. __decorate([
  50230. BABYLON.serializeAsTexture("projectedLightTexture")
  50231. ], SpotLight.prototype, "_projectionTexture", void 0);
  50232. return SpotLight;
  50233. }(BABYLON.ShadowLight));
  50234. BABYLON.SpotLight = SpotLight;
  50235. })(BABYLON || (BABYLON = {}));
  50236. //# sourceMappingURL=babylon.spotLight.js.map
  50237. var BABYLON;
  50238. (function (BABYLON) {
  50239. /**
  50240. * Class used to override all child animations of a given target
  50241. */
  50242. var AnimationPropertiesOverride = /** @class */ (function () {
  50243. function AnimationPropertiesOverride() {
  50244. /**
  50245. * Gets or sets a value indicating if animation blending must be used
  50246. */
  50247. this.enableBlending = false;
  50248. /**
  50249. * Gets or sets the blending speed to use when enableBlending is true
  50250. */
  50251. this.blendingSpeed = 0.01;
  50252. /**
  50253. * Gets or sets the default loop mode to use
  50254. */
  50255. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  50256. }
  50257. return AnimationPropertiesOverride;
  50258. }());
  50259. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  50260. })(BABYLON || (BABYLON = {}));
  50261. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  50262. var BABYLON;
  50263. (function (BABYLON) {
  50264. /**
  50265. * Represents the range of an animation
  50266. */
  50267. var AnimationRange = /** @class */ (function () {
  50268. /**
  50269. * Initializes the range of an animation
  50270. * @param name The name of the animation range
  50271. * @param from The starting frame of the animation
  50272. * @param to The ending frame of the animation
  50273. */
  50274. function AnimationRange(
  50275. /**The name of the animation range**/
  50276. name,
  50277. /**The starting frame of the animation */
  50278. from,
  50279. /**The ending frame of the animation*/
  50280. to) {
  50281. this.name = name;
  50282. this.from = from;
  50283. this.to = to;
  50284. }
  50285. /**
  50286. * Makes a copy of the animation range
  50287. * @returns A copy of the animation range
  50288. */
  50289. AnimationRange.prototype.clone = function () {
  50290. return new AnimationRange(this.name, this.from, this.to);
  50291. };
  50292. return AnimationRange;
  50293. }());
  50294. BABYLON.AnimationRange = AnimationRange;
  50295. /**
  50296. * Composed of a frame, and an action function
  50297. */
  50298. var AnimationEvent = /** @class */ (function () {
  50299. /**
  50300. * Initializes the animation event
  50301. * @param frame The frame for which the event is triggered
  50302. * @param action The event to perform when triggered
  50303. * @param onlyOnce Specifies if the event should be triggered only once
  50304. */
  50305. function AnimationEvent(
  50306. /** The frame for which the event is triggered **/
  50307. frame,
  50308. /** The event to perform when triggered **/
  50309. action,
  50310. /** Specifies if the event should be triggered only once**/
  50311. onlyOnce) {
  50312. this.frame = frame;
  50313. this.action = action;
  50314. this.onlyOnce = onlyOnce;
  50315. /**
  50316. * Specifies if the animation event is done
  50317. */
  50318. this.isDone = false;
  50319. }
  50320. return AnimationEvent;
  50321. }());
  50322. BABYLON.AnimationEvent = AnimationEvent;
  50323. /**
  50324. * A cursor which tracks a point on a path
  50325. */
  50326. var PathCursor = /** @class */ (function () {
  50327. /**
  50328. * Initializes the path cursor
  50329. * @param path The path to track
  50330. */
  50331. function PathCursor(path) {
  50332. this.path = path;
  50333. /**
  50334. * Stores path cursor callbacks for when an onchange event is triggered
  50335. */
  50336. this._onchange = new Array();
  50337. /**
  50338. * The value of the path cursor
  50339. */
  50340. this.value = 0;
  50341. /**
  50342. * The animation array of the path cursor
  50343. */
  50344. this.animations = new Array();
  50345. }
  50346. /**
  50347. * Gets the cursor point on the path
  50348. * @returns A point on the path cursor at the cursor location
  50349. */
  50350. PathCursor.prototype.getPoint = function () {
  50351. var point = this.path.getPointAtLengthPosition(this.value);
  50352. return new BABYLON.Vector3(point.x, 0, point.y);
  50353. };
  50354. /**
  50355. * Moves the cursor ahead by the step amount
  50356. * @param step The amount to move the cursor forward
  50357. * @returns This path cursor
  50358. */
  50359. PathCursor.prototype.moveAhead = function (step) {
  50360. if (step === void 0) { step = 0.002; }
  50361. this.move(step);
  50362. return this;
  50363. };
  50364. /**
  50365. * Moves the cursor behind by the step amount
  50366. * @param step The amount to move the cursor back
  50367. * @returns This path cursor
  50368. */
  50369. PathCursor.prototype.moveBack = function (step) {
  50370. if (step === void 0) { step = 0.002; }
  50371. this.move(-step);
  50372. return this;
  50373. };
  50374. /**
  50375. * Moves the cursor by the step amount
  50376. * If the step amount is greater than one, an exception is thrown
  50377. * @param step The amount to move the cursor
  50378. * @returns This path cursor
  50379. */
  50380. PathCursor.prototype.move = function (step) {
  50381. if (Math.abs(step) > 1) {
  50382. throw "step size should be less than 1.";
  50383. }
  50384. this.value += step;
  50385. this.ensureLimits();
  50386. this.raiseOnChange();
  50387. return this;
  50388. };
  50389. /**
  50390. * Ensures that the value is limited between zero and one
  50391. * @returns This path cursor
  50392. */
  50393. PathCursor.prototype.ensureLimits = function () {
  50394. while (this.value > 1) {
  50395. this.value -= 1;
  50396. }
  50397. while (this.value < 0) {
  50398. this.value += 1;
  50399. }
  50400. return this;
  50401. };
  50402. /**
  50403. * Runs onchange callbacks on change (used by the animation engine)
  50404. * @returns This path cursor
  50405. */
  50406. PathCursor.prototype.raiseOnChange = function () {
  50407. var _this = this;
  50408. this._onchange.forEach(function (f) { return f(_this); });
  50409. return this;
  50410. };
  50411. /**
  50412. * Executes a function on change
  50413. * @param f A path cursor onchange callback
  50414. * @returns This path cursor
  50415. */
  50416. PathCursor.prototype.onchange = function (f) {
  50417. this._onchange.push(f);
  50418. return this;
  50419. };
  50420. return PathCursor;
  50421. }());
  50422. BABYLON.PathCursor = PathCursor;
  50423. /**
  50424. * Enum for the animation key frame interpolation type
  50425. */
  50426. var AnimationKeyInterpolation;
  50427. (function (AnimationKeyInterpolation) {
  50428. /**
  50429. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  50430. */
  50431. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  50432. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  50433. /**
  50434. * Class used to store any kind of animation
  50435. */
  50436. var Animation = /** @class */ (function () {
  50437. /**
  50438. * Initializes the animation
  50439. * @param name Name of the animation
  50440. * @param targetProperty Property to animate
  50441. * @param framePerSecond The frames per second of the animation
  50442. * @param dataType The data type of the animation
  50443. * @param loopMode The loop mode of the animation
  50444. * @param enableBlendings Specifies if blending should be enabled
  50445. */
  50446. function Animation(
  50447. /**Name of the animation */
  50448. name,
  50449. /**Property to animate */
  50450. targetProperty,
  50451. /**The frames per second of the animation */
  50452. framePerSecond,
  50453. /**The data type of the animation */
  50454. dataType,
  50455. /**The loop mode of the animation */
  50456. loopMode,
  50457. /**Specifies if blending should be enabled */
  50458. enableBlending) {
  50459. this.name = name;
  50460. this.targetProperty = targetProperty;
  50461. this.framePerSecond = framePerSecond;
  50462. this.dataType = dataType;
  50463. this.loopMode = loopMode;
  50464. this.enableBlending = enableBlending;
  50465. /**
  50466. * @hidden Internal use only
  50467. */
  50468. this._runtimeAnimations = new Array();
  50469. /**
  50470. * The set of event that will be linked to this animation
  50471. */
  50472. this._events = new Array();
  50473. /**
  50474. * Stores the blending speed of the animation
  50475. */
  50476. this.blendingSpeed = 0.01;
  50477. /**
  50478. * Stores the animation ranges for the animation
  50479. */
  50480. this._ranges = {};
  50481. this.targetPropertyPath = targetProperty.split(".");
  50482. this.dataType = dataType;
  50483. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  50484. }
  50485. /**
  50486. * @hidden Internal use
  50487. */
  50488. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  50489. var dataType = undefined;
  50490. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  50491. dataType = Animation.ANIMATIONTYPE_FLOAT;
  50492. }
  50493. else if (from instanceof BABYLON.Quaternion) {
  50494. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  50495. }
  50496. else if (from instanceof BABYLON.Vector3) {
  50497. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  50498. }
  50499. else if (from instanceof BABYLON.Vector2) {
  50500. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  50501. }
  50502. else if (from instanceof BABYLON.Color3) {
  50503. dataType = Animation.ANIMATIONTYPE_COLOR3;
  50504. }
  50505. else if (from instanceof BABYLON.Size) {
  50506. dataType = Animation.ANIMATIONTYPE_SIZE;
  50507. }
  50508. if (dataType == undefined) {
  50509. return null;
  50510. }
  50511. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  50512. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  50513. animation.setKeys(keys);
  50514. if (easingFunction !== undefined) {
  50515. animation.setEasingFunction(easingFunction);
  50516. }
  50517. return animation;
  50518. };
  50519. /**
  50520. * Sets up an animation
  50521. * @param property The property to animate
  50522. * @param animationType The animation type to apply
  50523. * @param framePerSecond The frames per second of the animation
  50524. * @param easingFunction The easing function used in the animation
  50525. * @returns The created animation
  50526. */
  50527. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  50528. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  50529. animation.setEasingFunction(easingFunction);
  50530. return animation;
  50531. };
  50532. /**
  50533. * Create and start an animation on a node
  50534. * @param name defines the name of the global animation that will be run on all nodes
  50535. * @param node defines the root node where the animation will take place
  50536. * @param targetProperty defines property to animate
  50537. * @param framePerSecond defines the number of frame per second yo use
  50538. * @param totalFrame defines the number of frames in total
  50539. * @param from defines the initial value
  50540. * @param to defines the final value
  50541. * @param loopMode defines which loop mode you want to use (off by default)
  50542. * @param easingFunction defines the easing function to use (linear by default)
  50543. * @param onAnimationEnd defines the callback to call when animation end
  50544. * @returns the animatable created for this animation
  50545. */
  50546. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50547. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50548. if (!animation) {
  50549. return null;
  50550. }
  50551. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50552. };
  50553. /**
  50554. * Create and start an animation on a node and its descendants
  50555. * @param name defines the name of the global animation that will be run on all nodes
  50556. * @param node defines the root node where the animation will take place
  50557. * @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
  50558. * @param targetProperty defines property to animate
  50559. * @param framePerSecond defines the number of frame per second to use
  50560. * @param totalFrame defines the number of frames in total
  50561. * @param from defines the initial value
  50562. * @param to defines the final value
  50563. * @param loopMode defines which loop mode you want to use (off by default)
  50564. * @param easingFunction defines the easing function to use (linear by default)
  50565. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  50566. * @returns the list of animatables created for all nodes
  50567. * @example https://www.babylonjs-playground.com/#MH0VLI
  50568. */
  50569. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50570. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50571. if (!animation) {
  50572. return null;
  50573. }
  50574. var scene = node.getScene();
  50575. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50576. };
  50577. /**
  50578. * Creates a new animation, merges it with the existing animations and starts it
  50579. * @param name Name of the animation
  50580. * @param node Node which contains the scene that begins the animations
  50581. * @param targetProperty Specifies which property to animate
  50582. * @param framePerSecond The frames per second of the animation
  50583. * @param totalFrame The total number of frames
  50584. * @param from The frame at the beginning of the animation
  50585. * @param to The frame at the end of the animation
  50586. * @param loopMode Specifies the loop mode of the animation
  50587. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  50588. * @param onAnimationEnd Callback to run once the animation is complete
  50589. * @returns Nullable animation
  50590. */
  50591. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  50592. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  50593. if (!animation) {
  50594. return null;
  50595. }
  50596. node.animations.push(animation);
  50597. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  50598. };
  50599. /**
  50600. * Transition property of the Camera to the target Value
  50601. * @param property The property to transition
  50602. * @param targetValue The target Value of the property
  50603. * @param host The object where the property to animate belongs
  50604. * @param scene Scene used to run the animation
  50605. * @param frameRate Framerate (in frame/s) to use
  50606. * @param transition The transition type we want to use
  50607. * @param duration The duration of the animation, in milliseconds
  50608. * @param onAnimationEnd Callback trigger at the end of the animation
  50609. * @returns Nullable animation
  50610. */
  50611. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  50612. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  50613. if (duration <= 0) {
  50614. host[property] = targetValue;
  50615. if (onAnimationEnd) {
  50616. onAnimationEnd();
  50617. }
  50618. return null;
  50619. }
  50620. var endFrame = frameRate * (duration / 1000);
  50621. transition.setKeys([{
  50622. frame: 0,
  50623. value: host[property].clone ? host[property].clone() : host[property]
  50624. },
  50625. {
  50626. frame: endFrame,
  50627. value: targetValue
  50628. }]);
  50629. if (!host.animations) {
  50630. host.animations = [];
  50631. }
  50632. host.animations.push(transition);
  50633. var animation = scene.beginAnimation(host, 0, endFrame, false);
  50634. animation.onAnimationEnd = onAnimationEnd;
  50635. return animation;
  50636. };
  50637. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  50638. /**
  50639. * Return the array of runtime animations currently using this animation
  50640. */
  50641. get: function () {
  50642. return this._runtimeAnimations;
  50643. },
  50644. enumerable: true,
  50645. configurable: true
  50646. });
  50647. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  50648. /**
  50649. * Specifies if any of the runtime animations are currently running
  50650. */
  50651. get: function () {
  50652. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  50653. var runtimeAnimation = _a[_i];
  50654. if (!runtimeAnimation.isStopped) {
  50655. return true;
  50656. }
  50657. }
  50658. return false;
  50659. },
  50660. enumerable: true,
  50661. configurable: true
  50662. });
  50663. // Methods
  50664. /**
  50665. * Converts the animation to a string
  50666. * @param fullDetails support for multiple levels of logging within scene loading
  50667. * @returns String form of the animation
  50668. */
  50669. Animation.prototype.toString = function (fullDetails) {
  50670. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  50671. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  50672. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  50673. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  50674. if (fullDetails) {
  50675. ret += ", Ranges: {";
  50676. var first = true;
  50677. for (var name in this._ranges) {
  50678. if (first) {
  50679. ret += ", ";
  50680. first = false;
  50681. }
  50682. ret += name;
  50683. }
  50684. ret += "}";
  50685. }
  50686. return ret;
  50687. };
  50688. /**
  50689. * Add an event to this animation
  50690. * @param event Event to add
  50691. */
  50692. Animation.prototype.addEvent = function (event) {
  50693. this._events.push(event);
  50694. };
  50695. /**
  50696. * Remove all events found at the given frame
  50697. * @param frame The frame to remove events from
  50698. */
  50699. Animation.prototype.removeEvents = function (frame) {
  50700. for (var index = 0; index < this._events.length; index++) {
  50701. if (this._events[index].frame === frame) {
  50702. this._events.splice(index, 1);
  50703. index--;
  50704. }
  50705. }
  50706. };
  50707. /**
  50708. * Retrieves all the events from the animation
  50709. * @returns Events from the animation
  50710. */
  50711. Animation.prototype.getEvents = function () {
  50712. return this._events;
  50713. };
  50714. /**
  50715. * Creates an animation range
  50716. * @param name Name of the animation range
  50717. * @param from Starting frame of the animation range
  50718. * @param to Ending frame of the animation
  50719. */
  50720. Animation.prototype.createRange = function (name, from, to) {
  50721. // check name not already in use; could happen for bones after serialized
  50722. if (!this._ranges[name]) {
  50723. this._ranges[name] = new AnimationRange(name, from, to);
  50724. }
  50725. };
  50726. /**
  50727. * Deletes an animation range by name
  50728. * @param name Name of the animation range to delete
  50729. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  50730. */
  50731. Animation.prototype.deleteRange = function (name, deleteFrames) {
  50732. if (deleteFrames === void 0) { deleteFrames = true; }
  50733. var range = this._ranges[name];
  50734. if (!range) {
  50735. return;
  50736. }
  50737. if (deleteFrames) {
  50738. var from = range.from;
  50739. var to = range.to;
  50740. // this loop MUST go high to low for multiple splices to work
  50741. for (var key = this._keys.length - 1; key >= 0; key--) {
  50742. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  50743. this._keys.splice(key, 1);
  50744. }
  50745. }
  50746. }
  50747. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  50748. };
  50749. /**
  50750. * Gets the animation range by name, or null if not defined
  50751. * @param name Name of the animation range
  50752. * @returns Nullable animation range
  50753. */
  50754. Animation.prototype.getRange = function (name) {
  50755. return this._ranges[name];
  50756. };
  50757. /**
  50758. * Gets the key frames from the animation
  50759. * @returns The key frames of the animation
  50760. */
  50761. Animation.prototype.getKeys = function () {
  50762. return this._keys;
  50763. };
  50764. /**
  50765. * Gets the highest frame rate of the animation
  50766. * @returns Highest frame rate of the animation
  50767. */
  50768. Animation.prototype.getHighestFrame = function () {
  50769. var ret = 0;
  50770. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  50771. if (ret < this._keys[key].frame) {
  50772. ret = this._keys[key].frame;
  50773. }
  50774. }
  50775. return ret;
  50776. };
  50777. /**
  50778. * Gets the easing function of the animation
  50779. * @returns Easing function of the animation
  50780. */
  50781. Animation.prototype.getEasingFunction = function () {
  50782. return this._easingFunction;
  50783. };
  50784. /**
  50785. * Sets the easing function of the animation
  50786. * @param easingFunction A custom mathematical formula for animation
  50787. */
  50788. Animation.prototype.setEasingFunction = function (easingFunction) {
  50789. this._easingFunction = easingFunction;
  50790. };
  50791. /**
  50792. * Interpolates a scalar linearly
  50793. * @param startValue Start value of the animation curve
  50794. * @param endValue End value of the animation curve
  50795. * @param gradient Scalar amount to interpolate
  50796. * @returns Interpolated scalar value
  50797. */
  50798. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  50799. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  50800. };
  50801. /**
  50802. * Interpolates a scalar cubically
  50803. * @param startValue Start value of the animation curve
  50804. * @param outTangent End tangent of the animation
  50805. * @param endValue End value of the animation curve
  50806. * @param inTangent Start tangent of the animation curve
  50807. * @param gradient Scalar amount to interpolate
  50808. * @returns Interpolated scalar value
  50809. */
  50810. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50811. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50812. };
  50813. /**
  50814. * Interpolates a quaternion using a spherical linear interpolation
  50815. * @param startValue Start value of the animation curve
  50816. * @param endValue End value of the animation curve
  50817. * @param gradient Scalar amount to interpolate
  50818. * @returns Interpolated quaternion value
  50819. */
  50820. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50821. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50822. };
  50823. /**
  50824. * Interpolates a quaternion cubically
  50825. * @param startValue Start value of the animation curve
  50826. * @param outTangent End tangent of the animation curve
  50827. * @param endValue End value of the animation curve
  50828. * @param inTangent Start tangent of the animation curve
  50829. * @param gradient Scalar amount to interpolate
  50830. * @returns Interpolated quaternion value
  50831. */
  50832. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50833. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50834. };
  50835. /**
  50836. * Interpolates a Vector3 linearl
  50837. * @param startValue Start value of the animation curve
  50838. * @param endValue End value of the animation curve
  50839. * @param gradient Scalar amount to interpolate
  50840. * @returns Interpolated scalar value
  50841. */
  50842. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50843. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50844. };
  50845. /**
  50846. * Interpolates a Vector3 cubically
  50847. * @param startValue Start value of the animation curve
  50848. * @param outTangent End tangent of the animation
  50849. * @param endValue End value of the animation curve
  50850. * @param inTangent Start tangent of the animation curve
  50851. * @param gradient Scalar amount to interpolate
  50852. * @returns InterpolatedVector3 value
  50853. */
  50854. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50855. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50856. };
  50857. /**
  50858. * Interpolates a Vector2 linearly
  50859. * @param startValue Start value of the animation curve
  50860. * @param endValue End value of the animation curve
  50861. * @param gradient Scalar amount to interpolate
  50862. * @returns Interpolated Vector2 value
  50863. */
  50864. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50865. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50866. };
  50867. /**
  50868. * Interpolates a Vector2 cubically
  50869. * @param startValue Start value of the animation curve
  50870. * @param outTangent End tangent of the animation
  50871. * @param endValue End value of the animation curve
  50872. * @param inTangent Start tangent of the animation curve
  50873. * @param gradient Scalar amount to interpolate
  50874. * @returns Interpolated Vector2 value
  50875. */
  50876. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50877. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50878. };
  50879. /**
  50880. * Interpolates a size linearly
  50881. * @param startValue Start value of the animation curve
  50882. * @param endValue End value of the animation curve
  50883. * @param gradient Scalar amount to interpolate
  50884. * @returns Interpolated Size value
  50885. */
  50886. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50887. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50888. };
  50889. /**
  50890. * Interpolates a Color3 linearly
  50891. * @param startValue Start value of the animation curve
  50892. * @param endValue End value of the animation curve
  50893. * @param gradient Scalar amount to interpolate
  50894. * @returns Interpolated Color3 value
  50895. */
  50896. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50897. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50898. };
  50899. /**
  50900. * @hidden Internal use only
  50901. */
  50902. Animation.prototype._getKeyValue = function (value) {
  50903. if (typeof value === "function") {
  50904. return value();
  50905. }
  50906. return value;
  50907. };
  50908. /**
  50909. * @hidden Internal use only
  50910. */
  50911. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50912. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50913. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50914. }
  50915. var keys = this.getKeys();
  50916. // Try to get a hash to find the right key
  50917. 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));
  50918. if (keys[startKeyIndex].frame >= currentFrame) {
  50919. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50920. startKeyIndex--;
  50921. }
  50922. }
  50923. for (var key = startKeyIndex; key < keys.length; key++) {
  50924. var endKey = keys[key + 1];
  50925. if (endKey.frame >= currentFrame) {
  50926. var startKey = keys[key];
  50927. var startValue = this._getKeyValue(startKey.value);
  50928. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50929. return startValue;
  50930. }
  50931. var endValue = this._getKeyValue(endKey.value);
  50932. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50933. var frameDelta = endKey.frame - startKey.frame;
  50934. // gradient : percent of currentFrame between the frame inf and the frame sup
  50935. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50936. // check for easingFunction and correction of gradient
  50937. var easingFunction = this.getEasingFunction();
  50938. if (easingFunction != null) {
  50939. gradient = easingFunction.ease(gradient);
  50940. }
  50941. switch (this.dataType) {
  50942. // Float
  50943. case Animation.ANIMATIONTYPE_FLOAT:
  50944. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50945. switch (loopMode) {
  50946. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50947. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50948. return floatValue;
  50949. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50950. return offsetValue * repeatCount + floatValue;
  50951. }
  50952. break;
  50953. // Quaternion
  50954. case Animation.ANIMATIONTYPE_QUATERNION:
  50955. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50956. switch (loopMode) {
  50957. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50958. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50959. return quatValue;
  50960. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50961. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50962. }
  50963. return quatValue;
  50964. // Vector3
  50965. case Animation.ANIMATIONTYPE_VECTOR3:
  50966. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50967. switch (loopMode) {
  50968. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50969. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50970. return vec3Value;
  50971. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50972. return vec3Value.add(offsetValue.scale(repeatCount));
  50973. }
  50974. // Vector2
  50975. case Animation.ANIMATIONTYPE_VECTOR2:
  50976. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50977. switch (loopMode) {
  50978. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50979. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50980. return vec2Value;
  50981. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50982. return vec2Value.add(offsetValue.scale(repeatCount));
  50983. }
  50984. // Size
  50985. case Animation.ANIMATIONTYPE_SIZE:
  50986. switch (loopMode) {
  50987. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50988. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50989. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50990. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50991. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50992. }
  50993. // Color3
  50994. case Animation.ANIMATIONTYPE_COLOR3:
  50995. switch (loopMode) {
  50996. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50997. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50998. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50999. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51000. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  51001. }
  51002. // Matrix
  51003. case Animation.ANIMATIONTYPE_MATRIX:
  51004. switch (loopMode) {
  51005. case Animation.ANIMATIONLOOPMODE_CYCLE:
  51006. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  51007. if (Animation.AllowMatricesInterpolation) {
  51008. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  51009. }
  51010. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  51011. return startValue;
  51012. }
  51013. default:
  51014. break;
  51015. }
  51016. break;
  51017. }
  51018. }
  51019. return this._getKeyValue(keys[keys.length - 1].value);
  51020. };
  51021. /**
  51022. * Defines the function to use to interpolate matrices
  51023. * @param startValue defines the start matrix
  51024. * @param endValue defines the end matrix
  51025. * @param gradient defines the gradient between both matrices
  51026. * @param result defines an optional target matrix where to store the interpolation
  51027. * @returns the interpolated matrix
  51028. */
  51029. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  51030. if (Animation.AllowMatrixDecomposeForInterpolation) {
  51031. if (result) {
  51032. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  51033. return result;
  51034. }
  51035. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  51036. }
  51037. if (result) {
  51038. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  51039. return result;
  51040. }
  51041. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  51042. };
  51043. /**
  51044. * Makes a copy of the animation
  51045. * @returns Cloned animation
  51046. */
  51047. Animation.prototype.clone = function () {
  51048. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  51049. clone.enableBlending = this.enableBlending;
  51050. clone.blendingSpeed = this.blendingSpeed;
  51051. if (this._keys) {
  51052. clone.setKeys(this._keys);
  51053. }
  51054. if (this._ranges) {
  51055. clone._ranges = {};
  51056. for (var name in this._ranges) {
  51057. var range = this._ranges[name];
  51058. if (!range) {
  51059. continue;
  51060. }
  51061. clone._ranges[name] = range.clone();
  51062. }
  51063. }
  51064. return clone;
  51065. };
  51066. /**
  51067. * Sets the key frames of the animation
  51068. * @param values The animation key frames to set
  51069. */
  51070. Animation.prototype.setKeys = function (values) {
  51071. this._keys = values.slice(0);
  51072. };
  51073. /**
  51074. * Serializes the animation to an object
  51075. * @returns Serialized object
  51076. */
  51077. Animation.prototype.serialize = function () {
  51078. var serializationObject = {};
  51079. serializationObject.name = this.name;
  51080. serializationObject.property = this.targetProperty;
  51081. serializationObject.framePerSecond = this.framePerSecond;
  51082. serializationObject.dataType = this.dataType;
  51083. serializationObject.loopBehavior = this.loopMode;
  51084. serializationObject.enableBlending = this.enableBlending;
  51085. serializationObject.blendingSpeed = this.blendingSpeed;
  51086. var dataType = this.dataType;
  51087. serializationObject.keys = [];
  51088. var keys = this.getKeys();
  51089. for (var index = 0; index < keys.length; index++) {
  51090. var animationKey = keys[index];
  51091. var key = {};
  51092. key.frame = animationKey.frame;
  51093. switch (dataType) {
  51094. case Animation.ANIMATIONTYPE_FLOAT:
  51095. key.values = [animationKey.value];
  51096. break;
  51097. case Animation.ANIMATIONTYPE_QUATERNION:
  51098. case Animation.ANIMATIONTYPE_MATRIX:
  51099. case Animation.ANIMATIONTYPE_VECTOR3:
  51100. case Animation.ANIMATIONTYPE_COLOR3:
  51101. key.values = animationKey.value.asArray();
  51102. break;
  51103. }
  51104. serializationObject.keys.push(key);
  51105. }
  51106. serializationObject.ranges = [];
  51107. for (var name in this._ranges) {
  51108. var source = this._ranges[name];
  51109. if (!source) {
  51110. continue;
  51111. }
  51112. var range = {};
  51113. range.name = name;
  51114. range.from = source.from;
  51115. range.to = source.to;
  51116. serializationObject.ranges.push(range);
  51117. }
  51118. return serializationObject;
  51119. };
  51120. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  51121. /**
  51122. * Get the float animation type
  51123. */
  51124. get: function () {
  51125. return Animation._ANIMATIONTYPE_FLOAT;
  51126. },
  51127. enumerable: true,
  51128. configurable: true
  51129. });
  51130. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  51131. /**
  51132. * Get the Vector3 animation type
  51133. */
  51134. get: function () {
  51135. return Animation._ANIMATIONTYPE_VECTOR3;
  51136. },
  51137. enumerable: true,
  51138. configurable: true
  51139. });
  51140. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  51141. /**
  51142. * Get the Vectpr2 animation type
  51143. */
  51144. get: function () {
  51145. return Animation._ANIMATIONTYPE_VECTOR2;
  51146. },
  51147. enumerable: true,
  51148. configurable: true
  51149. });
  51150. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  51151. /**
  51152. * Get the Size animation type
  51153. */
  51154. get: function () {
  51155. return Animation._ANIMATIONTYPE_SIZE;
  51156. },
  51157. enumerable: true,
  51158. configurable: true
  51159. });
  51160. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  51161. /**
  51162. * Get the Quaternion animation type
  51163. */
  51164. get: function () {
  51165. return Animation._ANIMATIONTYPE_QUATERNION;
  51166. },
  51167. enumerable: true,
  51168. configurable: true
  51169. });
  51170. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  51171. /**
  51172. * Get the Matrix animation type
  51173. */
  51174. get: function () {
  51175. return Animation._ANIMATIONTYPE_MATRIX;
  51176. },
  51177. enumerable: true,
  51178. configurable: true
  51179. });
  51180. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  51181. /**
  51182. * Get the Color3 animation type
  51183. */
  51184. get: function () {
  51185. return Animation._ANIMATIONTYPE_COLOR3;
  51186. },
  51187. enumerable: true,
  51188. configurable: true
  51189. });
  51190. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  51191. /**
  51192. * Get the Relative Loop Mode
  51193. */
  51194. get: function () {
  51195. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  51196. },
  51197. enumerable: true,
  51198. configurable: true
  51199. });
  51200. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  51201. /**
  51202. * Get the Cycle Loop Mode
  51203. */
  51204. get: function () {
  51205. return Animation._ANIMATIONLOOPMODE_CYCLE;
  51206. },
  51207. enumerable: true,
  51208. configurable: true
  51209. });
  51210. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  51211. /**
  51212. * Get the Constant Loop Mode
  51213. */
  51214. get: function () {
  51215. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  51216. },
  51217. enumerable: true,
  51218. configurable: true
  51219. });
  51220. /** @hidden */
  51221. Animation._UniversalLerp = function (left, right, amount) {
  51222. var constructor = left.constructor;
  51223. if (constructor.Lerp) { // Lerp supported
  51224. return constructor.Lerp(left, right, amount);
  51225. }
  51226. else if (constructor.Slerp) { // Slerp supported
  51227. return constructor.Slerp(left, right, amount);
  51228. }
  51229. else if (left.toFixed) { // Number
  51230. return left * (1.0 - amount) + amount * right;
  51231. }
  51232. else { // Blending not supported
  51233. return right;
  51234. }
  51235. };
  51236. /**
  51237. * Parses an animation object and creates an animation
  51238. * @param parsedAnimation Parsed animation object
  51239. * @returns Animation object
  51240. */
  51241. Animation.Parse = function (parsedAnimation) {
  51242. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  51243. var dataType = parsedAnimation.dataType;
  51244. var keys = [];
  51245. var data;
  51246. var index;
  51247. if (parsedAnimation.enableBlending) {
  51248. animation.enableBlending = parsedAnimation.enableBlending;
  51249. }
  51250. if (parsedAnimation.blendingSpeed) {
  51251. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  51252. }
  51253. for (index = 0; index < parsedAnimation.keys.length; index++) {
  51254. var key = parsedAnimation.keys[index];
  51255. var inTangent;
  51256. var outTangent;
  51257. switch (dataType) {
  51258. case Animation.ANIMATIONTYPE_FLOAT:
  51259. data = key.values[0];
  51260. if (key.values.length >= 1) {
  51261. inTangent = key.values[1];
  51262. }
  51263. if (key.values.length >= 2) {
  51264. outTangent = key.values[2];
  51265. }
  51266. break;
  51267. case Animation.ANIMATIONTYPE_QUATERNION:
  51268. data = BABYLON.Quaternion.FromArray(key.values);
  51269. if (key.values.length >= 8) {
  51270. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  51271. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  51272. inTangent = _inTangent;
  51273. }
  51274. }
  51275. if (key.values.length >= 12) {
  51276. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  51277. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  51278. outTangent = _outTangent;
  51279. }
  51280. }
  51281. break;
  51282. case Animation.ANIMATIONTYPE_MATRIX:
  51283. data = BABYLON.Matrix.FromArray(key.values);
  51284. break;
  51285. case Animation.ANIMATIONTYPE_COLOR3:
  51286. data = BABYLON.Color3.FromArray(key.values);
  51287. break;
  51288. case Animation.ANIMATIONTYPE_VECTOR3:
  51289. default:
  51290. data = BABYLON.Vector3.FromArray(key.values);
  51291. break;
  51292. }
  51293. var keyData = {};
  51294. keyData.frame = key.frame;
  51295. keyData.value = data;
  51296. if (inTangent != undefined) {
  51297. keyData.inTangent = inTangent;
  51298. }
  51299. if (outTangent != undefined) {
  51300. keyData.outTangent = outTangent;
  51301. }
  51302. keys.push(keyData);
  51303. }
  51304. animation.setKeys(keys);
  51305. if (parsedAnimation.ranges) {
  51306. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  51307. data = parsedAnimation.ranges[index];
  51308. animation.createRange(data.name, data.from, data.to);
  51309. }
  51310. }
  51311. return animation;
  51312. };
  51313. /**
  51314. * Appends the serialized animations from the source animations
  51315. * @param source Source containing the animations
  51316. * @param destination Target to store the animations
  51317. */
  51318. Animation.AppendSerializedAnimations = function (source, destination) {
  51319. if (source.animations) {
  51320. destination.animations = [];
  51321. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  51322. var animation = source.animations[animationIndex];
  51323. destination.animations.push(animation.serialize());
  51324. }
  51325. }
  51326. };
  51327. /**
  51328. * Use matrix interpolation instead of using direct key value when animating matrices
  51329. */
  51330. Animation.AllowMatricesInterpolation = false;
  51331. /**
  51332. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  51333. */
  51334. Animation.AllowMatrixDecomposeForInterpolation = true;
  51335. // Statics
  51336. /**
  51337. * Float animation type
  51338. */
  51339. Animation._ANIMATIONTYPE_FLOAT = 0;
  51340. /**
  51341. * Vector3 animation type
  51342. */
  51343. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  51344. /**
  51345. * Quaternion animation type
  51346. */
  51347. Animation._ANIMATIONTYPE_QUATERNION = 2;
  51348. /**
  51349. * Matrix animation type
  51350. */
  51351. Animation._ANIMATIONTYPE_MATRIX = 3;
  51352. /**
  51353. * Color3 animation type
  51354. */
  51355. Animation._ANIMATIONTYPE_COLOR3 = 4;
  51356. /**
  51357. * Vector2 animation type
  51358. */
  51359. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  51360. /**
  51361. * Size animation type
  51362. */
  51363. Animation._ANIMATIONTYPE_SIZE = 6;
  51364. /**
  51365. * Relative Loop Mode
  51366. */
  51367. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  51368. /**
  51369. * Cycle Loop Mode
  51370. */
  51371. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  51372. /**
  51373. * Constant Loop Mode
  51374. */
  51375. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  51376. return Animation;
  51377. }());
  51378. BABYLON.Animation = Animation;
  51379. })(BABYLON || (BABYLON = {}));
  51380. //# sourceMappingURL=babylon.animation.js.map
  51381. var BABYLON;
  51382. (function (BABYLON) {
  51383. /**
  51384. * This class defines the direct association between an animation and a target
  51385. */
  51386. var TargetedAnimation = /** @class */ (function () {
  51387. function TargetedAnimation() {
  51388. }
  51389. return TargetedAnimation;
  51390. }());
  51391. BABYLON.TargetedAnimation = TargetedAnimation;
  51392. /**
  51393. * Use this class to create coordinated animations on multiple targets
  51394. */
  51395. var AnimationGroup = /** @class */ (function () {
  51396. function AnimationGroup(name, scene) {
  51397. if (scene === void 0) { scene = null; }
  51398. this.name = name;
  51399. this._targetedAnimations = new Array();
  51400. this._animatables = new Array();
  51401. this._from = Number.MAX_VALUE;
  51402. this._to = -Number.MAX_VALUE;
  51403. this._speedRatio = 1;
  51404. this.onAnimationEndObservable = new BABYLON.Observable();
  51405. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  51406. this._scene.animationGroups.push(this);
  51407. }
  51408. Object.defineProperty(AnimationGroup.prototype, "from", {
  51409. /**
  51410. * Gets the first frame
  51411. */
  51412. get: function () {
  51413. return this._from;
  51414. },
  51415. enumerable: true,
  51416. configurable: true
  51417. });
  51418. Object.defineProperty(AnimationGroup.prototype, "to", {
  51419. /**
  51420. * Gets the last frame
  51421. */
  51422. get: function () {
  51423. return this._to;
  51424. },
  51425. enumerable: true,
  51426. configurable: true
  51427. });
  51428. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  51429. /**
  51430. * Define if the animations are started
  51431. */
  51432. get: function () {
  51433. return this._isStarted;
  51434. },
  51435. enumerable: true,
  51436. configurable: true
  51437. });
  51438. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  51439. /**
  51440. * Gets or sets the speed ratio to use for all animations
  51441. */
  51442. get: function () {
  51443. return this._speedRatio;
  51444. },
  51445. /**
  51446. * Gets or sets the speed ratio to use for all animations
  51447. */
  51448. set: function (value) {
  51449. if (this._speedRatio === value) {
  51450. return;
  51451. }
  51452. this._speedRatio = value;
  51453. for (var index = 0; index < this._animatables.length; index++) {
  51454. var animatable = this._animatables[index];
  51455. animatable.speedRatio = this._speedRatio;
  51456. }
  51457. },
  51458. enumerable: true,
  51459. configurable: true
  51460. });
  51461. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  51462. /**
  51463. * Gets the targeted animations for this animation group
  51464. */
  51465. get: function () {
  51466. return this._targetedAnimations;
  51467. },
  51468. enumerable: true,
  51469. configurable: true
  51470. });
  51471. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  51472. /**
  51473. * returning the list of animatables controlled by this animation group.
  51474. */
  51475. get: function () {
  51476. return this._animatables;
  51477. },
  51478. enumerable: true,
  51479. configurable: true
  51480. });
  51481. /**
  51482. * Add an animation (with its target) in the group
  51483. * @param animation defines the animation we want to add
  51484. * @param target defines the target of the animation
  51485. * @returns the {BABYLON.TargetedAnimation} object
  51486. */
  51487. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  51488. var targetedAnimation = {
  51489. animation: animation,
  51490. target: target
  51491. };
  51492. var keys = animation.getKeys();
  51493. if (this._from > keys[0].frame) {
  51494. this._from = keys[0].frame;
  51495. }
  51496. if (this._to < keys[keys.length - 1].frame) {
  51497. this._to = keys[keys.length - 1].frame;
  51498. }
  51499. this._targetedAnimations.push(targetedAnimation);
  51500. return targetedAnimation;
  51501. };
  51502. /**
  51503. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  51504. * It can add constant keys at begin or end
  51505. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  51506. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  51507. */
  51508. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  51509. if (beginFrame === void 0) { beginFrame = null; }
  51510. if (endFrame === void 0) { endFrame = null; }
  51511. if (beginFrame == null)
  51512. beginFrame = this._from;
  51513. if (endFrame == null)
  51514. endFrame = this._to;
  51515. for (var index = 0; index < this._targetedAnimations.length; index++) {
  51516. var targetedAnimation = this._targetedAnimations[index];
  51517. var keys = targetedAnimation.animation.getKeys();
  51518. var startKey = keys[0];
  51519. var endKey = keys[keys.length - 1];
  51520. if (startKey.frame > beginFrame) {
  51521. var newKey = {
  51522. frame: beginFrame,
  51523. value: startKey.value,
  51524. inTangent: startKey.inTangent,
  51525. outTangent: startKey.outTangent,
  51526. interpolation: startKey.interpolation
  51527. };
  51528. keys.splice(0, 0, newKey);
  51529. }
  51530. if (endKey.frame < endFrame) {
  51531. var newKey = {
  51532. frame: endFrame,
  51533. value: endKey.value,
  51534. inTangent: endKey.outTangent,
  51535. outTangent: endKey.outTangent,
  51536. interpolation: endKey.interpolation
  51537. };
  51538. keys.push(newKey);
  51539. }
  51540. }
  51541. this._from = beginFrame;
  51542. this._to = endFrame;
  51543. return this;
  51544. };
  51545. /**
  51546. * Start all animations on given targets
  51547. * @param loop defines if animations must loop
  51548. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  51549. * @param from defines the from key (optional)
  51550. * @param to defines the to key (optional)
  51551. * @returns the current animation group
  51552. */
  51553. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  51554. var _this = this;
  51555. if (loop === void 0) { loop = false; }
  51556. if (speedRatio === void 0) { speedRatio = 1; }
  51557. if (this._isStarted || this._targetedAnimations.length === 0) {
  51558. return this;
  51559. }
  51560. var _loop_1 = function (targetedAnimation) {
  51561. 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 () {
  51562. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  51563. }));
  51564. };
  51565. var this_1 = this;
  51566. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  51567. var targetedAnimation = _a[_i];
  51568. _loop_1(targetedAnimation);
  51569. }
  51570. this._speedRatio = speedRatio;
  51571. this._isStarted = true;
  51572. return this;
  51573. };
  51574. /**
  51575. * Pause all animations
  51576. */
  51577. AnimationGroup.prototype.pause = function () {
  51578. if (!this._isStarted) {
  51579. return this;
  51580. }
  51581. for (var index = 0; index < this._animatables.length; index++) {
  51582. var animatable = this._animatables[index];
  51583. animatable.pause();
  51584. }
  51585. return this;
  51586. };
  51587. /**
  51588. * Play all animations to initial state
  51589. * This function will start() the animations if they were not started or will restart() them if they were paused
  51590. * @param loop defines if animations must loop
  51591. */
  51592. AnimationGroup.prototype.play = function (loop) {
  51593. if (this.isStarted) {
  51594. if (loop !== undefined) {
  51595. for (var index = 0; index < this._animatables.length; index++) {
  51596. var animatable = this._animatables[index];
  51597. animatable.loopAnimation = loop;
  51598. }
  51599. }
  51600. this.restart();
  51601. }
  51602. else {
  51603. this.start(loop, this._speedRatio);
  51604. }
  51605. return this;
  51606. };
  51607. /**
  51608. * Reset all animations to initial state
  51609. */
  51610. AnimationGroup.prototype.reset = function () {
  51611. if (!this._isStarted) {
  51612. return this;
  51613. }
  51614. for (var index = 0; index < this._animatables.length; index++) {
  51615. var animatable = this._animatables[index];
  51616. animatable.reset();
  51617. }
  51618. return this;
  51619. };
  51620. /**
  51621. * Restart animations from key 0
  51622. */
  51623. AnimationGroup.prototype.restart = function () {
  51624. if (!this._isStarted) {
  51625. return this;
  51626. }
  51627. for (var index = 0; index < this._animatables.length; index++) {
  51628. var animatable = this._animatables[index];
  51629. animatable.restart();
  51630. }
  51631. return this;
  51632. };
  51633. /**
  51634. * Stop all animations
  51635. */
  51636. AnimationGroup.prototype.stop = function () {
  51637. if (!this._isStarted) {
  51638. return this;
  51639. }
  51640. for (var index = 0; index < this._animatables.length; index++) {
  51641. var animatable = this._animatables[index];
  51642. animatable.stop();
  51643. }
  51644. this._isStarted = false;
  51645. return this;
  51646. };
  51647. /**
  51648. * Set animation weight for all animatables
  51649. * @param weight defines the weight to use
  51650. * @return the animationGroup
  51651. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51652. */
  51653. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  51654. for (var index = 0; index < this._animatables.length; index++) {
  51655. var animatable = this._animatables[index];
  51656. animatable.weight = weight;
  51657. }
  51658. return this;
  51659. };
  51660. /**
  51661. * Synchronize and normalize all animatables with a source animatable
  51662. * @param root defines the root animatable to synchronize with
  51663. * @return the animationGroup
  51664. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  51665. */
  51666. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  51667. for (var index = 0; index < this._animatables.length; index++) {
  51668. var animatable = this._animatables[index];
  51669. animatable.syncWith(root);
  51670. }
  51671. return this;
  51672. };
  51673. /**
  51674. * Goes to a specific frame in this animation group
  51675. * @param frame the frame number to go to
  51676. * @return the animationGroup
  51677. */
  51678. AnimationGroup.prototype.goToFrame = function (frame) {
  51679. if (!this._isStarted) {
  51680. return this;
  51681. }
  51682. for (var index = 0; index < this._animatables.length; index++) {
  51683. var animatable = this._animatables[index];
  51684. animatable.goToFrame(frame);
  51685. }
  51686. return this;
  51687. };
  51688. /**
  51689. * Dispose all associated resources
  51690. */
  51691. AnimationGroup.prototype.dispose = function () {
  51692. this._targetedAnimations = [];
  51693. this._animatables = [];
  51694. var index = this._scene.animationGroups.indexOf(this);
  51695. if (index > -1) {
  51696. this._scene.animationGroups.splice(index, 1);
  51697. }
  51698. };
  51699. return AnimationGroup;
  51700. }());
  51701. BABYLON.AnimationGroup = AnimationGroup;
  51702. })(BABYLON || (BABYLON = {}));
  51703. //# sourceMappingURL=babylon.animationGroup.js.map
  51704. var BABYLON;
  51705. (function (BABYLON) {
  51706. /**
  51707. * Defines a runtime animation
  51708. */
  51709. var RuntimeAnimation = /** @class */ (function () {
  51710. /**
  51711. * Create a new RuntimeAnimation object
  51712. * @param target defines the target of the animation
  51713. * @param animation defines the source animation object
  51714. * @param scene defines the hosting scene
  51715. * @param host defines the initiating Animatable
  51716. */
  51717. function RuntimeAnimation(target, animation, scene, host) {
  51718. /**
  51719. * The current frame of the runtime animation
  51720. */
  51721. this._currentFrame = 0;
  51722. /**
  51723. * The original value of the runtime animation
  51724. */
  51725. this._originalValue = new Array();
  51726. /**
  51727. * The offsets cache of the runtime animation
  51728. */
  51729. this._offsetsCache = {};
  51730. /**
  51731. * The high limits cache of the runtime animation
  51732. */
  51733. this._highLimitsCache = {};
  51734. /**
  51735. * Specifies if the runtime animation has been stopped
  51736. */
  51737. this._stopped = false;
  51738. /**
  51739. * The blending factor of the runtime animation
  51740. */
  51741. this._blendingFactor = 0;
  51742. /**
  51743. * The target path of the runtime animation
  51744. */
  51745. this._targetPath = "";
  51746. /**
  51747. * The weight of the runtime animation
  51748. */
  51749. this._weight = 1.0;
  51750. /**
  51751. * The ratio offset of the runtime animation
  51752. */
  51753. this._ratioOffset = 0;
  51754. /**
  51755. * The previous delay of the runtime animation
  51756. */
  51757. this._previousDelay = 0;
  51758. /**
  51759. * The previous ratio of the runtime animation
  51760. */
  51761. this._previousRatio = 0;
  51762. this._animation = animation;
  51763. this._target = target;
  51764. this._scene = scene;
  51765. this._host = host;
  51766. animation._runtimeAnimations.push(this);
  51767. }
  51768. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  51769. /**
  51770. * Gets the current frame of the runtime animation
  51771. */
  51772. get: function () {
  51773. return this._currentFrame;
  51774. },
  51775. enumerable: true,
  51776. configurable: true
  51777. });
  51778. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51779. /**
  51780. * Gets the weight of the runtime animation
  51781. */
  51782. get: function () {
  51783. return this._weight;
  51784. },
  51785. enumerable: true,
  51786. configurable: true
  51787. });
  51788. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51789. /**
  51790. * Gets the current value of the runtime animation
  51791. */
  51792. get: function () {
  51793. return this._currentValue;
  51794. },
  51795. enumerable: true,
  51796. configurable: true
  51797. });
  51798. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51799. /**
  51800. * Gets the target path of the runtime animation
  51801. */
  51802. get: function () {
  51803. return this._targetPath;
  51804. },
  51805. enumerable: true,
  51806. configurable: true
  51807. });
  51808. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51809. /**
  51810. * Gets the actual target of the runtime animation
  51811. */
  51812. get: function () {
  51813. return this._activeTarget;
  51814. },
  51815. enumerable: true,
  51816. configurable: true
  51817. });
  51818. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51819. /**
  51820. * Gets the animation from the runtime animation
  51821. */
  51822. get: function () {
  51823. return this._animation;
  51824. },
  51825. enumerable: true,
  51826. configurable: true
  51827. });
  51828. /**
  51829. * Resets the runtime animation to the beginning
  51830. * @param restoreOriginal defines whether to restore the target property to the original value
  51831. */
  51832. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51833. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51834. if (restoreOriginal) {
  51835. if (this._target instanceof Array) {
  51836. var index = 0;
  51837. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51838. var target = _a[_i];
  51839. if (this._originalValue[index] !== undefined) {
  51840. this._setValue(target, this._originalValue[index], -1);
  51841. }
  51842. index++;
  51843. }
  51844. }
  51845. else {
  51846. if (this._originalValue[0] !== undefined) {
  51847. this._setValue(this._target, this._originalValue[0], -1);
  51848. }
  51849. }
  51850. }
  51851. this._offsetsCache = {};
  51852. this._highLimitsCache = {};
  51853. this._currentFrame = 0;
  51854. this._blendingFactor = 0;
  51855. this._originalValue = new Array();
  51856. };
  51857. /**
  51858. * Specifies if the runtime animation is stopped
  51859. * @returns Boolean specifying if the runtime animation is stopped
  51860. */
  51861. RuntimeAnimation.prototype.isStopped = function () {
  51862. return this._stopped;
  51863. };
  51864. /**
  51865. * Disposes of the runtime animation
  51866. */
  51867. RuntimeAnimation.prototype.dispose = function () {
  51868. var index = this._animation.runtimeAnimations.indexOf(this);
  51869. if (index > -1) {
  51870. this._animation.runtimeAnimations.splice(index, 1);
  51871. }
  51872. };
  51873. /**
  51874. * Interpolates the animation from the current frame
  51875. * @param currentFrame The frame to interpolate the animation to
  51876. * @param repeatCount The number of times that the animation should loop
  51877. * @param loopMode The type of looping mode to use
  51878. * @param offsetValue Animation offset value
  51879. * @param highLimitValue The high limit value
  51880. * @returns The interpolated value
  51881. */
  51882. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51883. this._currentFrame = currentFrame;
  51884. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51885. this._workValue = BABYLON.Matrix.Zero();
  51886. }
  51887. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51888. };
  51889. /**
  51890. * Apply the interpolated value to the target
  51891. * @param currentValue defines the value computed by the animation
  51892. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51893. */
  51894. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51895. if (weight === void 0) { weight = 1.0; }
  51896. if (this._target instanceof Array) {
  51897. var index = 0;
  51898. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51899. var target = _a[_i];
  51900. this._setValue(target, currentValue, weight, index);
  51901. index++;
  51902. }
  51903. }
  51904. else {
  51905. this._setValue(this._target, currentValue, weight);
  51906. }
  51907. };
  51908. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51909. if (targetIndex === void 0) { targetIndex = 0; }
  51910. // Set value
  51911. var path;
  51912. var destination;
  51913. var targetPropertyPath = this._animation.targetPropertyPath;
  51914. if (targetPropertyPath.length > 1) {
  51915. var property = target[targetPropertyPath[0]];
  51916. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51917. property = property[targetPropertyPath[index]];
  51918. }
  51919. path = targetPropertyPath[targetPropertyPath.length - 1];
  51920. destination = property;
  51921. }
  51922. else {
  51923. path = targetPropertyPath[0];
  51924. destination = target;
  51925. }
  51926. this._targetPath = path;
  51927. this._activeTarget = destination;
  51928. this._weight = weight;
  51929. if (this._originalValue[targetIndex] === undefined) {
  51930. var originalValue = void 0;
  51931. if (destination.getRestPose && path === "_matrix") { // For bones
  51932. originalValue = destination.getRestPose();
  51933. }
  51934. else {
  51935. originalValue = destination[path];
  51936. }
  51937. if (originalValue && originalValue.clone) {
  51938. this._originalValue[targetIndex] = originalValue.clone();
  51939. }
  51940. else {
  51941. this._originalValue[targetIndex] = originalValue;
  51942. }
  51943. }
  51944. // Blending
  51945. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51946. if (enableBlending && this._blendingFactor <= 1.0) {
  51947. if (!this._originalBlendValue) {
  51948. var originalValue = destination[path];
  51949. if (originalValue.clone) {
  51950. this._originalBlendValue = originalValue.clone();
  51951. }
  51952. else {
  51953. this._originalBlendValue = originalValue;
  51954. }
  51955. }
  51956. if (this._originalBlendValue.m) { // Matrix
  51957. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51958. if (this._currentValue) {
  51959. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51960. }
  51961. else {
  51962. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51963. }
  51964. }
  51965. else {
  51966. if (this._currentValue) {
  51967. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51968. }
  51969. else {
  51970. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51971. }
  51972. }
  51973. }
  51974. else {
  51975. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51976. }
  51977. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51978. this._blendingFactor += blendingSpeed;
  51979. }
  51980. else {
  51981. this._currentValue = currentValue;
  51982. }
  51983. if (weight !== -1.0) {
  51984. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51985. }
  51986. else {
  51987. destination[path] = this._currentValue;
  51988. }
  51989. if (target.markAsDirty) {
  51990. target.markAsDirty(this._animation.targetProperty);
  51991. }
  51992. };
  51993. /**
  51994. * Gets the loop pmode of the runtime animation
  51995. * @returns Loop Mode
  51996. */
  51997. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51998. if (this._target && this._target.animationPropertiesOverride) {
  51999. return this._target.animationPropertiesOverride.loopMode;
  52000. }
  52001. return this._animation.loopMode;
  52002. };
  52003. /**
  52004. * Move the current animation to a given frame
  52005. * @param frame defines the frame to move to
  52006. */
  52007. RuntimeAnimation.prototype.goToFrame = function (frame) {
  52008. var keys = this._animation.getKeys();
  52009. if (frame < keys[0].frame) {
  52010. frame = keys[0].frame;
  52011. }
  52012. else if (frame > keys[keys.length - 1].frame) {
  52013. frame = keys[keys.length - 1].frame;
  52014. }
  52015. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  52016. this.setValue(currentValue, -1);
  52017. };
  52018. /**
  52019. * @hidden Internal use only
  52020. */
  52021. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  52022. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  52023. this._ratioOffset = this._previousRatio - newRatio;
  52024. };
  52025. /**
  52026. * Execute the current animation
  52027. * @param delay defines the delay to add to the current frame
  52028. * @param from defines the lower bound of the animation range
  52029. * @param to defines the upper bound of the animation range
  52030. * @param loop defines if the current animation must loop
  52031. * @param speedRatio defines the current speed ratio
  52032. * @param weight defines the weight of the animation (default is -1 so no weight)
  52033. * @returns a boolean indicating if the animation has ended
  52034. */
  52035. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  52036. if (weight === void 0) { weight = -1.0; }
  52037. var targetPropertyPath = this._animation.targetPropertyPath;
  52038. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  52039. this._stopped = true;
  52040. return false;
  52041. }
  52042. var returnValue = true;
  52043. var keys = this._animation.getKeys();
  52044. // Adding a start key at frame 0 if missing
  52045. if (keys[0].frame !== 0) {
  52046. var newKey = { frame: 0, value: keys[0].value };
  52047. keys.splice(0, 0, newKey);
  52048. }
  52049. // Check limits
  52050. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  52051. from = keys[0].frame;
  52052. }
  52053. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  52054. to = keys[keys.length - 1].frame;
  52055. }
  52056. //to and from cannot be the same key
  52057. if (from === to) {
  52058. if (from > keys[0].frame) {
  52059. from--;
  52060. }
  52061. else if (to < keys[keys.length - 1].frame) {
  52062. to++;
  52063. }
  52064. }
  52065. // Compute ratio
  52066. var range = to - from;
  52067. var offsetValue;
  52068. // ratio represents the frame delta between from and to
  52069. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  52070. var highLimitValue = 0;
  52071. this._previousDelay = delay;
  52072. this._previousRatio = ratio;
  52073. if (((to > from && ratio > range) || (from > to && ratio < range)) && !loop) { // If we are out of range and not looping get back to caller
  52074. returnValue = false;
  52075. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  52076. }
  52077. else {
  52078. // Get max value if required
  52079. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  52080. var keyOffset = to.toString() + from.toString();
  52081. if (!this._offsetsCache[keyOffset]) {
  52082. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52083. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  52084. switch (this._animation.dataType) {
  52085. // Float
  52086. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52087. this._offsetsCache[keyOffset] = toValue - fromValue;
  52088. break;
  52089. // Quaternion
  52090. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52091. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52092. break;
  52093. // Vector3
  52094. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52095. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52096. // Vector2
  52097. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52098. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52099. // Size
  52100. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52101. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52102. // Color3
  52103. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52104. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  52105. default:
  52106. break;
  52107. }
  52108. this._highLimitsCache[keyOffset] = toValue;
  52109. }
  52110. highLimitValue = this._highLimitsCache[keyOffset];
  52111. offsetValue = this._offsetsCache[keyOffset];
  52112. }
  52113. }
  52114. if (offsetValue === undefined) {
  52115. switch (this._animation.dataType) {
  52116. // Float
  52117. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  52118. offsetValue = 0;
  52119. break;
  52120. // Quaternion
  52121. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  52122. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  52123. break;
  52124. // Vector3
  52125. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  52126. offsetValue = BABYLON.Vector3.Zero();
  52127. break;
  52128. // Vector2
  52129. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  52130. offsetValue = BABYLON.Vector2.Zero();
  52131. break;
  52132. // Size
  52133. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  52134. offsetValue = BABYLON.Size.Zero();
  52135. break;
  52136. // Color3
  52137. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  52138. offsetValue = BABYLON.Color3.Black();
  52139. }
  52140. }
  52141. // Compute value
  52142. var repeatCount = (ratio / range) >> 0;
  52143. var currentFrame = returnValue ? from + ratio % range : to;
  52144. // Need to normalize?
  52145. if (this._host && this._host.syncRoot) {
  52146. var syncRoot = this._host.syncRoot;
  52147. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  52148. currentFrame = from + (to - from) * hostNormalizedFrame;
  52149. }
  52150. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  52151. // Set value
  52152. this.setValue(currentValue, weight);
  52153. // Check events
  52154. var events = this._animation.getEvents();
  52155. for (var index = 0; index < events.length; index++) {
  52156. // Make sure current frame has passed event frame and that event frame is within the current range
  52157. // Also, handle both forward and reverse animations
  52158. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  52159. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  52160. var event = events[index];
  52161. if (!event.isDone) {
  52162. // If event should be done only once, remove it.
  52163. if (event.onlyOnce) {
  52164. events.splice(index, 1);
  52165. index--;
  52166. }
  52167. event.isDone = true;
  52168. event.action();
  52169. } // Don't do anything if the event has already be done.
  52170. }
  52171. else if (events[index].isDone && !events[index].onlyOnce) {
  52172. // reset event, the animation is looping
  52173. events[index].isDone = false;
  52174. }
  52175. }
  52176. if (!returnValue) {
  52177. this._stopped = true;
  52178. }
  52179. return returnValue;
  52180. };
  52181. return RuntimeAnimation;
  52182. }());
  52183. BABYLON.RuntimeAnimation = RuntimeAnimation;
  52184. })(BABYLON || (BABYLON = {}));
  52185. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  52186. var BABYLON;
  52187. (function (BABYLON) {
  52188. var Animatable = /** @class */ (function () {
  52189. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  52190. if (fromFrame === void 0) { fromFrame = 0; }
  52191. if (toFrame === void 0) { toFrame = 100; }
  52192. if (loopAnimation === void 0) { loopAnimation = false; }
  52193. if (speedRatio === void 0) { speedRatio = 1.0; }
  52194. this.target = target;
  52195. this.fromFrame = fromFrame;
  52196. this.toFrame = toFrame;
  52197. this.loopAnimation = loopAnimation;
  52198. this.onAnimationEnd = onAnimationEnd;
  52199. this._localDelayOffset = null;
  52200. this._pausedDelay = null;
  52201. this._runtimeAnimations = new Array();
  52202. this._paused = false;
  52203. this._speedRatio = 1;
  52204. this._weight = -1.0;
  52205. this.animationStarted = false;
  52206. this._scene = scene;
  52207. if (animations) {
  52208. this.appendAnimations(target, animations);
  52209. }
  52210. this._speedRatio = speedRatio;
  52211. scene._activeAnimatables.push(this);
  52212. }
  52213. Object.defineProperty(Animatable.prototype, "syncRoot", {
  52214. /**
  52215. * Gets the root Animatable used to synchronize and normalize animations
  52216. */
  52217. get: function () {
  52218. return this._syncRoot;
  52219. },
  52220. enumerable: true,
  52221. configurable: true
  52222. });
  52223. Object.defineProperty(Animatable.prototype, "masterFrame", {
  52224. /**
  52225. * Gets the current frame of the first RuntimeAnimation
  52226. * Used to synchronize Animatables
  52227. */
  52228. get: function () {
  52229. if (this._runtimeAnimations.length === 0) {
  52230. return 0;
  52231. }
  52232. return this._runtimeAnimations[0].currentFrame;
  52233. },
  52234. enumerable: true,
  52235. configurable: true
  52236. });
  52237. Object.defineProperty(Animatable.prototype, "weight", {
  52238. /**
  52239. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  52240. */
  52241. get: function () {
  52242. return this._weight;
  52243. },
  52244. set: function (value) {
  52245. if (value === -1) { // -1 is ok and means no weight
  52246. this._weight = -1;
  52247. return;
  52248. }
  52249. // Else weight must be in [0, 1] range
  52250. this._weight = Math.min(Math.max(value, 0), 1.0);
  52251. },
  52252. enumerable: true,
  52253. configurable: true
  52254. });
  52255. Object.defineProperty(Animatable.prototype, "speedRatio", {
  52256. /**
  52257. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  52258. */
  52259. get: function () {
  52260. return this._speedRatio;
  52261. },
  52262. set: function (value) {
  52263. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  52264. var animation = this._runtimeAnimations[index];
  52265. animation._prepareForSpeedRatioChange(value);
  52266. }
  52267. this._speedRatio = value;
  52268. },
  52269. enumerable: true,
  52270. configurable: true
  52271. });
  52272. // Methods
  52273. /**
  52274. * Synchronize and normalize current Animatable with a source Animatable
  52275. * This is useful when using animation weights and when animations are not of the same length
  52276. * @param root defines the root Animatable to synchronize with
  52277. * @returns the current Animatable
  52278. */
  52279. Animatable.prototype.syncWith = function (root) {
  52280. this._syncRoot = root;
  52281. if (root) {
  52282. // Make sure this animatable will animate after the root
  52283. var index = this._scene._activeAnimatables.indexOf(this);
  52284. if (index > -1) {
  52285. this._scene._activeAnimatables.splice(index, 1);
  52286. this._scene._activeAnimatables.push(this);
  52287. }
  52288. }
  52289. return this;
  52290. };
  52291. Animatable.prototype.getAnimations = function () {
  52292. return this._runtimeAnimations;
  52293. };
  52294. Animatable.prototype.appendAnimations = function (target, animations) {
  52295. for (var index = 0; index < animations.length; index++) {
  52296. var animation = animations[index];
  52297. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  52298. }
  52299. };
  52300. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  52301. var runtimeAnimations = this._runtimeAnimations;
  52302. for (var index = 0; index < runtimeAnimations.length; index++) {
  52303. if (runtimeAnimations[index].animation.targetProperty === property) {
  52304. return runtimeAnimations[index].animation;
  52305. }
  52306. }
  52307. return null;
  52308. };
  52309. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  52310. var runtimeAnimations = this._runtimeAnimations;
  52311. for (var index = 0; index < runtimeAnimations.length; index++) {
  52312. if (runtimeAnimations[index].animation.targetProperty === property) {
  52313. return runtimeAnimations[index];
  52314. }
  52315. }
  52316. return null;
  52317. };
  52318. Animatable.prototype.reset = function () {
  52319. var runtimeAnimations = this._runtimeAnimations;
  52320. for (var index = 0; index < runtimeAnimations.length; index++) {
  52321. runtimeAnimations[index].reset(true);
  52322. }
  52323. this._localDelayOffset = null;
  52324. this._pausedDelay = null;
  52325. };
  52326. Animatable.prototype.enableBlending = function (blendingSpeed) {
  52327. var runtimeAnimations = this._runtimeAnimations;
  52328. for (var index = 0; index < runtimeAnimations.length; index++) {
  52329. runtimeAnimations[index].animation.enableBlending = true;
  52330. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  52331. }
  52332. };
  52333. Animatable.prototype.disableBlending = function () {
  52334. var runtimeAnimations = this._runtimeAnimations;
  52335. for (var index = 0; index < runtimeAnimations.length; index++) {
  52336. runtimeAnimations[index].animation.enableBlending = false;
  52337. }
  52338. };
  52339. Animatable.prototype.goToFrame = function (frame) {
  52340. var runtimeAnimations = this._runtimeAnimations;
  52341. if (runtimeAnimations[0]) {
  52342. var fps = runtimeAnimations[0].animation.framePerSecond;
  52343. var currentFrame = runtimeAnimations[0].currentFrame;
  52344. var adjustTime = frame - currentFrame;
  52345. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  52346. if (this._localDelayOffset === null) {
  52347. this._localDelayOffset = 0;
  52348. }
  52349. this._localDelayOffset -= delay;
  52350. }
  52351. for (var index = 0; index < runtimeAnimations.length; index++) {
  52352. runtimeAnimations[index].goToFrame(frame);
  52353. }
  52354. };
  52355. Animatable.prototype.pause = function () {
  52356. if (this._paused) {
  52357. return;
  52358. }
  52359. this._paused = true;
  52360. };
  52361. Animatable.prototype.restart = function () {
  52362. this._paused = false;
  52363. };
  52364. Animatable.prototype.stop = function (animationName) {
  52365. if (animationName) {
  52366. var idx = this._scene._activeAnimatables.indexOf(this);
  52367. if (idx > -1) {
  52368. var runtimeAnimations = this._runtimeAnimations;
  52369. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  52370. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  52371. continue;
  52372. }
  52373. runtimeAnimations[index].dispose();
  52374. runtimeAnimations.splice(index, 1);
  52375. }
  52376. if (runtimeAnimations.length == 0) {
  52377. this._scene._activeAnimatables.splice(idx, 1);
  52378. if (this.onAnimationEnd) {
  52379. this.onAnimationEnd();
  52380. }
  52381. }
  52382. }
  52383. }
  52384. else {
  52385. var index = this._scene._activeAnimatables.indexOf(this);
  52386. if (index > -1) {
  52387. this._scene._activeAnimatables.splice(index, 1);
  52388. var runtimeAnimations = this._runtimeAnimations;
  52389. for (var index = 0; index < runtimeAnimations.length; index++) {
  52390. runtimeAnimations[index].dispose();
  52391. }
  52392. if (this.onAnimationEnd) {
  52393. this.onAnimationEnd();
  52394. }
  52395. }
  52396. }
  52397. };
  52398. Animatable.prototype._animate = function (delay) {
  52399. if (this._paused) {
  52400. this.animationStarted = false;
  52401. if (this._pausedDelay === null) {
  52402. this._pausedDelay = delay;
  52403. }
  52404. return true;
  52405. }
  52406. if (this._localDelayOffset === null) {
  52407. this._localDelayOffset = delay;
  52408. this._pausedDelay = null;
  52409. }
  52410. else if (this._pausedDelay !== null) {
  52411. this._localDelayOffset += delay - this._pausedDelay;
  52412. this._pausedDelay = null;
  52413. }
  52414. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  52415. return true;
  52416. }
  52417. // Animating
  52418. var running = false;
  52419. var runtimeAnimations = this._runtimeAnimations;
  52420. var index;
  52421. for (index = 0; index < runtimeAnimations.length; index++) {
  52422. var animation = runtimeAnimations[index];
  52423. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  52424. running = running || isRunning;
  52425. }
  52426. this.animationStarted = running;
  52427. if (!running) {
  52428. // Remove from active animatables
  52429. index = this._scene._activeAnimatables.indexOf(this);
  52430. this._scene._activeAnimatables.splice(index, 1);
  52431. // Dispose all runtime animations
  52432. for (index = 0; index < runtimeAnimations.length; index++) {
  52433. runtimeAnimations[index].dispose();
  52434. }
  52435. }
  52436. if (!running && this.onAnimationEnd) {
  52437. this.onAnimationEnd();
  52438. this.onAnimationEnd = null;
  52439. }
  52440. return running;
  52441. };
  52442. return Animatable;
  52443. }());
  52444. BABYLON.Animatable = Animatable;
  52445. })(BABYLON || (BABYLON = {}));
  52446. //# sourceMappingURL=babylon.animatable.js.map
  52447. var BABYLON;
  52448. (function (BABYLON) {
  52449. var EasingFunction = /** @class */ (function () {
  52450. function EasingFunction() {
  52451. // Properties
  52452. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  52453. }
  52454. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  52455. get: function () {
  52456. return EasingFunction._EASINGMODE_EASEIN;
  52457. },
  52458. enumerable: true,
  52459. configurable: true
  52460. });
  52461. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  52462. get: function () {
  52463. return EasingFunction._EASINGMODE_EASEOUT;
  52464. },
  52465. enumerable: true,
  52466. configurable: true
  52467. });
  52468. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  52469. get: function () {
  52470. return EasingFunction._EASINGMODE_EASEINOUT;
  52471. },
  52472. enumerable: true,
  52473. configurable: true
  52474. });
  52475. EasingFunction.prototype.setEasingMode = function (easingMode) {
  52476. var n = Math.min(Math.max(easingMode, 0), 2);
  52477. this._easingMode = n;
  52478. };
  52479. EasingFunction.prototype.getEasingMode = function () {
  52480. return this._easingMode;
  52481. };
  52482. EasingFunction.prototype.easeInCore = function (gradient) {
  52483. throw new Error('You must implement this method');
  52484. };
  52485. EasingFunction.prototype.ease = function (gradient) {
  52486. switch (this._easingMode) {
  52487. case EasingFunction.EASINGMODE_EASEIN:
  52488. return this.easeInCore(gradient);
  52489. case EasingFunction.EASINGMODE_EASEOUT:
  52490. return (1 - this.easeInCore(1 - gradient));
  52491. }
  52492. if (gradient >= 0.5) {
  52493. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  52494. }
  52495. return (this.easeInCore(gradient * 2) * 0.5);
  52496. };
  52497. //Statics
  52498. EasingFunction._EASINGMODE_EASEIN = 0;
  52499. EasingFunction._EASINGMODE_EASEOUT = 1;
  52500. EasingFunction._EASINGMODE_EASEINOUT = 2;
  52501. return EasingFunction;
  52502. }());
  52503. BABYLON.EasingFunction = EasingFunction;
  52504. var CircleEase = /** @class */ (function (_super) {
  52505. __extends(CircleEase, _super);
  52506. function CircleEase() {
  52507. return _super !== null && _super.apply(this, arguments) || this;
  52508. }
  52509. CircleEase.prototype.easeInCore = function (gradient) {
  52510. gradient = Math.max(0, Math.min(1, gradient));
  52511. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  52512. };
  52513. return CircleEase;
  52514. }(EasingFunction));
  52515. BABYLON.CircleEase = CircleEase;
  52516. var BackEase = /** @class */ (function (_super) {
  52517. __extends(BackEase, _super);
  52518. function BackEase(amplitude) {
  52519. if (amplitude === void 0) { amplitude = 1; }
  52520. var _this = _super.call(this) || this;
  52521. _this.amplitude = amplitude;
  52522. return _this;
  52523. }
  52524. BackEase.prototype.easeInCore = function (gradient) {
  52525. var num = Math.max(0, this.amplitude);
  52526. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  52527. };
  52528. return BackEase;
  52529. }(EasingFunction));
  52530. BABYLON.BackEase = BackEase;
  52531. var BounceEase = /** @class */ (function (_super) {
  52532. __extends(BounceEase, _super);
  52533. function BounceEase(bounces, bounciness) {
  52534. if (bounces === void 0) { bounces = 3; }
  52535. if (bounciness === void 0) { bounciness = 2; }
  52536. var _this = _super.call(this) || this;
  52537. _this.bounces = bounces;
  52538. _this.bounciness = bounciness;
  52539. return _this;
  52540. }
  52541. BounceEase.prototype.easeInCore = function (gradient) {
  52542. var y = Math.max(0.0, this.bounces);
  52543. var bounciness = this.bounciness;
  52544. if (bounciness <= 1.0) {
  52545. bounciness = 1.001;
  52546. }
  52547. var num9 = Math.pow(bounciness, y);
  52548. var num5 = 1.0 - bounciness;
  52549. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  52550. var num15 = gradient * num4;
  52551. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  52552. var num3 = Math.floor(num65);
  52553. var num13 = num3 + 1.0;
  52554. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  52555. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  52556. var num7 = (num8 + num12) * 0.5;
  52557. var num6 = gradient - num7;
  52558. var num2 = num7 - num8;
  52559. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  52560. };
  52561. return BounceEase;
  52562. }(EasingFunction));
  52563. BABYLON.BounceEase = BounceEase;
  52564. var CubicEase = /** @class */ (function (_super) {
  52565. __extends(CubicEase, _super);
  52566. function CubicEase() {
  52567. return _super !== null && _super.apply(this, arguments) || this;
  52568. }
  52569. CubicEase.prototype.easeInCore = function (gradient) {
  52570. return (gradient * gradient * gradient);
  52571. };
  52572. return CubicEase;
  52573. }(EasingFunction));
  52574. BABYLON.CubicEase = CubicEase;
  52575. var ElasticEase = /** @class */ (function (_super) {
  52576. __extends(ElasticEase, _super);
  52577. function ElasticEase(oscillations, springiness) {
  52578. if (oscillations === void 0) { oscillations = 3; }
  52579. if (springiness === void 0) { springiness = 3; }
  52580. var _this = _super.call(this) || this;
  52581. _this.oscillations = oscillations;
  52582. _this.springiness = springiness;
  52583. return _this;
  52584. }
  52585. ElasticEase.prototype.easeInCore = function (gradient) {
  52586. var num2;
  52587. var num3 = Math.max(0.0, this.oscillations);
  52588. var num = Math.max(0.0, this.springiness);
  52589. if (num == 0) {
  52590. num2 = gradient;
  52591. }
  52592. else {
  52593. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  52594. }
  52595. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  52596. };
  52597. return ElasticEase;
  52598. }(EasingFunction));
  52599. BABYLON.ElasticEase = ElasticEase;
  52600. var ExponentialEase = /** @class */ (function (_super) {
  52601. __extends(ExponentialEase, _super);
  52602. function ExponentialEase(exponent) {
  52603. if (exponent === void 0) { exponent = 2; }
  52604. var _this = _super.call(this) || this;
  52605. _this.exponent = exponent;
  52606. return _this;
  52607. }
  52608. ExponentialEase.prototype.easeInCore = function (gradient) {
  52609. if (this.exponent <= 0) {
  52610. return gradient;
  52611. }
  52612. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  52613. };
  52614. return ExponentialEase;
  52615. }(EasingFunction));
  52616. BABYLON.ExponentialEase = ExponentialEase;
  52617. var PowerEase = /** @class */ (function (_super) {
  52618. __extends(PowerEase, _super);
  52619. function PowerEase(power) {
  52620. if (power === void 0) { power = 2; }
  52621. var _this = _super.call(this) || this;
  52622. _this.power = power;
  52623. return _this;
  52624. }
  52625. PowerEase.prototype.easeInCore = function (gradient) {
  52626. var y = Math.max(0.0, this.power);
  52627. return Math.pow(gradient, y);
  52628. };
  52629. return PowerEase;
  52630. }(EasingFunction));
  52631. BABYLON.PowerEase = PowerEase;
  52632. var QuadraticEase = /** @class */ (function (_super) {
  52633. __extends(QuadraticEase, _super);
  52634. function QuadraticEase() {
  52635. return _super !== null && _super.apply(this, arguments) || this;
  52636. }
  52637. QuadraticEase.prototype.easeInCore = function (gradient) {
  52638. return (gradient * gradient);
  52639. };
  52640. return QuadraticEase;
  52641. }(EasingFunction));
  52642. BABYLON.QuadraticEase = QuadraticEase;
  52643. var QuarticEase = /** @class */ (function (_super) {
  52644. __extends(QuarticEase, _super);
  52645. function QuarticEase() {
  52646. return _super !== null && _super.apply(this, arguments) || this;
  52647. }
  52648. QuarticEase.prototype.easeInCore = function (gradient) {
  52649. return (gradient * gradient * gradient * gradient);
  52650. };
  52651. return QuarticEase;
  52652. }(EasingFunction));
  52653. BABYLON.QuarticEase = QuarticEase;
  52654. var QuinticEase = /** @class */ (function (_super) {
  52655. __extends(QuinticEase, _super);
  52656. function QuinticEase() {
  52657. return _super !== null && _super.apply(this, arguments) || this;
  52658. }
  52659. QuinticEase.prototype.easeInCore = function (gradient) {
  52660. return (gradient * gradient * gradient * gradient * gradient);
  52661. };
  52662. return QuinticEase;
  52663. }(EasingFunction));
  52664. BABYLON.QuinticEase = QuinticEase;
  52665. var SineEase = /** @class */ (function (_super) {
  52666. __extends(SineEase, _super);
  52667. function SineEase() {
  52668. return _super !== null && _super.apply(this, arguments) || this;
  52669. }
  52670. SineEase.prototype.easeInCore = function (gradient) {
  52671. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  52672. };
  52673. return SineEase;
  52674. }(EasingFunction));
  52675. BABYLON.SineEase = SineEase;
  52676. var BezierCurveEase = /** @class */ (function (_super) {
  52677. __extends(BezierCurveEase, _super);
  52678. function BezierCurveEase(x1, y1, x2, y2) {
  52679. if (x1 === void 0) { x1 = 0; }
  52680. if (y1 === void 0) { y1 = 0; }
  52681. if (x2 === void 0) { x2 = 1; }
  52682. if (y2 === void 0) { y2 = 1; }
  52683. var _this = _super.call(this) || this;
  52684. _this.x1 = x1;
  52685. _this.y1 = y1;
  52686. _this.x2 = x2;
  52687. _this.y2 = y2;
  52688. return _this;
  52689. }
  52690. BezierCurveEase.prototype.easeInCore = function (gradient) {
  52691. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  52692. };
  52693. return BezierCurveEase;
  52694. }(EasingFunction));
  52695. BABYLON.BezierCurveEase = BezierCurveEase;
  52696. })(BABYLON || (BABYLON = {}));
  52697. //# sourceMappingURL=babylon.easing.js.map
  52698. var BABYLON;
  52699. (function (BABYLON) {
  52700. /**
  52701. * A Condition applied to an Action
  52702. */
  52703. var Condition = /** @class */ (function () {
  52704. /**
  52705. * Creates a new Condition
  52706. * @param actionManager the manager of the action the condition is applied to
  52707. */
  52708. function Condition(actionManager) {
  52709. this._actionManager = actionManager;
  52710. }
  52711. /**
  52712. * Check if the current condition is valid
  52713. * @returns a boolean
  52714. */
  52715. Condition.prototype.isValid = function () {
  52716. return true;
  52717. };
  52718. /**
  52719. * Internal only
  52720. * @hidden
  52721. */
  52722. Condition.prototype._getProperty = function (propertyPath) {
  52723. return this._actionManager._getProperty(propertyPath);
  52724. };
  52725. /**
  52726. * Internal only
  52727. * @hidden
  52728. */
  52729. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  52730. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52731. };
  52732. /**
  52733. * Serialize placeholder for child classes
  52734. * @returns the serialized object
  52735. */
  52736. Condition.prototype.serialize = function () {
  52737. };
  52738. /**
  52739. * Internal only
  52740. * @hidden
  52741. */
  52742. Condition.prototype._serialize = function (serializedCondition) {
  52743. return {
  52744. type: 2,
  52745. children: [],
  52746. name: serializedCondition.name,
  52747. properties: serializedCondition.properties
  52748. };
  52749. };
  52750. return Condition;
  52751. }());
  52752. BABYLON.Condition = Condition;
  52753. /**
  52754. * Defines specific conditional operators as extensions of Condition
  52755. */
  52756. var ValueCondition = /** @class */ (function (_super) {
  52757. __extends(ValueCondition, _super);
  52758. /**
  52759. * Creates a new ValueCondition
  52760. * @param actionManager manager for the action the condition applies to
  52761. * @param target for the action
  52762. * @param propertyPath path to specify the property of the target the conditional operator uses
  52763. * @param value the value compared by the conditional operator against the current value of the property
  52764. * @param operator the conditional operator, default ValueCondition.IsEqual
  52765. */
  52766. function ValueCondition(actionManager, target,
  52767. /** path to specify the property of the target the conditional operator uses */
  52768. propertyPath,
  52769. /** the value compared by the conditional operator against the current value of the property */
  52770. value,
  52771. /** the conditional operator, default ValueCondition.IsEqual */
  52772. operator) {
  52773. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52774. var _this = _super.call(this, actionManager) || this;
  52775. _this.propertyPath = propertyPath;
  52776. _this.value = value;
  52777. _this.operator = operator;
  52778. _this._target = target;
  52779. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52780. _this._property = _this._getProperty(_this.propertyPath);
  52781. return _this;
  52782. }
  52783. Object.defineProperty(ValueCondition, "IsEqual", {
  52784. /**
  52785. * returns the number for IsEqual
  52786. */
  52787. get: function () {
  52788. return ValueCondition._IsEqual;
  52789. },
  52790. enumerable: true,
  52791. configurable: true
  52792. });
  52793. Object.defineProperty(ValueCondition, "IsDifferent", {
  52794. /**
  52795. * Returns the number for IsDifferent
  52796. */
  52797. get: function () {
  52798. return ValueCondition._IsDifferent;
  52799. },
  52800. enumerable: true,
  52801. configurable: true
  52802. });
  52803. Object.defineProperty(ValueCondition, "IsGreater", {
  52804. /**
  52805. * Returns the number for IsGreater
  52806. */
  52807. get: function () {
  52808. return ValueCondition._IsGreater;
  52809. },
  52810. enumerable: true,
  52811. configurable: true
  52812. });
  52813. Object.defineProperty(ValueCondition, "IsLesser", {
  52814. /**
  52815. * Returns the number for IsLesser
  52816. */
  52817. get: function () {
  52818. return ValueCondition._IsLesser;
  52819. },
  52820. enumerable: true,
  52821. configurable: true
  52822. });
  52823. /**
  52824. * Compares the given value with the property value for the specified conditional operator
  52825. * @returns the result of the comparison
  52826. */
  52827. ValueCondition.prototype.isValid = function () {
  52828. switch (this.operator) {
  52829. case ValueCondition.IsGreater:
  52830. return this._effectiveTarget[this._property] > this.value;
  52831. case ValueCondition.IsLesser:
  52832. return this._effectiveTarget[this._property] < this.value;
  52833. case ValueCondition.IsEqual:
  52834. case ValueCondition.IsDifferent:
  52835. var check;
  52836. if (this.value.equals) {
  52837. check = this.value.equals(this._effectiveTarget[this._property]);
  52838. }
  52839. else {
  52840. check = this.value === this._effectiveTarget[this._property];
  52841. }
  52842. return this.operator === ValueCondition.IsEqual ? check : !check;
  52843. }
  52844. return false;
  52845. };
  52846. /**
  52847. * Serialize the ValueCondition into a JSON compatible object
  52848. * @returns serialization object
  52849. */
  52850. ValueCondition.prototype.serialize = function () {
  52851. return this._serialize({
  52852. name: "ValueCondition",
  52853. properties: [
  52854. BABYLON.Action._GetTargetProperty(this._target),
  52855. { name: "propertyPath", value: this.propertyPath },
  52856. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52857. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52858. ]
  52859. });
  52860. };
  52861. /**
  52862. * Gets the name of the conditional operator for the ValueCondition
  52863. * @param operator the conditional operator
  52864. * @returns the name
  52865. */
  52866. ValueCondition.GetOperatorName = function (operator) {
  52867. switch (operator) {
  52868. case ValueCondition._IsEqual: return "IsEqual";
  52869. case ValueCondition._IsDifferent: return "IsDifferent";
  52870. case ValueCondition._IsGreater: return "IsGreater";
  52871. case ValueCondition._IsLesser: return "IsLesser";
  52872. default: return "";
  52873. }
  52874. };
  52875. /**
  52876. * Internal only
  52877. * @hidden
  52878. */
  52879. ValueCondition._IsEqual = 0;
  52880. /**
  52881. * Internal only
  52882. * @hidden
  52883. */
  52884. ValueCondition._IsDifferent = 1;
  52885. /**
  52886. * Internal only
  52887. * @hidden
  52888. */
  52889. ValueCondition._IsGreater = 2;
  52890. /**
  52891. * Internal only
  52892. * @hidden
  52893. */
  52894. ValueCondition._IsLesser = 3;
  52895. return ValueCondition;
  52896. }(Condition));
  52897. BABYLON.ValueCondition = ValueCondition;
  52898. /**
  52899. * Defines a predicate condition as an extension of Condition
  52900. */
  52901. var PredicateCondition = /** @class */ (function (_super) {
  52902. __extends(PredicateCondition, _super);
  52903. /**
  52904. * Creates a new PredicateCondition
  52905. * @param actionManager manager for the action the condition applies to
  52906. * @param predicate defines the predicate function used to validate the condition
  52907. */
  52908. function PredicateCondition(actionManager,
  52909. /** defines the predicate function used to validate the condition */
  52910. predicate) {
  52911. var _this = _super.call(this, actionManager) || this;
  52912. _this.predicate = predicate;
  52913. return _this;
  52914. }
  52915. /**
  52916. * @returns the validity of the predicate condition
  52917. */
  52918. PredicateCondition.prototype.isValid = function () {
  52919. return this.predicate();
  52920. };
  52921. return PredicateCondition;
  52922. }(Condition));
  52923. BABYLON.PredicateCondition = PredicateCondition;
  52924. /**
  52925. * Defines a state condition as an extension of Condition
  52926. */
  52927. var StateCondition = /** @class */ (function (_super) {
  52928. __extends(StateCondition, _super);
  52929. /**
  52930. * Creates a new StateCondition
  52931. * @param actionManager manager for the action the condition applies to
  52932. * @param target of the condition
  52933. * @param value to compare with target state
  52934. */
  52935. function StateCondition(actionManager, target, value) {
  52936. var _this = _super.call(this, actionManager) || this;
  52937. _this.value = value;
  52938. _this._target = target;
  52939. return _this;
  52940. }
  52941. /**
  52942. * @returns the validity of the state
  52943. */
  52944. StateCondition.prototype.isValid = function () {
  52945. return this._target.state === this.value;
  52946. };
  52947. /**
  52948. * Serialize the StateCondition into a JSON compatible object
  52949. * @returns serialization object
  52950. */
  52951. StateCondition.prototype.serialize = function () {
  52952. return this._serialize({
  52953. name: "StateCondition",
  52954. properties: [
  52955. BABYLON.Action._GetTargetProperty(this._target),
  52956. { name: "value", value: this.value }
  52957. ]
  52958. });
  52959. };
  52960. return StateCondition;
  52961. }(Condition));
  52962. BABYLON.StateCondition = StateCondition;
  52963. })(BABYLON || (BABYLON = {}));
  52964. //# sourceMappingURL=babylon.condition.js.map
  52965. var BABYLON;
  52966. (function (BABYLON) {
  52967. /**
  52968. * The action to be carried out following a trigger
  52969. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52970. */
  52971. var Action = /** @class */ (function () {
  52972. /**
  52973. * Creates a new Action
  52974. * @param triggerOptions the trigger, with or without parameters, for the action
  52975. * @param condition an optional determinant of action
  52976. */
  52977. function Action(
  52978. /** the trigger, with or without parameters, for the action */
  52979. triggerOptions, condition) {
  52980. this.triggerOptions = triggerOptions;
  52981. /**
  52982. * An event triggered prior to action being executed.
  52983. */
  52984. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52985. if (triggerOptions.parameter) {
  52986. this.trigger = triggerOptions.trigger;
  52987. this._triggerParameter = triggerOptions.parameter;
  52988. }
  52989. else {
  52990. this.trigger = triggerOptions;
  52991. }
  52992. this._nextActiveAction = this;
  52993. this._condition = condition;
  52994. }
  52995. /**
  52996. * Internal only
  52997. * @hidden
  52998. */
  52999. Action.prototype._prepare = function () {
  53000. };
  53001. /**
  53002. * Gets the trigger parameters
  53003. * @returns the trigger parameters
  53004. */
  53005. Action.prototype.getTriggerParameter = function () {
  53006. return this._triggerParameter;
  53007. };
  53008. /**
  53009. * Internal only - executes current action event
  53010. * @hidden
  53011. */
  53012. Action.prototype._executeCurrent = function (evt) {
  53013. if (this._nextActiveAction._condition) {
  53014. var condition = this._nextActiveAction._condition;
  53015. var currentRenderId = this._actionManager.getScene().getRenderId();
  53016. // We cache the current evaluation for the current frame
  53017. if (condition._evaluationId === currentRenderId) {
  53018. if (!condition._currentResult) {
  53019. return;
  53020. }
  53021. }
  53022. else {
  53023. condition._evaluationId = currentRenderId;
  53024. if (!condition.isValid()) {
  53025. condition._currentResult = false;
  53026. return;
  53027. }
  53028. condition._currentResult = true;
  53029. }
  53030. }
  53031. this.onBeforeExecuteObservable.notifyObservers(this);
  53032. this._nextActiveAction.execute(evt);
  53033. this.skipToNextActiveAction();
  53034. };
  53035. /**
  53036. * Execute placeholder for child classes
  53037. * @param evt optional action event
  53038. */
  53039. Action.prototype.execute = function (evt) {
  53040. };
  53041. /**
  53042. * Skips to next active action
  53043. */
  53044. Action.prototype.skipToNextActiveAction = function () {
  53045. if (this._nextActiveAction._child) {
  53046. if (!this._nextActiveAction._child._actionManager) {
  53047. this._nextActiveAction._child._actionManager = this._actionManager;
  53048. }
  53049. this._nextActiveAction = this._nextActiveAction._child;
  53050. }
  53051. else {
  53052. this._nextActiveAction = this;
  53053. }
  53054. };
  53055. /**
  53056. * Adds action to chain of actions, may be a DoNothingAction
  53057. * @param action defines the next action to execute
  53058. * @returns The action passed in
  53059. * @see https://www.babylonjs-playground.com/#1T30HR#0
  53060. */
  53061. Action.prototype.then = function (action) {
  53062. this._child = action;
  53063. action._actionManager = this._actionManager;
  53064. action._prepare();
  53065. return action;
  53066. };
  53067. /**
  53068. * Internal only
  53069. * @hidden
  53070. */
  53071. Action.prototype._getProperty = function (propertyPath) {
  53072. return this._actionManager._getProperty(propertyPath);
  53073. };
  53074. /**
  53075. * Internal only
  53076. * @hidden
  53077. */
  53078. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  53079. return this._actionManager._getEffectiveTarget(target, propertyPath);
  53080. };
  53081. /**
  53082. * Serialize placeholder for child classes
  53083. * @param parent of child
  53084. * @returns the serialized object
  53085. */
  53086. Action.prototype.serialize = function (parent) {
  53087. };
  53088. /**
  53089. * Internal only called by serialize
  53090. * @hidden
  53091. */
  53092. Action.prototype._serialize = function (serializedAction, parent) {
  53093. var serializationObject = {
  53094. type: 1,
  53095. children: [],
  53096. name: serializedAction.name,
  53097. properties: serializedAction.properties || []
  53098. };
  53099. // Serialize child
  53100. if (this._child) {
  53101. this._child.serialize(serializationObject);
  53102. }
  53103. // Check if "this" has a condition
  53104. if (this._condition) {
  53105. var serializedCondition = this._condition.serialize();
  53106. serializedCondition.children.push(serializationObject);
  53107. if (parent) {
  53108. parent.children.push(serializedCondition);
  53109. }
  53110. return serializedCondition;
  53111. }
  53112. if (parent) {
  53113. parent.children.push(serializationObject);
  53114. }
  53115. return serializationObject;
  53116. };
  53117. /**
  53118. * Internal only
  53119. * @hidden
  53120. */
  53121. Action._SerializeValueAsString = function (value) {
  53122. if (typeof value === "number") {
  53123. return value.toString();
  53124. }
  53125. if (typeof value === "boolean") {
  53126. return value ? "true" : "false";
  53127. }
  53128. if (value instanceof BABYLON.Vector2) {
  53129. return value.x + ", " + value.y;
  53130. }
  53131. if (value instanceof BABYLON.Vector3) {
  53132. return value.x + ", " + value.y + ", " + value.z;
  53133. }
  53134. if (value instanceof BABYLON.Color3) {
  53135. return value.r + ", " + value.g + ", " + value.b;
  53136. }
  53137. if (value instanceof BABYLON.Color4) {
  53138. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  53139. }
  53140. return value; // string
  53141. };
  53142. /**
  53143. * Internal only
  53144. * @hidden
  53145. */
  53146. Action._GetTargetProperty = function (target) {
  53147. return {
  53148. name: "target",
  53149. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  53150. : target instanceof BABYLON.Light ? "LightProperties"
  53151. : target instanceof BABYLON.Camera ? "CameraProperties"
  53152. : "SceneProperties",
  53153. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  53154. };
  53155. };
  53156. return Action;
  53157. }());
  53158. BABYLON.Action = Action;
  53159. })(BABYLON || (BABYLON = {}));
  53160. //# sourceMappingURL=babylon.action.js.map
  53161. var BABYLON;
  53162. (function (BABYLON) {
  53163. /**
  53164. * ActionEvent is the event being sent when an action is triggered.
  53165. */
  53166. var ActionEvent = /** @class */ (function () {
  53167. /**
  53168. * Creates a new ActionEvent
  53169. * @param source The mesh or sprite that triggered the action
  53170. * @param pointerX The X mouse cursor position at the time of the event
  53171. * @param pointerY The Y mouse cursor position at the time of the event
  53172. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  53173. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  53174. * @param additionalData additional data for the event
  53175. */
  53176. function ActionEvent(
  53177. /** The mesh or sprite that triggered the action */
  53178. source,
  53179. /** The X mouse cursor position at the time of the event */
  53180. pointerX,
  53181. /** The Y mouse cursor position at the time of the event */
  53182. pointerY,
  53183. /** The mesh that is currently pointed at (can be null) */
  53184. meshUnderPointer,
  53185. /** the original (browser) event that triggered the ActionEvent */
  53186. sourceEvent,
  53187. /** additional data for the event */
  53188. additionalData) {
  53189. this.source = source;
  53190. this.pointerX = pointerX;
  53191. this.pointerY = pointerY;
  53192. this.meshUnderPointer = meshUnderPointer;
  53193. this.sourceEvent = sourceEvent;
  53194. this.additionalData = additionalData;
  53195. }
  53196. /**
  53197. * Helper function to auto-create an ActionEvent from a source mesh.
  53198. * @param source The source mesh that triggered the event
  53199. * @param evt The original (browser) event
  53200. * @param additionalData additional data for the event
  53201. * @returns the new ActionEvent
  53202. */
  53203. ActionEvent.CreateNew = function (source, evt, additionalData) {
  53204. var scene = source.getScene();
  53205. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53206. };
  53207. /**
  53208. * Helper function to auto-create an ActionEvent from a source sprite
  53209. * @param source The source sprite that triggered the event
  53210. * @param scene Scene associated with the sprite
  53211. * @param evt The original (browser) event
  53212. * @param additionalData additional data for the event
  53213. * @returns the new ActionEvent
  53214. */
  53215. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  53216. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  53217. };
  53218. /**
  53219. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  53220. * @param scene the scene where the event occurred
  53221. * @param evt The original (browser) event
  53222. * @returns the new ActionEvent
  53223. */
  53224. ActionEvent.CreateNewFromScene = function (scene, evt) {
  53225. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  53226. };
  53227. /**
  53228. * Helper function to auto-create an ActionEvent from a primitive
  53229. * @param prim defines the target primitive
  53230. * @param pointerPos defines the pointer position
  53231. * @param evt The original (browser) event
  53232. * @param additionalData additional data for the event
  53233. * @returns the new ActionEvent
  53234. */
  53235. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  53236. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  53237. };
  53238. return ActionEvent;
  53239. }());
  53240. BABYLON.ActionEvent = ActionEvent;
  53241. /**
  53242. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  53243. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  53244. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  53245. */
  53246. var ActionManager = /** @class */ (function () {
  53247. /**
  53248. * Creates a new action manager
  53249. * @param scene defines the hosting scene
  53250. */
  53251. function ActionManager(scene) {
  53252. // Members
  53253. /** Gets the list of actions */
  53254. this.actions = new Array();
  53255. /** Gets the cursor to use when hovering items */
  53256. this.hoverCursor = '';
  53257. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  53258. scene._actionManagers.push(this);
  53259. }
  53260. Object.defineProperty(ActionManager, "NothingTrigger", {
  53261. /**
  53262. * Nothing
  53263. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53264. */
  53265. get: function () {
  53266. return ActionManager._NothingTrigger;
  53267. },
  53268. enumerable: true,
  53269. configurable: true
  53270. });
  53271. Object.defineProperty(ActionManager, "OnPickTrigger", {
  53272. /**
  53273. * On pick
  53274. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53275. */
  53276. get: function () {
  53277. return ActionManager._OnPickTrigger;
  53278. },
  53279. enumerable: true,
  53280. configurable: true
  53281. });
  53282. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  53283. /**
  53284. * On left pick
  53285. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53286. */
  53287. get: function () {
  53288. return ActionManager._OnLeftPickTrigger;
  53289. },
  53290. enumerable: true,
  53291. configurable: true
  53292. });
  53293. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  53294. /**
  53295. * On right pick
  53296. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53297. */
  53298. get: function () {
  53299. return ActionManager._OnRightPickTrigger;
  53300. },
  53301. enumerable: true,
  53302. configurable: true
  53303. });
  53304. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  53305. /**
  53306. * On center pick
  53307. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53308. */
  53309. get: function () {
  53310. return ActionManager._OnCenterPickTrigger;
  53311. },
  53312. enumerable: true,
  53313. configurable: true
  53314. });
  53315. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  53316. /**
  53317. * On pick down
  53318. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53319. */
  53320. get: function () {
  53321. return ActionManager._OnPickDownTrigger;
  53322. },
  53323. enumerable: true,
  53324. configurable: true
  53325. });
  53326. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  53327. /**
  53328. * On double pick
  53329. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53330. */
  53331. get: function () {
  53332. return ActionManager._OnDoublePickTrigger;
  53333. },
  53334. enumerable: true,
  53335. configurable: true
  53336. });
  53337. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  53338. /**
  53339. * On pick up
  53340. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53341. */
  53342. get: function () {
  53343. return ActionManager._OnPickUpTrigger;
  53344. },
  53345. enumerable: true,
  53346. configurable: true
  53347. });
  53348. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  53349. /**
  53350. * On pick out.
  53351. * This trigger will only be raised if you also declared a OnPickDown
  53352. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53353. */
  53354. get: function () {
  53355. return ActionManager._OnPickOutTrigger;
  53356. },
  53357. enumerable: true,
  53358. configurable: true
  53359. });
  53360. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  53361. /**
  53362. * On long press
  53363. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53364. */
  53365. get: function () {
  53366. return ActionManager._OnLongPressTrigger;
  53367. },
  53368. enumerable: true,
  53369. configurable: true
  53370. });
  53371. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  53372. /**
  53373. * On pointer over
  53374. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53375. */
  53376. get: function () {
  53377. return ActionManager._OnPointerOverTrigger;
  53378. },
  53379. enumerable: true,
  53380. configurable: true
  53381. });
  53382. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  53383. /**
  53384. * On pointer out
  53385. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53386. */
  53387. get: function () {
  53388. return ActionManager._OnPointerOutTrigger;
  53389. },
  53390. enumerable: true,
  53391. configurable: true
  53392. });
  53393. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  53394. /**
  53395. * On every frame
  53396. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53397. */
  53398. get: function () {
  53399. return ActionManager._OnEveryFrameTrigger;
  53400. },
  53401. enumerable: true,
  53402. configurable: true
  53403. });
  53404. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  53405. /**
  53406. * On intersection enter
  53407. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53408. */
  53409. get: function () {
  53410. return ActionManager._OnIntersectionEnterTrigger;
  53411. },
  53412. enumerable: true,
  53413. configurable: true
  53414. });
  53415. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  53416. /**
  53417. * On intersection exit
  53418. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53419. */
  53420. get: function () {
  53421. return ActionManager._OnIntersectionExitTrigger;
  53422. },
  53423. enumerable: true,
  53424. configurable: true
  53425. });
  53426. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  53427. /**
  53428. * On key down
  53429. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53430. */
  53431. get: function () {
  53432. return ActionManager._OnKeyDownTrigger;
  53433. },
  53434. enumerable: true,
  53435. configurable: true
  53436. });
  53437. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  53438. /**
  53439. * On key up
  53440. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  53441. */
  53442. get: function () {
  53443. return ActionManager._OnKeyUpTrigger;
  53444. },
  53445. enumerable: true,
  53446. configurable: true
  53447. });
  53448. // Methods
  53449. /**
  53450. * Releases all associated resources
  53451. */
  53452. ActionManager.prototype.dispose = function () {
  53453. var index = this._scene._actionManagers.indexOf(this);
  53454. for (var i = 0; i < this.actions.length; i++) {
  53455. var action = this.actions[i];
  53456. ActionManager.Triggers[action.trigger]--;
  53457. if (ActionManager.Triggers[action.trigger] === 0) {
  53458. delete ActionManager.Triggers[action.trigger];
  53459. }
  53460. }
  53461. if (index > -1) {
  53462. this._scene._actionManagers.splice(index, 1);
  53463. }
  53464. };
  53465. /**
  53466. * Gets hosting scene
  53467. * @returns the hosting scene
  53468. */
  53469. ActionManager.prototype.getScene = function () {
  53470. return this._scene;
  53471. };
  53472. /**
  53473. * Does this action manager handles actions of any of the given triggers
  53474. * @param triggers defines the triggers to be tested
  53475. * @return a boolean indicating whether one (or more) of the triggers is handled
  53476. */
  53477. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  53478. for (var index = 0; index < this.actions.length; index++) {
  53479. var action = this.actions[index];
  53480. if (triggers.indexOf(action.trigger) > -1) {
  53481. return true;
  53482. }
  53483. }
  53484. return false;
  53485. };
  53486. /**
  53487. * Does this action manager handles actions of a given trigger
  53488. * @param trigger defines the trigger to be tested
  53489. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  53490. * @return whether the trigger is handled
  53491. */
  53492. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  53493. for (var index = 0; index < this.actions.length; index++) {
  53494. var action = this.actions[index];
  53495. if (action.trigger === trigger) {
  53496. if (parameterPredicate) {
  53497. if (parameterPredicate(action.getTriggerParameter())) {
  53498. return true;
  53499. }
  53500. }
  53501. else {
  53502. return true;
  53503. }
  53504. }
  53505. }
  53506. return false;
  53507. };
  53508. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  53509. /**
  53510. * Does this action manager has pointer triggers
  53511. */
  53512. get: function () {
  53513. for (var index = 0; index < this.actions.length; index++) {
  53514. var action = this.actions[index];
  53515. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  53516. return true;
  53517. }
  53518. }
  53519. return false;
  53520. },
  53521. enumerable: true,
  53522. configurable: true
  53523. });
  53524. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  53525. /**
  53526. * Does this action manager has pick triggers
  53527. */
  53528. get: function () {
  53529. for (var index = 0; index < this.actions.length; index++) {
  53530. var action = this.actions[index];
  53531. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  53532. return true;
  53533. }
  53534. }
  53535. return false;
  53536. },
  53537. enumerable: true,
  53538. configurable: true
  53539. });
  53540. Object.defineProperty(ActionManager, "HasTriggers", {
  53541. /**
  53542. * Does exist one action manager with at least one trigger
  53543. **/
  53544. get: function () {
  53545. for (var t in ActionManager.Triggers) {
  53546. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53547. return true;
  53548. }
  53549. }
  53550. return false;
  53551. },
  53552. enumerable: true,
  53553. configurable: true
  53554. });
  53555. Object.defineProperty(ActionManager, "HasPickTriggers", {
  53556. /**
  53557. * Does exist one action manager with at least one pick trigger
  53558. **/
  53559. get: function () {
  53560. for (var t in ActionManager.Triggers) {
  53561. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53562. var t_int = parseInt(t);
  53563. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  53564. return true;
  53565. }
  53566. }
  53567. }
  53568. return false;
  53569. },
  53570. enumerable: true,
  53571. configurable: true
  53572. });
  53573. /**
  53574. * Does exist one action manager that handles actions of a given trigger
  53575. * @param trigger defines the trigger to be tested
  53576. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  53577. **/
  53578. ActionManager.HasSpecificTrigger = function (trigger) {
  53579. for (var t in ActionManager.Triggers) {
  53580. if (ActionManager.Triggers.hasOwnProperty(t)) {
  53581. var t_int = parseInt(t);
  53582. if (t_int === trigger) {
  53583. return true;
  53584. }
  53585. }
  53586. }
  53587. return false;
  53588. };
  53589. /**
  53590. * Registers an action to this action manager
  53591. * @param action defines the action to be registered
  53592. * @return the action amended (prepared) after registration
  53593. */
  53594. ActionManager.prototype.registerAction = function (action) {
  53595. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  53596. if (this.getScene().actionManager !== this) {
  53597. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  53598. return null;
  53599. }
  53600. }
  53601. this.actions.push(action);
  53602. if (ActionManager.Triggers[action.trigger]) {
  53603. ActionManager.Triggers[action.trigger]++;
  53604. }
  53605. else {
  53606. ActionManager.Triggers[action.trigger] = 1;
  53607. }
  53608. action._actionManager = this;
  53609. action._prepare();
  53610. return action;
  53611. };
  53612. /**
  53613. * Unregisters an action to this action manager
  53614. * @param action defines the action to be unregistered
  53615. * @return a boolean indicating whether the action has been unregistered
  53616. */
  53617. ActionManager.prototype.unregisterAction = function (action) {
  53618. var index = this.actions.indexOf(action);
  53619. if (index !== -1) {
  53620. this.actions.splice(index, 1);
  53621. ActionManager.Triggers[action.trigger] -= 1;
  53622. if (ActionManager.Triggers[action.trigger] === 0) {
  53623. delete ActionManager.Triggers[action.trigger];
  53624. }
  53625. delete action._actionManager;
  53626. return true;
  53627. }
  53628. return false;
  53629. };
  53630. /**
  53631. * Process a specific trigger
  53632. * @param trigger defines the trigger to process
  53633. * @param evt defines the event details to be processed
  53634. */
  53635. ActionManager.prototype.processTrigger = function (trigger, evt) {
  53636. for (var index = 0; index < this.actions.length; index++) {
  53637. var action = this.actions[index];
  53638. if (action.trigger === trigger) {
  53639. if (evt) {
  53640. if (trigger === ActionManager.OnKeyUpTrigger
  53641. || trigger === ActionManager.OnKeyDownTrigger) {
  53642. var parameter = action.getTriggerParameter();
  53643. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  53644. if (!parameter.toLowerCase) {
  53645. continue;
  53646. }
  53647. var lowerCase = parameter.toLowerCase();
  53648. if (lowerCase !== evt.sourceEvent.key) {
  53649. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  53650. var actualkey = String.fromCharCode(unicode).toLowerCase();
  53651. if (actualkey !== lowerCase) {
  53652. continue;
  53653. }
  53654. }
  53655. }
  53656. }
  53657. }
  53658. action._executeCurrent(evt);
  53659. }
  53660. }
  53661. };
  53662. /** @hidden */
  53663. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  53664. var properties = propertyPath.split(".");
  53665. for (var index = 0; index < properties.length - 1; index++) {
  53666. target = target[properties[index]];
  53667. }
  53668. return target;
  53669. };
  53670. /** @hidden */
  53671. ActionManager.prototype._getProperty = function (propertyPath) {
  53672. var properties = propertyPath.split(".");
  53673. return properties[properties.length - 1];
  53674. };
  53675. /**
  53676. * Serialize this manager to a JSON object
  53677. * @param name defines the property name to store this manager
  53678. * @returns a JSON representation of this manager
  53679. */
  53680. ActionManager.prototype.serialize = function (name) {
  53681. var root = {
  53682. children: new Array(),
  53683. name: name,
  53684. type: 3,
  53685. properties: new Array() // Empty for root but required
  53686. };
  53687. for (var i = 0; i < this.actions.length; i++) {
  53688. var triggerObject = {
  53689. type: 0,
  53690. children: new Array(),
  53691. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  53692. properties: new Array()
  53693. };
  53694. var triggerOptions = this.actions[i].triggerOptions;
  53695. if (triggerOptions && typeof triggerOptions !== "number") {
  53696. if (triggerOptions.parameter instanceof BABYLON.Node) {
  53697. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  53698. }
  53699. else {
  53700. var parameter = {};
  53701. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  53702. if (triggerOptions.parameter.mesh) {
  53703. parameter._meshId = triggerOptions.parameter.mesh.id;
  53704. }
  53705. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  53706. }
  53707. }
  53708. // Serialize child action, recursively
  53709. this.actions[i].serialize(triggerObject);
  53710. // Add serialized trigger
  53711. root.children.push(triggerObject);
  53712. }
  53713. return root;
  53714. };
  53715. /**
  53716. * Creates a new ActionManager from a JSON data
  53717. * @param parsedActions defines the JSON data to read from
  53718. * @param object defines the hosting mesh
  53719. * @param scene defines the hosting scene
  53720. */
  53721. ActionManager.Parse = function (parsedActions, object, scene) {
  53722. var actionManager = new ActionManager(scene);
  53723. if (object === null)
  53724. scene.actionManager = actionManager;
  53725. else
  53726. object.actionManager = actionManager;
  53727. // instanciate a new object
  53728. var instanciate = function (name, params) {
  53729. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  53730. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  53731. newInstance.constructor.apply(newInstance, params);
  53732. return newInstance;
  53733. };
  53734. var parseParameter = function (name, value, target, propertyPath) {
  53735. if (propertyPath === null) {
  53736. // String, boolean or float
  53737. var floatValue = parseFloat(value);
  53738. if (value === "true" || value === "false")
  53739. return value === "true";
  53740. else
  53741. return isNaN(floatValue) ? value : floatValue;
  53742. }
  53743. var effectiveTarget = propertyPath.split(".");
  53744. var values = value.split(",");
  53745. // Get effective Target
  53746. for (var i = 0; i < effectiveTarget.length; i++) {
  53747. target = target[effectiveTarget[i]];
  53748. }
  53749. // Return appropriate value with its type
  53750. if (typeof (target) === "boolean")
  53751. return values[0] === "true";
  53752. if (typeof (target) === "string")
  53753. return values[0];
  53754. // Parameters with multiple values such as Vector3 etc.
  53755. var split = new Array();
  53756. for (var i = 0; i < values.length; i++)
  53757. split.push(parseFloat(values[i]));
  53758. if (target instanceof BABYLON.Vector3)
  53759. return BABYLON.Vector3.FromArray(split);
  53760. if (target instanceof BABYLON.Vector4)
  53761. return BABYLON.Vector4.FromArray(split);
  53762. if (target instanceof BABYLON.Color3)
  53763. return BABYLON.Color3.FromArray(split);
  53764. if (target instanceof BABYLON.Color4)
  53765. return BABYLON.Color4.FromArray(split);
  53766. return parseFloat(values[0]);
  53767. };
  53768. // traverse graph per trigger
  53769. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53770. if (combineArray === void 0) { combineArray = null; }
  53771. if (parsedAction.detached)
  53772. return;
  53773. var parameters = new Array();
  53774. var target = null;
  53775. var propertyPath = null;
  53776. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53777. // Parameters
  53778. if (parsedAction.type === 2)
  53779. parameters.push(actionManager);
  53780. else
  53781. parameters.push(trigger);
  53782. if (combine) {
  53783. var actions = new Array();
  53784. for (var j = 0; j < parsedAction.combine.length; j++) {
  53785. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53786. }
  53787. parameters.push(actions);
  53788. }
  53789. else {
  53790. for (var i = 0; i < parsedAction.properties.length; i++) {
  53791. var value = parsedAction.properties[i].value;
  53792. var name = parsedAction.properties[i].name;
  53793. var targetType = parsedAction.properties[i].targetType;
  53794. if (name === "target")
  53795. if (targetType !== null && targetType === "SceneProperties")
  53796. value = target = scene;
  53797. else
  53798. value = target = scene.getNodeByName(value);
  53799. else if (name === "parent")
  53800. value = scene.getNodeByName(value);
  53801. else if (name === "sound")
  53802. value = scene.getSoundByName(value);
  53803. else if (name !== "propertyPath") {
  53804. if (parsedAction.type === 2 && name === "operator")
  53805. value = BABYLON.ValueCondition[value];
  53806. else
  53807. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53808. }
  53809. else {
  53810. propertyPath = value;
  53811. }
  53812. parameters.push(value);
  53813. }
  53814. }
  53815. if (combineArray === null) {
  53816. parameters.push(condition);
  53817. }
  53818. else {
  53819. parameters.push(null);
  53820. }
  53821. // If interpolate value action
  53822. if (parsedAction.name === "InterpolateValueAction") {
  53823. var param = parameters[parameters.length - 2];
  53824. parameters[parameters.length - 1] = param;
  53825. parameters[parameters.length - 2] = condition;
  53826. }
  53827. // Action or condition(s) and not CombineAction
  53828. var newAction = instanciate(parsedAction.name, parameters);
  53829. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53830. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53831. if (action)
  53832. action.then(nothing);
  53833. else
  53834. actionManager.registerAction(nothing);
  53835. action = nothing;
  53836. }
  53837. if (combineArray === null) {
  53838. if (newAction instanceof BABYLON.Condition) {
  53839. condition = newAction;
  53840. newAction = action;
  53841. }
  53842. else {
  53843. condition = null;
  53844. if (action)
  53845. action.then(newAction);
  53846. else
  53847. actionManager.registerAction(newAction);
  53848. }
  53849. }
  53850. else {
  53851. combineArray.push(newAction);
  53852. }
  53853. for (var i = 0; i < parsedAction.children.length; i++)
  53854. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53855. };
  53856. // triggers
  53857. for (var i = 0; i < parsedActions.children.length; i++) {
  53858. var triggerParams;
  53859. var trigger = parsedActions.children[i];
  53860. if (trigger.properties.length > 0) {
  53861. var param = trigger.properties[0].value;
  53862. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53863. if (value._meshId) {
  53864. value.mesh = scene.getMeshByID(value._meshId);
  53865. }
  53866. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53867. }
  53868. else
  53869. triggerParams = ActionManager[trigger.name];
  53870. for (var j = 0; j < trigger.children.length; j++) {
  53871. if (!trigger.detached)
  53872. traverse(trigger.children[j], triggerParams, null, null);
  53873. }
  53874. }
  53875. };
  53876. /**
  53877. * Get a trigger name by index
  53878. * @param trigger defines the trigger index
  53879. * @returns a trigger name
  53880. */
  53881. ActionManager.GetTriggerName = function (trigger) {
  53882. switch (trigger) {
  53883. case 0: return "NothingTrigger";
  53884. case 1: return "OnPickTrigger";
  53885. case 2: return "OnLeftPickTrigger";
  53886. case 3: return "OnRightPickTrigger";
  53887. case 4: return "OnCenterPickTrigger";
  53888. case 5: return "OnPickDownTrigger";
  53889. case 6: return "OnPickUpTrigger";
  53890. case 7: return "OnLongPressTrigger";
  53891. case 8: return "OnPointerOverTrigger";
  53892. case 9: return "OnPointerOutTrigger";
  53893. case 10: return "OnEveryFrameTrigger";
  53894. case 11: return "OnIntersectionEnterTrigger";
  53895. case 12: return "OnIntersectionExitTrigger";
  53896. case 13: return "OnKeyDownTrigger";
  53897. case 14: return "OnKeyUpTrigger";
  53898. case 15: return "OnPickOutTrigger";
  53899. default: return "";
  53900. }
  53901. };
  53902. // Statics
  53903. ActionManager._NothingTrigger = 0;
  53904. ActionManager._OnPickTrigger = 1;
  53905. ActionManager._OnLeftPickTrigger = 2;
  53906. ActionManager._OnRightPickTrigger = 3;
  53907. ActionManager._OnCenterPickTrigger = 4;
  53908. ActionManager._OnPickDownTrigger = 5;
  53909. ActionManager._OnDoublePickTrigger = 6;
  53910. ActionManager._OnPickUpTrigger = 7;
  53911. ActionManager._OnLongPressTrigger = 8;
  53912. ActionManager._OnPointerOverTrigger = 9;
  53913. ActionManager._OnPointerOutTrigger = 10;
  53914. ActionManager._OnEveryFrameTrigger = 11;
  53915. ActionManager._OnIntersectionEnterTrigger = 12;
  53916. ActionManager._OnIntersectionExitTrigger = 13;
  53917. ActionManager._OnKeyDownTrigger = 14;
  53918. ActionManager._OnKeyUpTrigger = 15;
  53919. ActionManager._OnPickOutTrigger = 16;
  53920. /** Gets the list of active triggers */
  53921. ActionManager.Triggers = {};
  53922. return ActionManager;
  53923. }());
  53924. BABYLON.ActionManager = ActionManager;
  53925. })(BABYLON || (BABYLON = {}));
  53926. //# sourceMappingURL=babylon.actionManager.js.map
  53927. var BABYLON;
  53928. (function (BABYLON) {
  53929. var InterpolateValueAction = /** @class */ (function (_super) {
  53930. __extends(InterpolateValueAction, _super);
  53931. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53932. if (duration === void 0) { duration = 1000; }
  53933. var _this = _super.call(this, triggerOptions, condition) || this;
  53934. _this.propertyPath = propertyPath;
  53935. _this.value = value;
  53936. _this.duration = duration;
  53937. _this.stopOtherAnimations = stopOtherAnimations;
  53938. _this.onInterpolationDone = onInterpolationDone;
  53939. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53940. _this._target = _this._effectiveTarget = target;
  53941. return _this;
  53942. }
  53943. InterpolateValueAction.prototype._prepare = function () {
  53944. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53945. this._property = this._getProperty(this.propertyPath);
  53946. };
  53947. InterpolateValueAction.prototype.execute = function () {
  53948. var _this = this;
  53949. var scene = this._actionManager.getScene();
  53950. var keys = [
  53951. {
  53952. frame: 0,
  53953. value: this._effectiveTarget[this._property]
  53954. }, {
  53955. frame: 100,
  53956. value: this.value
  53957. }
  53958. ];
  53959. var dataType;
  53960. if (typeof this.value === "number") {
  53961. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53962. }
  53963. else if (this.value instanceof BABYLON.Color3) {
  53964. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53965. }
  53966. else if (this.value instanceof BABYLON.Vector3) {
  53967. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53968. }
  53969. else if (this.value instanceof BABYLON.Matrix) {
  53970. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53971. }
  53972. else if (this.value instanceof BABYLON.Quaternion) {
  53973. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53974. }
  53975. else {
  53976. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53977. return;
  53978. }
  53979. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53980. animation.setKeys(keys);
  53981. if (this.stopOtherAnimations) {
  53982. scene.stopAnimation(this._effectiveTarget);
  53983. }
  53984. var wrapper = function () {
  53985. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53986. if (_this.onInterpolationDone) {
  53987. _this.onInterpolationDone();
  53988. }
  53989. };
  53990. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53991. };
  53992. InterpolateValueAction.prototype.serialize = function (parent) {
  53993. return _super.prototype._serialize.call(this, {
  53994. name: "InterpolateValueAction",
  53995. properties: [
  53996. BABYLON.Action._GetTargetProperty(this._target),
  53997. { name: "propertyPath", value: this.propertyPath },
  53998. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53999. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  54000. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  54001. ]
  54002. }, parent);
  54003. };
  54004. return InterpolateValueAction;
  54005. }(BABYLON.Action));
  54006. BABYLON.InterpolateValueAction = InterpolateValueAction;
  54007. })(BABYLON || (BABYLON = {}));
  54008. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  54009. var BABYLON;
  54010. (function (BABYLON) {
  54011. var SwitchBooleanAction = /** @class */ (function (_super) {
  54012. __extends(SwitchBooleanAction, _super);
  54013. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  54014. var _this = _super.call(this, triggerOptions, condition) || this;
  54015. _this.propertyPath = propertyPath;
  54016. _this._target = _this._effectiveTarget = target;
  54017. return _this;
  54018. }
  54019. SwitchBooleanAction.prototype._prepare = function () {
  54020. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54021. this._property = this._getProperty(this.propertyPath);
  54022. };
  54023. SwitchBooleanAction.prototype.execute = function () {
  54024. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  54025. };
  54026. SwitchBooleanAction.prototype.serialize = function (parent) {
  54027. return _super.prototype._serialize.call(this, {
  54028. name: "SwitchBooleanAction",
  54029. properties: [
  54030. BABYLON.Action._GetTargetProperty(this._target),
  54031. { name: "propertyPath", value: this.propertyPath }
  54032. ]
  54033. }, parent);
  54034. };
  54035. return SwitchBooleanAction;
  54036. }(BABYLON.Action));
  54037. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  54038. var SetStateAction = /** @class */ (function (_super) {
  54039. __extends(SetStateAction, _super);
  54040. function SetStateAction(triggerOptions, target, value, condition) {
  54041. var _this = _super.call(this, triggerOptions, condition) || this;
  54042. _this.value = value;
  54043. _this._target = target;
  54044. return _this;
  54045. }
  54046. SetStateAction.prototype.execute = function () {
  54047. this._target.state = this.value;
  54048. };
  54049. SetStateAction.prototype.serialize = function (parent) {
  54050. return _super.prototype._serialize.call(this, {
  54051. name: "SetStateAction",
  54052. properties: [
  54053. BABYLON.Action._GetTargetProperty(this._target),
  54054. { name: "value", value: this.value }
  54055. ]
  54056. }, parent);
  54057. };
  54058. return SetStateAction;
  54059. }(BABYLON.Action));
  54060. BABYLON.SetStateAction = SetStateAction;
  54061. var SetValueAction = /** @class */ (function (_super) {
  54062. __extends(SetValueAction, _super);
  54063. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  54064. var _this = _super.call(this, triggerOptions, condition) || this;
  54065. _this.propertyPath = propertyPath;
  54066. _this.value = value;
  54067. _this._target = _this._effectiveTarget = target;
  54068. return _this;
  54069. }
  54070. SetValueAction.prototype._prepare = function () {
  54071. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54072. this._property = this._getProperty(this.propertyPath);
  54073. };
  54074. SetValueAction.prototype.execute = function () {
  54075. this._effectiveTarget[this._property] = this.value;
  54076. if (this._target.markAsDirty) {
  54077. this._target.markAsDirty(this._property);
  54078. }
  54079. };
  54080. SetValueAction.prototype.serialize = function (parent) {
  54081. return _super.prototype._serialize.call(this, {
  54082. name: "SetValueAction",
  54083. properties: [
  54084. BABYLON.Action._GetTargetProperty(this._target),
  54085. { name: "propertyPath", value: this.propertyPath },
  54086. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54087. ]
  54088. }, parent);
  54089. };
  54090. return SetValueAction;
  54091. }(BABYLON.Action));
  54092. BABYLON.SetValueAction = SetValueAction;
  54093. var IncrementValueAction = /** @class */ (function (_super) {
  54094. __extends(IncrementValueAction, _super);
  54095. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  54096. var _this = _super.call(this, triggerOptions, condition) || this;
  54097. _this.propertyPath = propertyPath;
  54098. _this.value = value;
  54099. _this._target = _this._effectiveTarget = target;
  54100. return _this;
  54101. }
  54102. IncrementValueAction.prototype._prepare = function () {
  54103. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  54104. this._property = this._getProperty(this.propertyPath);
  54105. if (typeof this._effectiveTarget[this._property] !== "number") {
  54106. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  54107. }
  54108. };
  54109. IncrementValueAction.prototype.execute = function () {
  54110. this._effectiveTarget[this._property] += this.value;
  54111. if (this._target.markAsDirty) {
  54112. this._target.markAsDirty(this._property);
  54113. }
  54114. };
  54115. IncrementValueAction.prototype.serialize = function (parent) {
  54116. return _super.prototype._serialize.call(this, {
  54117. name: "IncrementValueAction",
  54118. properties: [
  54119. BABYLON.Action._GetTargetProperty(this._target),
  54120. { name: "propertyPath", value: this.propertyPath },
  54121. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  54122. ]
  54123. }, parent);
  54124. };
  54125. return IncrementValueAction;
  54126. }(BABYLON.Action));
  54127. BABYLON.IncrementValueAction = IncrementValueAction;
  54128. var PlayAnimationAction = /** @class */ (function (_super) {
  54129. __extends(PlayAnimationAction, _super);
  54130. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  54131. var _this = _super.call(this, triggerOptions, condition) || this;
  54132. _this.from = from;
  54133. _this.to = to;
  54134. _this.loop = loop;
  54135. _this._target = target;
  54136. return _this;
  54137. }
  54138. PlayAnimationAction.prototype._prepare = function () {
  54139. };
  54140. PlayAnimationAction.prototype.execute = function () {
  54141. var scene = this._actionManager.getScene();
  54142. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  54143. };
  54144. PlayAnimationAction.prototype.serialize = function (parent) {
  54145. return _super.prototype._serialize.call(this, {
  54146. name: "PlayAnimationAction",
  54147. properties: [
  54148. BABYLON.Action._GetTargetProperty(this._target),
  54149. { name: "from", value: String(this.from) },
  54150. { name: "to", value: String(this.to) },
  54151. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  54152. ]
  54153. }, parent);
  54154. };
  54155. return PlayAnimationAction;
  54156. }(BABYLON.Action));
  54157. BABYLON.PlayAnimationAction = PlayAnimationAction;
  54158. var StopAnimationAction = /** @class */ (function (_super) {
  54159. __extends(StopAnimationAction, _super);
  54160. function StopAnimationAction(triggerOptions, target, condition) {
  54161. var _this = _super.call(this, triggerOptions, condition) || this;
  54162. _this._target = target;
  54163. return _this;
  54164. }
  54165. StopAnimationAction.prototype._prepare = function () {
  54166. };
  54167. StopAnimationAction.prototype.execute = function () {
  54168. var scene = this._actionManager.getScene();
  54169. scene.stopAnimation(this._target);
  54170. };
  54171. StopAnimationAction.prototype.serialize = function (parent) {
  54172. return _super.prototype._serialize.call(this, {
  54173. name: "StopAnimationAction",
  54174. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  54175. }, parent);
  54176. };
  54177. return StopAnimationAction;
  54178. }(BABYLON.Action));
  54179. BABYLON.StopAnimationAction = StopAnimationAction;
  54180. var DoNothingAction = /** @class */ (function (_super) {
  54181. __extends(DoNothingAction, _super);
  54182. function DoNothingAction(triggerOptions, condition) {
  54183. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  54184. return _super.call(this, triggerOptions, condition) || this;
  54185. }
  54186. DoNothingAction.prototype.execute = function () {
  54187. };
  54188. DoNothingAction.prototype.serialize = function (parent) {
  54189. return _super.prototype._serialize.call(this, {
  54190. name: "DoNothingAction",
  54191. properties: []
  54192. }, parent);
  54193. };
  54194. return DoNothingAction;
  54195. }(BABYLON.Action));
  54196. BABYLON.DoNothingAction = DoNothingAction;
  54197. var CombineAction = /** @class */ (function (_super) {
  54198. __extends(CombineAction, _super);
  54199. function CombineAction(triggerOptions, children, condition) {
  54200. var _this = _super.call(this, triggerOptions, condition) || this;
  54201. _this.children = children;
  54202. return _this;
  54203. }
  54204. CombineAction.prototype._prepare = function () {
  54205. for (var index = 0; index < this.children.length; index++) {
  54206. this.children[index]._actionManager = this._actionManager;
  54207. this.children[index]._prepare();
  54208. }
  54209. };
  54210. CombineAction.prototype.execute = function (evt) {
  54211. for (var index = 0; index < this.children.length; index++) {
  54212. this.children[index].execute(evt);
  54213. }
  54214. };
  54215. CombineAction.prototype.serialize = function (parent) {
  54216. var serializationObject = _super.prototype._serialize.call(this, {
  54217. name: "CombineAction",
  54218. properties: [],
  54219. combine: []
  54220. }, parent);
  54221. for (var i = 0; i < this.children.length; i++) {
  54222. serializationObject.combine.push(this.children[i].serialize(null));
  54223. }
  54224. return serializationObject;
  54225. };
  54226. return CombineAction;
  54227. }(BABYLON.Action));
  54228. BABYLON.CombineAction = CombineAction;
  54229. var ExecuteCodeAction = /** @class */ (function (_super) {
  54230. __extends(ExecuteCodeAction, _super);
  54231. function ExecuteCodeAction(triggerOptions, func, condition) {
  54232. var _this = _super.call(this, triggerOptions, condition) || this;
  54233. _this.func = func;
  54234. return _this;
  54235. }
  54236. ExecuteCodeAction.prototype.execute = function (evt) {
  54237. this.func(evt);
  54238. };
  54239. return ExecuteCodeAction;
  54240. }(BABYLON.Action));
  54241. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  54242. var SetParentAction = /** @class */ (function (_super) {
  54243. __extends(SetParentAction, _super);
  54244. function SetParentAction(triggerOptions, target, parent, condition) {
  54245. var _this = _super.call(this, triggerOptions, condition) || this;
  54246. _this._target = target;
  54247. _this._parent = parent;
  54248. return _this;
  54249. }
  54250. SetParentAction.prototype._prepare = function () {
  54251. };
  54252. SetParentAction.prototype.execute = function () {
  54253. if (this._target.parent === this._parent) {
  54254. return;
  54255. }
  54256. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  54257. invertParentWorldMatrix.invert();
  54258. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  54259. this._target.parent = this._parent;
  54260. };
  54261. SetParentAction.prototype.serialize = function (parent) {
  54262. return _super.prototype._serialize.call(this, {
  54263. name: "SetParentAction",
  54264. properties: [
  54265. BABYLON.Action._GetTargetProperty(this._target),
  54266. BABYLON.Action._GetTargetProperty(this._parent),
  54267. ]
  54268. }, parent);
  54269. };
  54270. return SetParentAction;
  54271. }(BABYLON.Action));
  54272. BABYLON.SetParentAction = SetParentAction;
  54273. var PlaySoundAction = /** @class */ (function (_super) {
  54274. __extends(PlaySoundAction, _super);
  54275. function PlaySoundAction(triggerOptions, sound, condition) {
  54276. var _this = _super.call(this, triggerOptions, condition) || this;
  54277. _this._sound = sound;
  54278. return _this;
  54279. }
  54280. PlaySoundAction.prototype._prepare = function () {
  54281. };
  54282. PlaySoundAction.prototype.execute = function () {
  54283. if (this._sound !== undefined)
  54284. this._sound.play();
  54285. };
  54286. PlaySoundAction.prototype.serialize = function (parent) {
  54287. return _super.prototype._serialize.call(this, {
  54288. name: "PlaySoundAction",
  54289. properties: [{ name: "sound", value: this._sound.name }]
  54290. }, parent);
  54291. };
  54292. return PlaySoundAction;
  54293. }(BABYLON.Action));
  54294. BABYLON.PlaySoundAction = PlaySoundAction;
  54295. var StopSoundAction = /** @class */ (function (_super) {
  54296. __extends(StopSoundAction, _super);
  54297. function StopSoundAction(triggerOptions, sound, condition) {
  54298. var _this = _super.call(this, triggerOptions, condition) || this;
  54299. _this._sound = sound;
  54300. return _this;
  54301. }
  54302. StopSoundAction.prototype._prepare = function () {
  54303. };
  54304. StopSoundAction.prototype.execute = function () {
  54305. if (this._sound !== undefined)
  54306. this._sound.stop();
  54307. };
  54308. StopSoundAction.prototype.serialize = function (parent) {
  54309. return _super.prototype._serialize.call(this, {
  54310. name: "StopSoundAction",
  54311. properties: [{ name: "sound", value: this._sound.name }]
  54312. }, parent);
  54313. };
  54314. return StopSoundAction;
  54315. }(BABYLON.Action));
  54316. BABYLON.StopSoundAction = StopSoundAction;
  54317. })(BABYLON || (BABYLON = {}));
  54318. //# sourceMappingURL=babylon.directActions.js.map
  54319. var BABYLON;
  54320. (function (BABYLON) {
  54321. var SpriteManager = /** @class */ (function () {
  54322. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  54323. if (epsilon === void 0) { epsilon = 0.01; }
  54324. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  54325. this.name = name;
  54326. this.sprites = new Array();
  54327. this.renderingGroupId = 0;
  54328. this.layerMask = 0x0FFFFFFF;
  54329. this.fogEnabled = true;
  54330. this.isPickable = false;
  54331. /**
  54332. * An event triggered when the manager is disposed.
  54333. */
  54334. this.onDisposeObservable = new BABYLON.Observable();
  54335. this._vertexBuffers = {};
  54336. this._capacity = capacity;
  54337. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  54338. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54339. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  54340. if (cellSize.width && cellSize.height) {
  54341. this.cellWidth = cellSize.width;
  54342. this.cellHeight = cellSize.height;
  54343. }
  54344. else if (cellSize !== undefined) {
  54345. this.cellWidth = cellSize;
  54346. this.cellHeight = cellSize;
  54347. }
  54348. else {
  54349. return;
  54350. }
  54351. this._epsilon = epsilon;
  54352. this._scene = scene;
  54353. this._scene.spriteManagers.push(this);
  54354. var indices = [];
  54355. var index = 0;
  54356. for (var count = 0; count < capacity; count++) {
  54357. indices.push(index);
  54358. indices.push(index + 1);
  54359. indices.push(index + 2);
  54360. indices.push(index);
  54361. indices.push(index + 2);
  54362. indices.push(index + 3);
  54363. index += 4;
  54364. }
  54365. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  54366. // VBO
  54367. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  54368. this._vertexData = new Float32Array(capacity * 16 * 4);
  54369. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  54370. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  54371. var options = this._buffer.createVertexBuffer("options", 4, 4);
  54372. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  54373. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  54374. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  54375. this._vertexBuffers["options"] = options;
  54376. this._vertexBuffers["cellInfo"] = cellInfo;
  54377. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  54378. // Effects
  54379. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  54380. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  54381. }
  54382. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  54383. set: function (callback) {
  54384. if (this._onDisposeObserver) {
  54385. this.onDisposeObservable.remove(this._onDisposeObserver);
  54386. }
  54387. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  54388. },
  54389. enumerable: true,
  54390. configurable: true
  54391. });
  54392. Object.defineProperty(SpriteManager.prototype, "texture", {
  54393. get: function () {
  54394. return this._spriteTexture;
  54395. },
  54396. set: function (value) {
  54397. this._spriteTexture = value;
  54398. },
  54399. enumerable: true,
  54400. configurable: true
  54401. });
  54402. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  54403. var arrayOffset = index * 16;
  54404. if (offsetX === 0)
  54405. offsetX = this._epsilon;
  54406. else if (offsetX === 1)
  54407. offsetX = 1 - this._epsilon;
  54408. if (offsetY === 0)
  54409. offsetY = this._epsilon;
  54410. else if (offsetY === 1)
  54411. offsetY = 1 - this._epsilon;
  54412. this._vertexData[arrayOffset] = sprite.position.x;
  54413. this._vertexData[arrayOffset + 1] = sprite.position.y;
  54414. this._vertexData[arrayOffset + 2] = sprite.position.z;
  54415. this._vertexData[arrayOffset + 3] = sprite.angle;
  54416. this._vertexData[arrayOffset + 4] = sprite.width;
  54417. this._vertexData[arrayOffset + 5] = sprite.height;
  54418. this._vertexData[arrayOffset + 6] = offsetX;
  54419. this._vertexData[arrayOffset + 7] = offsetY;
  54420. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  54421. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  54422. var offset = (sprite.cellIndex / rowSize) >> 0;
  54423. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  54424. this._vertexData[arrayOffset + 11] = offset;
  54425. // Color
  54426. this._vertexData[arrayOffset + 12] = sprite.color.r;
  54427. this._vertexData[arrayOffset + 13] = sprite.color.g;
  54428. this._vertexData[arrayOffset + 14] = sprite.color.b;
  54429. this._vertexData[arrayOffset + 15] = sprite.color.a;
  54430. };
  54431. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  54432. var count = Math.min(this._capacity, this.sprites.length);
  54433. var min = BABYLON.Vector3.Zero();
  54434. var max = BABYLON.Vector3.Zero();
  54435. var distance = Number.MAX_VALUE;
  54436. var currentSprite = null;
  54437. var cameraSpacePosition = BABYLON.Vector3.Zero();
  54438. var cameraView = camera.getViewMatrix();
  54439. for (var index = 0; index < count; index++) {
  54440. var sprite = this.sprites[index];
  54441. if (!sprite) {
  54442. continue;
  54443. }
  54444. if (predicate) {
  54445. if (!predicate(sprite)) {
  54446. continue;
  54447. }
  54448. }
  54449. else if (!sprite.isPickable) {
  54450. continue;
  54451. }
  54452. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  54453. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  54454. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  54455. if (ray.intersectsBoxMinMax(min, max)) {
  54456. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  54457. if (distance > currentDistance) {
  54458. distance = currentDistance;
  54459. currentSprite = sprite;
  54460. if (fastCheck) {
  54461. break;
  54462. }
  54463. }
  54464. }
  54465. }
  54466. if (currentSprite) {
  54467. var result = new BABYLON.PickingInfo();
  54468. result.hit = true;
  54469. result.pickedSprite = currentSprite;
  54470. result.distance = distance;
  54471. return result;
  54472. }
  54473. return null;
  54474. };
  54475. SpriteManager.prototype.render = function () {
  54476. // Check
  54477. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  54478. return;
  54479. var engine = this._scene.getEngine();
  54480. var baseSize = this._spriteTexture.getBaseSize();
  54481. // Sprites
  54482. var deltaTime = engine.getDeltaTime();
  54483. var max = Math.min(this._capacity, this.sprites.length);
  54484. var rowSize = baseSize.width / this.cellWidth;
  54485. var offset = 0;
  54486. for (var index = 0; index < max; index++) {
  54487. var sprite = this.sprites[index];
  54488. if (!sprite) {
  54489. continue;
  54490. }
  54491. sprite._animate(deltaTime);
  54492. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  54493. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  54494. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  54495. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  54496. }
  54497. this._buffer.update(this._vertexData);
  54498. // Render
  54499. var effect = this._effectBase;
  54500. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54501. effect = this._effectFog;
  54502. }
  54503. engine.enableEffect(effect);
  54504. var viewMatrix = this._scene.getViewMatrix();
  54505. effect.setTexture("diffuseSampler", this._spriteTexture);
  54506. effect.setMatrix("view", viewMatrix);
  54507. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  54508. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  54509. // Fog
  54510. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  54511. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  54512. effect.setColor3("vFogColor", this._scene.fogColor);
  54513. }
  54514. // VBOs
  54515. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  54516. // Draw order
  54517. engine.setDepthFunctionToLessOrEqual();
  54518. effect.setBool("alphaTest", true);
  54519. engine.setColorWrite(false);
  54520. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54521. engine.setColorWrite(true);
  54522. effect.setBool("alphaTest", false);
  54523. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  54524. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, max * 6);
  54525. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  54526. };
  54527. SpriteManager.prototype.dispose = function () {
  54528. if (this._buffer) {
  54529. this._buffer.dispose();
  54530. this._buffer = null;
  54531. }
  54532. if (this._indexBuffer) {
  54533. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  54534. this._indexBuffer = null;
  54535. }
  54536. if (this._spriteTexture) {
  54537. this._spriteTexture.dispose();
  54538. this._spriteTexture = null;
  54539. }
  54540. // Remove from scene
  54541. var index = this._scene.spriteManagers.indexOf(this);
  54542. this._scene.spriteManagers.splice(index, 1);
  54543. // Callback
  54544. this.onDisposeObservable.notifyObservers(this);
  54545. this.onDisposeObservable.clear();
  54546. };
  54547. return SpriteManager;
  54548. }());
  54549. BABYLON.SpriteManager = SpriteManager;
  54550. })(BABYLON || (BABYLON = {}));
  54551. //# sourceMappingURL=babylon.spriteManager.js.map
  54552. var BABYLON;
  54553. (function (BABYLON) {
  54554. var Sprite = /** @class */ (function () {
  54555. function Sprite(name, manager) {
  54556. this.name = name;
  54557. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  54558. this.width = 1.0;
  54559. this.height = 1.0;
  54560. this.angle = 0;
  54561. this.cellIndex = 0;
  54562. this.invertU = 0;
  54563. this.invertV = 0;
  54564. this.animations = new Array();
  54565. this.isPickable = false;
  54566. this._animationStarted = false;
  54567. this._loopAnimation = false;
  54568. this._fromIndex = 0;
  54569. this._toIndex = 0;
  54570. this._delay = 0;
  54571. this._direction = 1;
  54572. this._time = 0;
  54573. this._manager = manager;
  54574. this._manager.sprites.push(this);
  54575. this.position = BABYLON.Vector3.Zero();
  54576. }
  54577. Object.defineProperty(Sprite.prototype, "size", {
  54578. get: function () {
  54579. return this.width;
  54580. },
  54581. set: function (value) {
  54582. this.width = value;
  54583. this.height = value;
  54584. },
  54585. enumerable: true,
  54586. configurable: true
  54587. });
  54588. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  54589. this._fromIndex = from;
  54590. this._toIndex = to;
  54591. this._loopAnimation = loop;
  54592. this._delay = delay;
  54593. this._animationStarted = true;
  54594. this._direction = from < to ? 1 : -1;
  54595. this.cellIndex = from;
  54596. this._time = 0;
  54597. this._onAnimationEnd = onAnimationEnd;
  54598. };
  54599. Sprite.prototype.stopAnimation = function () {
  54600. this._animationStarted = false;
  54601. };
  54602. Sprite.prototype._animate = function (deltaTime) {
  54603. if (!this._animationStarted)
  54604. return;
  54605. this._time += deltaTime;
  54606. if (this._time > this._delay) {
  54607. this._time = this._time % this._delay;
  54608. this.cellIndex += this._direction;
  54609. if (this.cellIndex > this._toIndex) {
  54610. if (this._loopAnimation) {
  54611. this.cellIndex = this._fromIndex;
  54612. }
  54613. else {
  54614. this.cellIndex = this._toIndex;
  54615. this._animationStarted = false;
  54616. if (this._onAnimationEnd) {
  54617. this._onAnimationEnd();
  54618. }
  54619. if (this.disposeWhenFinishedAnimating) {
  54620. this.dispose();
  54621. }
  54622. }
  54623. }
  54624. }
  54625. };
  54626. Sprite.prototype.dispose = function () {
  54627. for (var i = 0; i < this._manager.sprites.length; i++) {
  54628. if (this._manager.sprites[i] == this) {
  54629. this._manager.sprites.splice(i, 1);
  54630. }
  54631. }
  54632. };
  54633. return Sprite;
  54634. }());
  54635. BABYLON.Sprite = Sprite;
  54636. })(BABYLON || (BABYLON = {}));
  54637. //# sourceMappingURL=babylon.sprite.js.map
  54638. var BABYLON;
  54639. (function (BABYLON) {
  54640. var IntersectionInfo = /** @class */ (function () {
  54641. function IntersectionInfo(bu, bv, distance) {
  54642. this.bu = bu;
  54643. this.bv = bv;
  54644. this.distance = distance;
  54645. this.faceId = 0;
  54646. this.subMeshId = 0;
  54647. }
  54648. return IntersectionInfo;
  54649. }());
  54650. BABYLON.IntersectionInfo = IntersectionInfo;
  54651. var PickingInfo = /** @class */ (function () {
  54652. function PickingInfo() {
  54653. this.hit = false;
  54654. this.distance = 0;
  54655. this.pickedPoint = null;
  54656. this.pickedMesh = null;
  54657. this.bu = 0;
  54658. this.bv = 0;
  54659. this.faceId = -1;
  54660. this.subMeshId = 0;
  54661. this.pickedSprite = null;
  54662. }
  54663. // Methods
  54664. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  54665. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  54666. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  54667. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  54668. return null;
  54669. }
  54670. var indices = this.pickedMesh.getIndices();
  54671. if (!indices) {
  54672. return null;
  54673. }
  54674. var result;
  54675. if (useVerticesNormals) {
  54676. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  54677. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  54678. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  54679. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  54680. normal0 = normal0.scale(this.bu);
  54681. normal1 = normal1.scale(this.bv);
  54682. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  54683. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  54684. }
  54685. else {
  54686. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  54687. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  54688. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  54689. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  54690. var p1p2 = vertex1.subtract(vertex2);
  54691. var p3p2 = vertex3.subtract(vertex2);
  54692. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  54693. }
  54694. if (useWorldCoordinates) {
  54695. result = BABYLON.Vector3.TransformNormal(result, this.pickedMesh.getWorldMatrix());
  54696. }
  54697. return BABYLON.Vector3.Normalize(result);
  54698. };
  54699. PickingInfo.prototype.getTextureCoordinates = function () {
  54700. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54701. return null;
  54702. }
  54703. var indices = this.pickedMesh.getIndices();
  54704. if (!indices) {
  54705. return null;
  54706. }
  54707. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54708. if (!uvs) {
  54709. return null;
  54710. }
  54711. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54712. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54713. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54714. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54715. uv1 = uv1.scale(this.bu);
  54716. uv2 = uv2.scale(this.bv);
  54717. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54718. };
  54719. return PickingInfo;
  54720. }());
  54721. BABYLON.PickingInfo = PickingInfo;
  54722. })(BABYLON || (BABYLON = {}));
  54723. //# sourceMappingURL=babylon.pickingInfo.js.map
  54724. var BABYLON;
  54725. (function (BABYLON) {
  54726. var Ray = /** @class */ (function () {
  54727. function Ray(origin, direction, length) {
  54728. if (length === void 0) { length = Number.MAX_VALUE; }
  54729. this.origin = origin;
  54730. this.direction = direction;
  54731. this.length = length;
  54732. }
  54733. // Methods
  54734. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54735. var d = 0.0;
  54736. var maxValue = Number.MAX_VALUE;
  54737. var inv;
  54738. var min;
  54739. var max;
  54740. var temp;
  54741. if (Math.abs(this.direction.x) < 0.0000001) {
  54742. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54743. return false;
  54744. }
  54745. }
  54746. else {
  54747. inv = 1.0 / this.direction.x;
  54748. min = (minimum.x - this.origin.x) * inv;
  54749. max = (maximum.x - this.origin.x) * inv;
  54750. if (max === -Infinity) {
  54751. max = Infinity;
  54752. }
  54753. if (min > max) {
  54754. temp = min;
  54755. min = max;
  54756. max = temp;
  54757. }
  54758. d = Math.max(min, d);
  54759. maxValue = Math.min(max, maxValue);
  54760. if (d > maxValue) {
  54761. return false;
  54762. }
  54763. }
  54764. if (Math.abs(this.direction.y) < 0.0000001) {
  54765. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54766. return false;
  54767. }
  54768. }
  54769. else {
  54770. inv = 1.0 / this.direction.y;
  54771. min = (minimum.y - this.origin.y) * inv;
  54772. max = (maximum.y - this.origin.y) * inv;
  54773. if (max === -Infinity) {
  54774. max = Infinity;
  54775. }
  54776. if (min > max) {
  54777. temp = min;
  54778. min = max;
  54779. max = temp;
  54780. }
  54781. d = Math.max(min, d);
  54782. maxValue = Math.min(max, maxValue);
  54783. if (d > maxValue) {
  54784. return false;
  54785. }
  54786. }
  54787. if (Math.abs(this.direction.z) < 0.0000001) {
  54788. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54789. return false;
  54790. }
  54791. }
  54792. else {
  54793. inv = 1.0 / this.direction.z;
  54794. min = (minimum.z - this.origin.z) * inv;
  54795. max = (maximum.z - this.origin.z) * inv;
  54796. if (max === -Infinity) {
  54797. max = Infinity;
  54798. }
  54799. if (min > max) {
  54800. temp = min;
  54801. min = max;
  54802. max = temp;
  54803. }
  54804. d = Math.max(min, d);
  54805. maxValue = Math.min(max, maxValue);
  54806. if (d > maxValue) {
  54807. return false;
  54808. }
  54809. }
  54810. return true;
  54811. };
  54812. Ray.prototype.intersectsBox = function (box) {
  54813. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54814. };
  54815. Ray.prototype.intersectsSphere = function (sphere) {
  54816. var x = sphere.center.x - this.origin.x;
  54817. var y = sphere.center.y - this.origin.y;
  54818. var z = sphere.center.z - this.origin.z;
  54819. var pyth = (x * x) + (y * y) + (z * z);
  54820. var rr = sphere.radius * sphere.radius;
  54821. if (pyth <= rr) {
  54822. return true;
  54823. }
  54824. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54825. if (dot < 0.0) {
  54826. return false;
  54827. }
  54828. var temp = pyth - (dot * dot);
  54829. return temp <= rr;
  54830. };
  54831. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54832. if (!this._edge1) {
  54833. this._edge1 = BABYLON.Vector3.Zero();
  54834. this._edge2 = BABYLON.Vector3.Zero();
  54835. this._pvec = BABYLON.Vector3.Zero();
  54836. this._tvec = BABYLON.Vector3.Zero();
  54837. this._qvec = BABYLON.Vector3.Zero();
  54838. }
  54839. vertex1.subtractToRef(vertex0, this._edge1);
  54840. vertex2.subtractToRef(vertex0, this._edge2);
  54841. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54842. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54843. if (det === 0) {
  54844. return null;
  54845. }
  54846. var invdet = 1 / det;
  54847. this.origin.subtractToRef(vertex0, this._tvec);
  54848. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54849. if (bu < 0 || bu > 1.0) {
  54850. return null;
  54851. }
  54852. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54853. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54854. if (bv < 0 || bu + bv > 1.0) {
  54855. return null;
  54856. }
  54857. //check if the distance is longer than the predefined length.
  54858. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54859. if (distance > this.length) {
  54860. return null;
  54861. }
  54862. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54863. };
  54864. Ray.prototype.intersectsPlane = function (plane) {
  54865. var distance;
  54866. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54867. if (Math.abs(result1) < 9.99999997475243E-07) {
  54868. return null;
  54869. }
  54870. else {
  54871. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54872. distance = (-plane.d - result2) / result1;
  54873. if (distance < 0.0) {
  54874. if (distance < -9.99999997475243E-07) {
  54875. return null;
  54876. }
  54877. else {
  54878. return 0;
  54879. }
  54880. }
  54881. return distance;
  54882. }
  54883. };
  54884. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54885. var tm = BABYLON.Tmp.Matrix[0];
  54886. mesh.getWorldMatrix().invertToRef(tm);
  54887. if (this._tmpRay) {
  54888. Ray.TransformToRef(this, tm, this._tmpRay);
  54889. }
  54890. else {
  54891. this._tmpRay = Ray.Transform(this, tm);
  54892. }
  54893. return mesh.intersects(this._tmpRay, fastCheck);
  54894. };
  54895. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54896. if (results) {
  54897. results.length = 0;
  54898. }
  54899. else {
  54900. results = [];
  54901. }
  54902. for (var i = 0; i < meshes.length; i++) {
  54903. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54904. if (pickInfo.hit) {
  54905. results.push(pickInfo);
  54906. }
  54907. }
  54908. results.sort(this._comparePickingInfo);
  54909. return results;
  54910. };
  54911. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54912. if (pickingInfoA.distance < pickingInfoB.distance) {
  54913. return -1;
  54914. }
  54915. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54916. return 1;
  54917. }
  54918. else {
  54919. return 0;
  54920. }
  54921. };
  54922. /**
  54923. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54924. * @param sega the first point of the segment to test the intersection against
  54925. * @param segb the second point of the segment to test the intersection against
  54926. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54927. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54928. */
  54929. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54930. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54931. var u = segb.subtract(sega);
  54932. var v = rsegb.subtract(this.origin);
  54933. var w = sega.subtract(this.origin);
  54934. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54935. var b = BABYLON.Vector3.Dot(u, v);
  54936. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54937. var d = BABYLON.Vector3.Dot(u, w);
  54938. var e = BABYLON.Vector3.Dot(v, w);
  54939. var D = a * c - b * b; // always >= 0
  54940. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54941. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54942. // compute the line parameters of the two closest points
  54943. if (D < Ray.smallnum) { // the lines are almost parallel
  54944. sN = 0.0; // force using point P0 on segment S1
  54945. sD = 1.0; // to prevent possible division by 0.0 later
  54946. tN = e;
  54947. tD = c;
  54948. }
  54949. else { // get the closest points on the infinite lines
  54950. sN = (b * e - c * d);
  54951. tN = (a * e - b * d);
  54952. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54953. sN = 0.0;
  54954. tN = e;
  54955. tD = c;
  54956. }
  54957. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54958. sN = sD;
  54959. tN = e + b;
  54960. tD = c;
  54961. }
  54962. }
  54963. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54964. tN = 0.0;
  54965. // recompute sc for this edge
  54966. if (-d < 0.0) {
  54967. sN = 0.0;
  54968. }
  54969. else if (-d > a)
  54970. sN = sD;
  54971. else {
  54972. sN = -d;
  54973. sD = a;
  54974. }
  54975. }
  54976. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54977. tN = tD;
  54978. // recompute sc for this edge
  54979. if ((-d + b) < 0.0) {
  54980. sN = 0;
  54981. }
  54982. else if ((-d + b) > a) {
  54983. sN = sD;
  54984. }
  54985. else {
  54986. sN = (-d + b);
  54987. sD = a;
  54988. }
  54989. }
  54990. // finally do the division to get sc and tc
  54991. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54992. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54993. // get the difference of the two closest points
  54994. var qtc = v.multiplyByFloats(tc, tc, tc);
  54995. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54996. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54997. if (isIntersected) {
  54998. return qtc.length();
  54999. }
  55000. return -1;
  55001. };
  55002. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55003. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  55004. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  55005. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  55006. this.direction.normalize();
  55007. return this;
  55008. };
  55009. // Statics
  55010. Ray.Zero = function () {
  55011. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  55012. };
  55013. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  55014. var result = Ray.Zero();
  55015. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  55016. };
  55017. /**
  55018. * 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
  55019. * transformed to the given world matrix.
  55020. * @param origin The origin point
  55021. * @param end The end point
  55022. * @param world a matrix to transform the ray to. Default is the identity matrix.
  55023. */
  55024. Ray.CreateNewFromTo = function (origin, end, world) {
  55025. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  55026. var direction = end.subtract(origin);
  55027. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  55028. direction.normalize();
  55029. return Ray.Transform(new Ray(origin, direction, length), world);
  55030. };
  55031. Ray.Transform = function (ray, matrix) {
  55032. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  55033. Ray.TransformToRef(ray, matrix, result);
  55034. return result;
  55035. };
  55036. Ray.TransformToRef = function (ray, matrix, result) {
  55037. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  55038. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  55039. result.length = ray.length;
  55040. var dir = result.direction;
  55041. var len = dir.length();
  55042. if (!(len === 0 || len === 1)) {
  55043. var num = 1.0 / len;
  55044. dir.x *= num;
  55045. dir.y *= num;
  55046. dir.z *= num;
  55047. result.length *= len;
  55048. }
  55049. };
  55050. Ray.smallnum = 0.00000001;
  55051. Ray.rayl = 10e8;
  55052. return Ray;
  55053. }());
  55054. BABYLON.Ray = Ray;
  55055. })(BABYLON || (BABYLON = {}));
  55056. //# sourceMappingURL=babylon.ray.js.map
  55057. var BABYLON;
  55058. (function (BABYLON) {
  55059. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  55060. if (boxMin.x > sphereCenter.x + sphereRadius)
  55061. return false;
  55062. if (sphereCenter.x - sphereRadius > boxMax.x)
  55063. return false;
  55064. if (boxMin.y > sphereCenter.y + sphereRadius)
  55065. return false;
  55066. if (sphereCenter.y - sphereRadius > boxMax.y)
  55067. return false;
  55068. if (boxMin.z > sphereCenter.z + sphereRadius)
  55069. return false;
  55070. if (sphereCenter.z - sphereRadius > boxMax.z)
  55071. return false;
  55072. return true;
  55073. };
  55074. var getLowestRoot = (function () {
  55075. var result = { root: 0, found: false };
  55076. return function (a, b, c, maxR) {
  55077. result.root = 0;
  55078. result.found = false;
  55079. var determinant = b * b - 4.0 * a * c;
  55080. if (determinant < 0)
  55081. return result;
  55082. var sqrtD = Math.sqrt(determinant);
  55083. var r1 = (-b - sqrtD) / (2.0 * a);
  55084. var r2 = (-b + sqrtD) / (2.0 * a);
  55085. if (r1 > r2) {
  55086. var temp = r2;
  55087. r2 = r1;
  55088. r1 = temp;
  55089. }
  55090. if (r1 > 0 && r1 < maxR) {
  55091. result.root = r1;
  55092. result.found = true;
  55093. return result;
  55094. }
  55095. if (r2 > 0 && r2 < maxR) {
  55096. result.root = r2;
  55097. result.found = true;
  55098. return result;
  55099. }
  55100. return result;
  55101. };
  55102. })();
  55103. var Collider = /** @class */ (function () {
  55104. function Collider() {
  55105. this._collisionPoint = BABYLON.Vector3.Zero();
  55106. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  55107. this._tempVector = BABYLON.Vector3.Zero();
  55108. this._tempVector2 = BABYLON.Vector3.Zero();
  55109. this._tempVector3 = BABYLON.Vector3.Zero();
  55110. this._tempVector4 = BABYLON.Vector3.Zero();
  55111. this._edge = BABYLON.Vector3.Zero();
  55112. this._baseToVertex = BABYLON.Vector3.Zero();
  55113. this._destinationPoint = BABYLON.Vector3.Zero();
  55114. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  55115. this._displacementVector = BABYLON.Vector3.Zero();
  55116. this._radius = BABYLON.Vector3.One();
  55117. this._retry = 0;
  55118. this._basePointWorld = BABYLON.Vector3.Zero();
  55119. this._velocityWorld = BABYLON.Vector3.Zero();
  55120. this._normalizedVelocity = BABYLON.Vector3.Zero();
  55121. this._collisionMask = -1;
  55122. }
  55123. Object.defineProperty(Collider.prototype, "collisionMask", {
  55124. get: function () {
  55125. return this._collisionMask;
  55126. },
  55127. set: function (mask) {
  55128. this._collisionMask = !isNaN(mask) ? mask : -1;
  55129. },
  55130. enumerable: true,
  55131. configurable: true
  55132. });
  55133. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  55134. /**
  55135. * Gets the plane normal used to compute the sliding response (in local space)
  55136. */
  55137. get: function () {
  55138. return this._slidePlaneNormal;
  55139. },
  55140. enumerable: true,
  55141. configurable: true
  55142. });
  55143. // Methods
  55144. Collider.prototype._initialize = function (source, dir, e) {
  55145. this._velocity = dir;
  55146. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  55147. this._basePoint = source;
  55148. source.multiplyToRef(this._radius, this._basePointWorld);
  55149. dir.multiplyToRef(this._radius, this._velocityWorld);
  55150. this._velocityWorldLength = this._velocityWorld.length();
  55151. this._epsilon = e;
  55152. this.collisionFound = false;
  55153. };
  55154. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  55155. pa.subtractToRef(point, this._tempVector);
  55156. pb.subtractToRef(point, this._tempVector2);
  55157. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  55158. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55159. if (d < 0)
  55160. return false;
  55161. pc.subtractToRef(point, this._tempVector3);
  55162. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  55163. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55164. if (d < 0)
  55165. return false;
  55166. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  55167. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  55168. return d >= 0;
  55169. };
  55170. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  55171. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  55172. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  55173. if (distance > this._velocityWorldLength + max + sphereRadius) {
  55174. return false;
  55175. }
  55176. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  55177. return false;
  55178. return true;
  55179. };
  55180. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  55181. var t0;
  55182. var embeddedInPlane = false;
  55183. //defensive programming, actually not needed.
  55184. if (!trianglePlaneArray) {
  55185. trianglePlaneArray = [];
  55186. }
  55187. if (!trianglePlaneArray[faceIndex]) {
  55188. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  55189. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  55190. }
  55191. var trianglePlane = trianglePlaneArray[faceIndex];
  55192. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  55193. return;
  55194. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  55195. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  55196. if (normalDotVelocity == 0) {
  55197. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  55198. return;
  55199. embeddedInPlane = true;
  55200. t0 = 0;
  55201. }
  55202. else {
  55203. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55204. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  55205. if (t0 > t1) {
  55206. var temp = t1;
  55207. t1 = t0;
  55208. t0 = temp;
  55209. }
  55210. if (t0 > 1.0 || t1 < 0.0)
  55211. return;
  55212. if (t0 < 0)
  55213. t0 = 0;
  55214. if (t0 > 1.0)
  55215. t0 = 1.0;
  55216. }
  55217. this._collisionPoint.copyFromFloats(0, 0, 0);
  55218. var found = false;
  55219. var t = 1.0;
  55220. if (!embeddedInPlane) {
  55221. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  55222. this._velocity.scaleToRef(t0, this._tempVector);
  55223. this._planeIntersectionPoint.addInPlace(this._tempVector);
  55224. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  55225. found = true;
  55226. t = t0;
  55227. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  55228. }
  55229. }
  55230. if (!found) {
  55231. var velocitySquaredLength = this._velocity.lengthSquared();
  55232. var a = velocitySquaredLength;
  55233. this._basePoint.subtractToRef(p1, this._tempVector);
  55234. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55235. var c = this._tempVector.lengthSquared() - 1.0;
  55236. var lowestRoot = getLowestRoot(a, b, c, t);
  55237. if (lowestRoot.found) {
  55238. t = lowestRoot.root;
  55239. found = true;
  55240. this._collisionPoint.copyFrom(p1);
  55241. }
  55242. this._basePoint.subtractToRef(p2, this._tempVector);
  55243. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55244. c = this._tempVector.lengthSquared() - 1.0;
  55245. lowestRoot = getLowestRoot(a, b, c, t);
  55246. if (lowestRoot.found) {
  55247. t = lowestRoot.root;
  55248. found = true;
  55249. this._collisionPoint.copyFrom(p2);
  55250. }
  55251. this._basePoint.subtractToRef(p3, this._tempVector);
  55252. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  55253. c = this._tempVector.lengthSquared() - 1.0;
  55254. lowestRoot = getLowestRoot(a, b, c, t);
  55255. if (lowestRoot.found) {
  55256. t = lowestRoot.root;
  55257. found = true;
  55258. this._collisionPoint.copyFrom(p3);
  55259. }
  55260. p2.subtractToRef(p1, this._edge);
  55261. p1.subtractToRef(this._basePoint, this._baseToVertex);
  55262. var edgeSquaredLength = this._edge.lengthSquared();
  55263. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55264. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55265. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55266. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55267. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55268. lowestRoot = getLowestRoot(a, b, c, t);
  55269. if (lowestRoot.found) {
  55270. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55271. if (f >= 0.0 && f <= 1.0) {
  55272. t = lowestRoot.root;
  55273. found = true;
  55274. this._edge.scaleInPlace(f);
  55275. p1.addToRef(this._edge, this._collisionPoint);
  55276. }
  55277. }
  55278. p3.subtractToRef(p2, this._edge);
  55279. p2.subtractToRef(this._basePoint, this._baseToVertex);
  55280. edgeSquaredLength = this._edge.lengthSquared();
  55281. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55282. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55283. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55284. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55285. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55286. lowestRoot = getLowestRoot(a, b, c, t);
  55287. if (lowestRoot.found) {
  55288. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55289. if (f >= 0.0 && f <= 1.0) {
  55290. t = lowestRoot.root;
  55291. found = true;
  55292. this._edge.scaleInPlace(f);
  55293. p2.addToRef(this._edge, this._collisionPoint);
  55294. }
  55295. }
  55296. p1.subtractToRef(p3, this._edge);
  55297. p3.subtractToRef(this._basePoint, this._baseToVertex);
  55298. edgeSquaredLength = this._edge.lengthSquared();
  55299. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  55300. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  55301. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  55302. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  55303. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  55304. lowestRoot = getLowestRoot(a, b, c, t);
  55305. if (lowestRoot.found) {
  55306. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  55307. if (f >= 0.0 && f <= 1.0) {
  55308. t = lowestRoot.root;
  55309. found = true;
  55310. this._edge.scaleInPlace(f);
  55311. p3.addToRef(this._edge, this._collisionPoint);
  55312. }
  55313. }
  55314. }
  55315. if (found) {
  55316. var distToCollision = t * this._velocity.length();
  55317. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  55318. if (!this.intersectionPoint) {
  55319. this.intersectionPoint = this._collisionPoint.clone();
  55320. }
  55321. else {
  55322. this.intersectionPoint.copyFrom(this._collisionPoint);
  55323. }
  55324. this._nearestDistance = distToCollision;
  55325. this.collisionFound = true;
  55326. }
  55327. }
  55328. };
  55329. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  55330. for (var i = indexStart; i < indexEnd; i += 3) {
  55331. var p1 = pts[indices[i] - decal];
  55332. var p2 = pts[indices[i + 1] - decal];
  55333. var p3 = pts[indices[i + 2] - decal];
  55334. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  55335. }
  55336. };
  55337. Collider.prototype._getResponse = function (pos, vel) {
  55338. pos.addToRef(vel, this._destinationPoint);
  55339. vel.scaleInPlace((this._nearestDistance / vel.length()));
  55340. this._basePoint.addToRef(vel, pos);
  55341. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  55342. this._slidePlaneNormal.normalize();
  55343. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  55344. pos.addInPlace(this._displacementVector);
  55345. this.intersectionPoint.addInPlace(this._displacementVector);
  55346. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  55347. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  55348. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  55349. };
  55350. return Collider;
  55351. }());
  55352. BABYLON.Collider = Collider;
  55353. })(BABYLON || (BABYLON = {}));
  55354. //# sourceMappingURL=babylon.collider.js.map
  55355. var BABYLON;
  55356. (function (BABYLON) {
  55357. //WebWorker code will be inserted to this variable.
  55358. BABYLON.CollisionWorker = "";
  55359. /** Defines supported task for worker process */
  55360. var WorkerTaskType;
  55361. (function (WorkerTaskType) {
  55362. /** Initialization */
  55363. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  55364. /** Update of geometry */
  55365. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  55366. /** Evaluate collision */
  55367. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  55368. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  55369. /** Defines kind of replies returned by worker */
  55370. var WorkerReplyType;
  55371. (function (WorkerReplyType) {
  55372. /** Success */
  55373. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  55374. /** Unkown error */
  55375. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  55376. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  55377. var CollisionCoordinatorWorker = /** @class */ (function () {
  55378. function CollisionCoordinatorWorker() {
  55379. var _this = this;
  55380. this._scaledPosition = BABYLON.Vector3.Zero();
  55381. this._scaledVelocity = BABYLON.Vector3.Zero();
  55382. this.onMeshUpdated = function (transformNode) {
  55383. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  55384. };
  55385. this.onGeometryUpdated = function (geometry) {
  55386. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  55387. };
  55388. this._afterRender = function () {
  55389. if (!_this._init)
  55390. return;
  55391. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  55392. return;
  55393. }
  55394. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  55395. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  55396. if (_this._runningUpdated > 4) {
  55397. return;
  55398. }
  55399. ++_this._runningUpdated;
  55400. var payload = {
  55401. updatedMeshes: _this._addUpdateMeshesList,
  55402. updatedGeometries: _this._addUpdateGeometriesList,
  55403. removedGeometries: _this._toRemoveGeometryArray,
  55404. removedMeshes: _this._toRemoveMeshesArray
  55405. };
  55406. var message = {
  55407. payload: payload,
  55408. taskType: WorkerTaskType.UPDATE
  55409. };
  55410. var serializable = [];
  55411. for (var id in payload.updatedGeometries) {
  55412. if (payload.updatedGeometries.hasOwnProperty(id)) {
  55413. //prepare transferables
  55414. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  55415. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  55416. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  55417. }
  55418. }
  55419. _this._worker.postMessage(message, serializable);
  55420. _this._addUpdateMeshesList = {};
  55421. _this._addUpdateGeometriesList = {};
  55422. _this._toRemoveGeometryArray = [];
  55423. _this._toRemoveMeshesArray = [];
  55424. };
  55425. this._onMessageFromWorker = function (e) {
  55426. var returnData = e.data;
  55427. if (returnData.error != WorkerReplyType.SUCCESS) {
  55428. //TODO what errors can be returned from the worker?
  55429. BABYLON.Tools.Warn("error returned from worker!");
  55430. return;
  55431. }
  55432. switch (returnData.taskType) {
  55433. case WorkerTaskType.INIT:
  55434. _this._init = true;
  55435. //Update the worked with ALL of the scene's current state
  55436. _this._scene.meshes.forEach(function (mesh) {
  55437. _this.onMeshAdded(mesh);
  55438. });
  55439. _this._scene.getGeometries().forEach(function (geometry) {
  55440. _this.onGeometryAdded(geometry);
  55441. });
  55442. break;
  55443. case WorkerTaskType.UPDATE:
  55444. _this._runningUpdated--;
  55445. break;
  55446. case WorkerTaskType.COLLIDE:
  55447. var returnPayload = returnData.payload;
  55448. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  55449. return;
  55450. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  55451. if (callback) {
  55452. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  55453. if (mesh) {
  55454. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  55455. }
  55456. }
  55457. //cleanup
  55458. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  55459. break;
  55460. }
  55461. };
  55462. this._collisionsCallbackArray = [];
  55463. this._init = false;
  55464. this._runningUpdated = 0;
  55465. this._addUpdateMeshesList = {};
  55466. this._addUpdateGeometriesList = {};
  55467. this._toRemoveGeometryArray = [];
  55468. this._toRemoveMeshesArray = [];
  55469. }
  55470. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55471. if (!this._init)
  55472. return;
  55473. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  55474. return;
  55475. position.divideToRef(collider._radius, this._scaledPosition);
  55476. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55477. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  55478. var payload = {
  55479. collider: {
  55480. position: this._scaledPosition.asArray(),
  55481. velocity: this._scaledVelocity.asArray(),
  55482. radius: collider._radius.asArray()
  55483. },
  55484. collisionId: collisionIndex,
  55485. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  55486. maximumRetry: maximumRetry
  55487. };
  55488. var message = {
  55489. payload: payload,
  55490. taskType: WorkerTaskType.COLLIDE
  55491. };
  55492. this._worker.postMessage(message);
  55493. };
  55494. CollisionCoordinatorWorker.prototype.init = function (scene) {
  55495. this._scene = scene;
  55496. this._scene.registerAfterRender(this._afterRender);
  55497. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  55498. this._worker = new Worker(workerUrl);
  55499. this._worker.onmessage = this._onMessageFromWorker;
  55500. var message = {
  55501. payload: {},
  55502. taskType: WorkerTaskType.INIT
  55503. };
  55504. this._worker.postMessage(message);
  55505. };
  55506. CollisionCoordinatorWorker.prototype.destroy = function () {
  55507. this._scene.unregisterAfterRender(this._afterRender);
  55508. this._worker.terminate();
  55509. };
  55510. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  55511. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  55512. this.onMeshUpdated(mesh);
  55513. };
  55514. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  55515. this._toRemoveMeshesArray.push(mesh.uniqueId);
  55516. };
  55517. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  55518. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  55519. geometry.onGeometryUpdated = this.onGeometryUpdated;
  55520. this.onGeometryUpdated(geometry);
  55521. };
  55522. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  55523. this._toRemoveGeometryArray.push(geometry.id);
  55524. };
  55525. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  55526. var submeshes = [];
  55527. if (mesh.subMeshes) {
  55528. submeshes = mesh.subMeshes.map(function (sm, idx) {
  55529. var boundingInfo = sm.getBoundingInfo();
  55530. return {
  55531. position: idx,
  55532. verticesStart: sm.verticesStart,
  55533. verticesCount: sm.verticesCount,
  55534. indexStart: sm.indexStart,
  55535. indexCount: sm.indexCount,
  55536. hasMaterial: !!sm.getMaterial(),
  55537. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55538. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55539. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55540. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  55541. };
  55542. });
  55543. }
  55544. var geometryId = null;
  55545. if (mesh instanceof BABYLON.Mesh) {
  55546. var geometry = mesh.geometry;
  55547. geometryId = geometry ? geometry.id : null;
  55548. }
  55549. else if (mesh instanceof BABYLON.InstancedMesh) {
  55550. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  55551. geometryId = geometry ? geometry.id : null;
  55552. }
  55553. var boundingInfo = mesh.getBoundingInfo();
  55554. return {
  55555. uniqueId: mesh.uniqueId,
  55556. id: mesh.id,
  55557. name: mesh.name,
  55558. geometryId: geometryId,
  55559. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  55560. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  55561. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  55562. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  55563. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  55564. subMeshes: submeshes,
  55565. checkCollisions: mesh.checkCollisions
  55566. };
  55567. };
  55568. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  55569. return {
  55570. id: geometry.id,
  55571. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  55572. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  55573. indices: new Uint32Array(geometry.getIndices() || []),
  55574. };
  55575. };
  55576. return CollisionCoordinatorWorker;
  55577. }());
  55578. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  55579. var CollisionCoordinatorLegacy = /** @class */ (function () {
  55580. function CollisionCoordinatorLegacy() {
  55581. this._scaledPosition = BABYLON.Vector3.Zero();
  55582. this._scaledVelocity = BABYLON.Vector3.Zero();
  55583. this._finalPosition = BABYLON.Vector3.Zero();
  55584. }
  55585. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  55586. position.divideToRef(collider._radius, this._scaledPosition);
  55587. displacement.divideToRef(collider._radius, this._scaledVelocity);
  55588. collider.collidedMesh = null;
  55589. collider._retry = 0;
  55590. collider._initialVelocity = this._scaledVelocity;
  55591. collider._initialPosition = this._scaledPosition;
  55592. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  55593. this._finalPosition.multiplyInPlace(collider._radius);
  55594. //run the callback
  55595. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  55596. };
  55597. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  55598. this._scene = scene;
  55599. };
  55600. CollisionCoordinatorLegacy.prototype.destroy = function () {
  55601. //Legacy need no destruction method.
  55602. };
  55603. //No update in legacy mode
  55604. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  55605. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  55606. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  55607. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  55608. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  55609. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  55610. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  55611. if (excludedMesh === void 0) { excludedMesh = null; }
  55612. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  55613. if (collider._retry >= maximumRetry) {
  55614. finalPosition.copyFrom(position);
  55615. return;
  55616. }
  55617. // Check if this is a mesh else camera or -1
  55618. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  55619. collider._initialize(position, velocity, closeDistance);
  55620. // Check all meshes
  55621. for (var index = 0; index < this._scene.meshes.length; index++) {
  55622. var mesh = this._scene.meshes[index];
  55623. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  55624. mesh._checkCollision(collider);
  55625. }
  55626. }
  55627. if (!collider.collisionFound) {
  55628. position.addToRef(velocity, finalPosition);
  55629. return;
  55630. }
  55631. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  55632. collider._getResponse(position, velocity);
  55633. }
  55634. if (velocity.length() <= closeDistance) {
  55635. finalPosition.copyFrom(position);
  55636. return;
  55637. }
  55638. collider._retry++;
  55639. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  55640. };
  55641. return CollisionCoordinatorLegacy;
  55642. }());
  55643. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  55644. })(BABYLON || (BABYLON = {}));
  55645. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  55646. var BABYLON;
  55647. (function (BABYLON) {
  55648. /**
  55649. * A particle represents one of the element emitted by a particle system.
  55650. * This is mainly define by its coordinates, direction, velocity and age.
  55651. */
  55652. var Particle = /** @class */ (function () {
  55653. /**
  55654. * Creates a new instance Particle
  55655. * @param particleSystem the particle system the particle belongs to
  55656. */
  55657. function Particle(
  55658. /**
  55659. * particleSystem the particle system the particle belongs to.
  55660. */
  55661. particleSystem) {
  55662. this.particleSystem = particleSystem;
  55663. /**
  55664. * The world position of the particle in the scene.
  55665. */
  55666. this.position = BABYLON.Vector3.Zero();
  55667. /**
  55668. * The world direction of the particle in the scene.
  55669. */
  55670. this.direction = BABYLON.Vector3.Zero();
  55671. /**
  55672. * The color of the particle.
  55673. */
  55674. this.color = new BABYLON.Color4(0, 0, 0, 0);
  55675. /**
  55676. * The color change of the particle per step.
  55677. */
  55678. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  55679. /**
  55680. * Defines how long will the life of the particle be.
  55681. */
  55682. this.lifeTime = 1.0;
  55683. /**
  55684. * The current age of the particle.
  55685. */
  55686. this.age = 0;
  55687. /**
  55688. * The current size of the particle.
  55689. */
  55690. this.size = 0;
  55691. /**
  55692. * The current angle of the particle.
  55693. */
  55694. this.angle = 0;
  55695. /**
  55696. * Defines how fast is the angle changing.
  55697. */
  55698. this.angularSpeed = 0;
  55699. /**
  55700. * Defines the cell index used by the particle to be rendered from a sprite.
  55701. */
  55702. this.cellIndex = 0;
  55703. this._currentFrameCounter = 0;
  55704. if (!this.particleSystem.isAnimationSheetEnabled) {
  55705. return;
  55706. }
  55707. this.updateCellInfoFromSystem();
  55708. }
  55709. Particle.prototype.updateCellInfoFromSystem = function () {
  55710. this.cellIndex = this.particleSystem.startSpriteCellID;
  55711. if (this.particleSystem.spriteCellChangeSpeed == 0) {
  55712. this.updateCellIndex = this._updateCellIndexWithSpeedCalculated;
  55713. }
  55714. else {
  55715. this.updateCellIndex = this._updateCellIndexWithCustomSpeed;
  55716. }
  55717. };
  55718. Particle.prototype._updateCellIndexWithSpeedCalculated = function (scaledUpdateSpeed) {
  55719. // (ageOffset / scaledUpdateSpeed) / available cells
  55720. var numberOfScaledUpdatesPerCell = ((this.lifeTime - this.age) / scaledUpdateSpeed) / (this.particleSystem.endSpriteCellID + 1 - this.cellIndex);
  55721. this._currentFrameCounter += scaledUpdateSpeed;
  55722. if (this._currentFrameCounter >= numberOfScaledUpdatesPerCell * scaledUpdateSpeed) {
  55723. this._currentFrameCounter = 0;
  55724. this.cellIndex++;
  55725. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55726. this.cellIndex = this.particleSystem.endSpriteCellID;
  55727. }
  55728. }
  55729. };
  55730. Particle.prototype._updateCellIndexWithCustomSpeed = function () {
  55731. if (this._currentFrameCounter >= this.particleSystem.spriteCellChangeSpeed) {
  55732. this.cellIndex++;
  55733. this._currentFrameCounter = 0;
  55734. if (this.cellIndex > this.particleSystem.endSpriteCellID) {
  55735. if (this.particleSystem.spriteCellLoop) {
  55736. this.cellIndex = this.particleSystem.startSpriteCellID;
  55737. }
  55738. else {
  55739. this.cellIndex = this.particleSystem.endSpriteCellID;
  55740. }
  55741. }
  55742. }
  55743. else {
  55744. this._currentFrameCounter++;
  55745. }
  55746. };
  55747. /**
  55748. * Copy the properties of particle to another one.
  55749. * @param other the particle to copy the information to.
  55750. */
  55751. Particle.prototype.copyTo = function (other) {
  55752. other.position.copyFrom(this.position);
  55753. other.direction.copyFrom(this.direction);
  55754. other.color.copyFrom(this.color);
  55755. other.colorStep.copyFrom(this.colorStep);
  55756. other.lifeTime = this.lifeTime;
  55757. other.age = this.age;
  55758. other.size = this.size;
  55759. other.angle = this.angle;
  55760. other.angularSpeed = this.angularSpeed;
  55761. other.particleSystem = this.particleSystem;
  55762. other.cellIndex = this.cellIndex;
  55763. };
  55764. return Particle;
  55765. }());
  55766. BABYLON.Particle = Particle;
  55767. })(BABYLON || (BABYLON = {}));
  55768. //# sourceMappingURL=babylon.particle.js.map
  55769. var BABYLON;
  55770. (function (BABYLON) {
  55771. /**
  55772. * This represents a particle system in Babylon.
  55773. * 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.
  55774. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55775. * @example https://doc.babylonjs.com/babylon101/particles
  55776. */
  55777. var ParticleSystem = /** @class */ (function () {
  55778. /**
  55779. * Instantiates a particle system.
  55780. * 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.
  55781. * @param name The name of the particle system
  55782. * @param capacity The max number of particles alive at the same time
  55783. * @param scene The scene the particle system belongs to
  55784. * @param customEffect a custom effect used to change the way particles are rendered by default
  55785. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55786. * @param epsilon Offset used to render the particles
  55787. */
  55788. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55789. if (customEffect === void 0) { customEffect = null; }
  55790. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55791. if (epsilon === void 0) { epsilon = 0.01; }
  55792. var _this = this;
  55793. /**
  55794. * List of animations used by the particle system.
  55795. */
  55796. this.animations = [];
  55797. /**
  55798. * The rendering group used by the Particle system to chose when to render.
  55799. */
  55800. this.renderingGroupId = 0;
  55801. /**
  55802. * The emitter represents the Mesh or position we are attaching the particle system to.
  55803. */
  55804. this.emitter = null;
  55805. /**
  55806. * The maximum number of particles to emit per frame
  55807. */
  55808. this.emitRate = 10;
  55809. /**
  55810. * If you want to launch only a few particles at once, that can be done, as well.
  55811. */
  55812. this.manualEmitCount = -1;
  55813. /**
  55814. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55815. */
  55816. this.updateSpeed = 0.01;
  55817. /**
  55818. * The amount of time the particle system is running (depends of the overall update speed).
  55819. */
  55820. this.targetStopDuration = 0;
  55821. /**
  55822. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55823. */
  55824. this.disposeOnStop = false;
  55825. /**
  55826. * Minimum power of emitting particles.
  55827. */
  55828. this.minEmitPower = 1;
  55829. /**
  55830. * Maximum power of emitting particles.
  55831. */
  55832. this.maxEmitPower = 1;
  55833. /**
  55834. * Minimum life time of emitting particles.
  55835. */
  55836. this.minLifeTime = 1;
  55837. /**
  55838. * Maximum life time of emitting particles.
  55839. */
  55840. this.maxLifeTime = 1;
  55841. /**
  55842. * Minimum Size of emitting particles.
  55843. */
  55844. this.minSize = 1;
  55845. /**
  55846. * Maximum Size of emitting particles.
  55847. */
  55848. this.maxSize = 1;
  55849. /**
  55850. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55851. */
  55852. this.minAngularSpeed = 0;
  55853. /**
  55854. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55855. */
  55856. this.maxAngularSpeed = 0;
  55857. /**
  55858. * The layer mask we are rendering the particles through.
  55859. */
  55860. this.layerMask = 0x0FFFFFFF;
  55861. /**
  55862. * This can help using your own shader to render the particle system.
  55863. * The according effect will be created
  55864. */
  55865. this.customShader = null;
  55866. /**
  55867. * By default particle system starts as soon as they are created. This prevents the
  55868. * automatic start to happen and let you decide when to start emitting particles.
  55869. */
  55870. this.preventAutoStart = false;
  55871. /**
  55872. * Callback triggered when the particle animation is ending.
  55873. */
  55874. this.onAnimationEnd = null;
  55875. /**
  55876. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55877. */
  55878. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55879. /**
  55880. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55881. * to override the particles.
  55882. */
  55883. this.forceDepthWrite = false;
  55884. /**
  55885. * You can use gravity if you want to give an orientation to your particles.
  55886. */
  55887. this.gravity = BABYLON.Vector3.Zero();
  55888. /**
  55889. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55890. */
  55891. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55892. /**
  55893. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  55894. */
  55895. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55896. /**
  55897. * Color the particle will have at the end of its lifetime.
  55898. */
  55899. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55900. /**
  55901. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel.
  55902. */
  55903. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55904. /**
  55905. * If using a spritesheet (isAnimationSheetEnabled), defines if the sprite animation should loop between startSpriteCellID and endSpriteCellID or not.
  55906. */
  55907. this.spriteCellLoop = true;
  55908. /**
  55909. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the speed of the sprite loop.
  55910. */
  55911. this.spriteCellChangeSpeed = 0;
  55912. /**
  55913. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the first sprite cell to display.
  55914. */
  55915. this.startSpriteCellID = 0;
  55916. /**
  55917. * If using a spritesheet (isAnimationSheetEnabled) and spriteCellLoop defines the last sprite cell to display.
  55918. */
  55919. this.endSpriteCellID = 0;
  55920. /**
  55921. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use.
  55922. */
  55923. this.spriteCellWidth = 0;
  55924. /**
  55925. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use.
  55926. */
  55927. this.spriteCellHeight = 0;
  55928. /**
  55929. * An event triggered when the system is disposed.
  55930. */
  55931. this.onDisposeObservable = new BABYLON.Observable();
  55932. this._particles = new Array();
  55933. this._stockParticles = new Array();
  55934. this._newPartsExcess = 0;
  55935. this._vertexBuffers = {};
  55936. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55937. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55938. this._scaledDirection = BABYLON.Vector3.Zero();
  55939. this._scaledGravity = BABYLON.Vector3.Zero();
  55940. this._currentRenderId = -1;
  55941. this._started = false;
  55942. this._stopped = false;
  55943. this._actualFrame = 0;
  55944. this._vertexBufferSize = 11;
  55945. // start of sub system methods
  55946. /**
  55947. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55948. * Its lifetime will start back at 0.
  55949. */
  55950. this.recycleParticle = function (particle) {
  55951. var lastParticle = _this._particles.pop();
  55952. if (lastParticle !== particle) {
  55953. lastParticle.copyTo(particle);
  55954. }
  55955. _this._stockParticles.push(lastParticle);
  55956. };
  55957. this._createParticle = function () {
  55958. var particle;
  55959. if (_this._stockParticles.length !== 0) {
  55960. particle = _this._stockParticles.pop();
  55961. particle.age = 0;
  55962. particle.cellIndex = _this.startSpriteCellID;
  55963. }
  55964. else {
  55965. particle = new BABYLON.Particle(_this);
  55966. }
  55967. return particle;
  55968. };
  55969. this._emitFromParticle = function (particle) {
  55970. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55971. return;
  55972. }
  55973. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55974. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55975. subSystem._rootParticleSystem = _this;
  55976. _this.activeSubSystems.push(subSystem);
  55977. subSystem.start();
  55978. };
  55979. this._appendParticleVertexes = null;
  55980. this.id = name;
  55981. this.name = name;
  55982. this._capacity = capacity;
  55983. this._epsilon = epsilon;
  55984. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55985. if (isAnimationSheetEnabled) {
  55986. this._vertexBufferSize = 12;
  55987. }
  55988. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55989. this._customEffect = customEffect;
  55990. scene.particleSystems.push(this);
  55991. this._createIndexBuffer();
  55992. // 11 floats per particle (x, y, z, r, g, b, a, angle, size, offsetX, offsetY) + 1 filler
  55993. this._vertexData = new Float32Array(capacity * this._vertexBufferSize * 4);
  55994. this._vertexBuffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, this._vertexBufferSize);
  55995. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 3);
  55996. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 3, 4);
  55997. var options = this._vertexBuffer.createVertexBuffer("options", 7, 4);
  55998. if (this._isAnimationSheetEnabled) {
  55999. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", 11, 1);
  56000. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  56001. }
  56002. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  56003. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  56004. this._vertexBuffers["options"] = options;
  56005. // Default emitter type
  56006. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  56007. this.updateFunction = function (particles) {
  56008. for (var index = 0; index < particles.length; index++) {
  56009. var particle = particles[index];
  56010. particle.age += _this._scaledUpdateSpeed;
  56011. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  56012. _this._emitFromParticle(particle);
  56013. _this.recycleParticle(particle);
  56014. index--;
  56015. continue;
  56016. }
  56017. else {
  56018. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  56019. particle.color.addInPlace(_this._scaledColorStep);
  56020. if (particle.color.a < 0)
  56021. particle.color.a = 0;
  56022. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  56023. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  56024. particle.position.addInPlace(_this._scaledDirection);
  56025. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  56026. particle.direction.addInPlace(_this._scaledGravity);
  56027. if (_this._isAnimationSheetEnabled) {
  56028. particle.updateCellIndex(_this._scaledUpdateSpeed);
  56029. }
  56030. }
  56031. }
  56032. };
  56033. }
  56034. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  56035. /**
  56036. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56037. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56038. */
  56039. get: function () {
  56040. if (this.particleEmitterType.direction1) {
  56041. return this.particleEmitterType.direction1;
  56042. }
  56043. return BABYLON.Vector3.Zero();
  56044. },
  56045. set: function (value) {
  56046. if (this.particleEmitterType.direction1) {
  56047. this.particleEmitterType.direction1 = value;
  56048. }
  56049. },
  56050. enumerable: true,
  56051. configurable: true
  56052. });
  56053. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  56054. /**
  56055. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56056. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56057. */
  56058. get: function () {
  56059. if (this.particleEmitterType.direction2) {
  56060. return this.particleEmitterType.direction2;
  56061. }
  56062. return BABYLON.Vector3.Zero();
  56063. },
  56064. set: function (value) {
  56065. if (this.particleEmitterType.direction2) {
  56066. this.particleEmitterType.direction2 = value;
  56067. }
  56068. },
  56069. enumerable: true,
  56070. configurable: true
  56071. });
  56072. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  56073. /**
  56074. * 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.
  56075. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56076. */
  56077. get: function () {
  56078. if (this.particleEmitterType.minEmitBox) {
  56079. return this.particleEmitterType.minEmitBox;
  56080. }
  56081. return BABYLON.Vector3.Zero();
  56082. },
  56083. set: function (value) {
  56084. if (this.particleEmitterType.minEmitBox) {
  56085. this.particleEmitterType.minEmitBox = value;
  56086. }
  56087. },
  56088. enumerable: true,
  56089. configurable: true
  56090. });
  56091. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  56092. /**
  56093. * 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.
  56094. * This only works when particleEmitterTyps is a BoxParticleEmitter
  56095. */
  56096. get: function () {
  56097. if (this.particleEmitterType.maxEmitBox) {
  56098. return this.particleEmitterType.maxEmitBox;
  56099. }
  56100. return BABYLON.Vector3.Zero();
  56101. },
  56102. set: function (value) {
  56103. if (this.particleEmitterType.maxEmitBox) {
  56104. this.particleEmitterType.maxEmitBox = value;
  56105. }
  56106. },
  56107. enumerable: true,
  56108. configurable: true
  56109. });
  56110. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  56111. /**
  56112. * Sets a callback that will be triggered when the system is disposed.
  56113. */
  56114. set: function (callback) {
  56115. if (this._onDisposeObserver) {
  56116. this.onDisposeObservable.remove(this._onDisposeObserver);
  56117. }
  56118. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  56119. },
  56120. enumerable: true,
  56121. configurable: true
  56122. });
  56123. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  56124. /**
  56125. * Gets wether an animation sprite sheet is enabled or not on the particle system.
  56126. */
  56127. get: function () {
  56128. return this._isAnimationSheetEnabled;
  56129. },
  56130. enumerable: true,
  56131. configurable: true
  56132. });
  56133. Object.defineProperty(ParticleSystem.prototype, "particles", {
  56134. //end of Sub-emitter
  56135. /**
  56136. * Gets the current list of active particles
  56137. */
  56138. get: function () {
  56139. return this._particles;
  56140. },
  56141. enumerable: true,
  56142. configurable: true
  56143. });
  56144. /**
  56145. * Returns the string "ParticleSystem"
  56146. * @returns a string containing the class name
  56147. */
  56148. ParticleSystem.prototype.getClassName = function () {
  56149. return "ParticleSystem";
  56150. };
  56151. ParticleSystem.prototype._createIndexBuffer = function () {
  56152. var indices = [];
  56153. var index = 0;
  56154. for (var count = 0; count < this._capacity; count++) {
  56155. indices.push(index);
  56156. indices.push(index + 1);
  56157. indices.push(index + 2);
  56158. indices.push(index);
  56159. indices.push(index + 2);
  56160. indices.push(index + 3);
  56161. index += 4;
  56162. }
  56163. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  56164. };
  56165. /**
  56166. * Gets the maximum number of particles active at the same time.
  56167. * @returns The max number of active particles.
  56168. */
  56169. ParticleSystem.prototype.getCapacity = function () {
  56170. return this._capacity;
  56171. };
  56172. /**
  56173. * Gets Wether there are still active particles in the system.
  56174. * @returns True if it is alive, otherwise false.
  56175. */
  56176. ParticleSystem.prototype.isAlive = function () {
  56177. return this._alive;
  56178. };
  56179. /**
  56180. * Gets Wether the system has been started.
  56181. * @returns True if it has been started, otherwise false.
  56182. */
  56183. ParticleSystem.prototype.isStarted = function () {
  56184. return this._started;
  56185. };
  56186. /**
  56187. * Starts the particle system and begins to emit.
  56188. */
  56189. ParticleSystem.prototype.start = function () {
  56190. this._started = true;
  56191. this._stopped = false;
  56192. this._actualFrame = 0;
  56193. if (this.subEmitters && this.subEmitters.length != 0) {
  56194. this.activeSubSystems = new Array();
  56195. }
  56196. };
  56197. /**
  56198. * Stops the particle system.
  56199. * @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.
  56200. */
  56201. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  56202. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  56203. this._stopped = true;
  56204. if (stopSubEmitters) {
  56205. this._stopSubEmitters();
  56206. }
  56207. };
  56208. // animation sheet
  56209. /**
  56210. * Remove all active particles
  56211. */
  56212. ParticleSystem.prototype.reset = function () {
  56213. this._stockParticles = [];
  56214. this._particles = [];
  56215. };
  56216. /**
  56217. * @hidden (for internal use only)
  56218. */
  56219. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  56220. var offset = index * this._vertexBufferSize;
  56221. this._vertexData[offset] = particle.position.x;
  56222. this._vertexData[offset + 1] = particle.position.y;
  56223. this._vertexData[offset + 2] = particle.position.z;
  56224. this._vertexData[offset + 3] = particle.color.r;
  56225. this._vertexData[offset + 4] = particle.color.g;
  56226. this._vertexData[offset + 5] = particle.color.b;
  56227. this._vertexData[offset + 6] = particle.color.a;
  56228. this._vertexData[offset + 7] = particle.angle;
  56229. this._vertexData[offset + 8] = particle.size;
  56230. this._vertexData[offset + 9] = offsetX;
  56231. this._vertexData[offset + 10] = offsetY;
  56232. };
  56233. /**
  56234. * @hidden (for internal use only)
  56235. */
  56236. ParticleSystem.prototype._appendParticleVertexWithAnimation = function (index, particle, offsetX, offsetY) {
  56237. if (offsetX === 0)
  56238. offsetX = this._epsilon;
  56239. else if (offsetX === 1)
  56240. offsetX = 1 - this._epsilon;
  56241. if (offsetY === 0)
  56242. offsetY = this._epsilon;
  56243. else if (offsetY === 1)
  56244. offsetY = 1 - this._epsilon;
  56245. var offset = index * this._vertexBufferSize;
  56246. this._vertexData[offset] = particle.position.x;
  56247. this._vertexData[offset + 1] = particle.position.y;
  56248. this._vertexData[offset + 2] = particle.position.z;
  56249. this._vertexData[offset + 3] = particle.color.r;
  56250. this._vertexData[offset + 4] = particle.color.g;
  56251. this._vertexData[offset + 5] = particle.color.b;
  56252. this._vertexData[offset + 6] = particle.color.a;
  56253. this._vertexData[offset + 7] = particle.angle;
  56254. this._vertexData[offset + 8] = particle.size;
  56255. this._vertexData[offset + 9] = offsetX;
  56256. this._vertexData[offset + 10] = offsetY;
  56257. this._vertexData[offset + 11] = particle.cellIndex;
  56258. };
  56259. ParticleSystem.prototype._stopSubEmitters = function () {
  56260. if (!this.activeSubSystems) {
  56261. return;
  56262. }
  56263. this.activeSubSystems.forEach(function (subSystem) {
  56264. subSystem.stop(true);
  56265. });
  56266. this.activeSubSystems = new Array();
  56267. };
  56268. ParticleSystem.prototype._removeFromRoot = function () {
  56269. if (!this._rootParticleSystem) {
  56270. return;
  56271. }
  56272. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  56273. if (index !== -1) {
  56274. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  56275. }
  56276. };
  56277. // end of sub system methods
  56278. ParticleSystem.prototype._update = function (newParticles) {
  56279. // Update current
  56280. this._alive = this._particles.length > 0;
  56281. this.updateFunction(this._particles);
  56282. // Add new ones
  56283. var worldMatrix;
  56284. if (this.emitter.position) {
  56285. var emitterMesh = this.emitter;
  56286. worldMatrix = emitterMesh.getWorldMatrix();
  56287. }
  56288. else {
  56289. var emitterPosition = this.emitter;
  56290. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  56291. }
  56292. var particle;
  56293. for (var index = 0; index < newParticles; index++) {
  56294. if (this._particles.length === this._capacity) {
  56295. break;
  56296. }
  56297. particle = this._createParticle();
  56298. this._particles.push(particle);
  56299. var emitPower = BABYLON.Scalar.RandomRange(this.minEmitPower, this.maxEmitPower);
  56300. if (this.startPositionFunction) {
  56301. this.startPositionFunction(worldMatrix, particle.position, particle);
  56302. }
  56303. else {
  56304. this.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  56305. }
  56306. if (this.startDirectionFunction) {
  56307. this.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56308. }
  56309. else {
  56310. this.particleEmitterType.startDirectionFunction(emitPower, worldMatrix, particle.direction, particle);
  56311. }
  56312. particle.lifeTime = BABYLON.Scalar.RandomRange(this.minLifeTime, this.maxLifeTime);
  56313. particle.size = BABYLON.Scalar.RandomRange(this.minSize, this.maxSize);
  56314. particle.angularSpeed = BABYLON.Scalar.RandomRange(this.minAngularSpeed, this.maxAngularSpeed);
  56315. var step = BABYLON.Scalar.RandomRange(0, 1.0);
  56316. BABYLON.Color4.LerpToRef(this.color1, this.color2, step, particle.color);
  56317. this.colorDead.subtractToRef(particle.color, this._colorDiff);
  56318. this._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  56319. }
  56320. };
  56321. ParticleSystem.prototype._getEffect = function () {
  56322. if (this._customEffect) {
  56323. return this._customEffect;
  56324. }
  56325. ;
  56326. var defines = [];
  56327. if (this._scene.clipPlane) {
  56328. defines.push("#define CLIPPLANE");
  56329. }
  56330. if (this._isAnimationSheetEnabled) {
  56331. defines.push("#define ANIMATESHEET");
  56332. }
  56333. // Effect
  56334. var join = defines.join("\n");
  56335. if (this._cachedDefines !== join) {
  56336. this._cachedDefines = join;
  56337. var attributesNamesOrOptions;
  56338. var effectCreationOption;
  56339. if (this._isAnimationSheetEnabled) {
  56340. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options", "cellIndex"];
  56341. effectCreationOption = ["invView", "view", "projection", "particlesInfos", "vClipPlane", "textureMask"];
  56342. }
  56343. else {
  56344. attributesNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "options"];
  56345. effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask"];
  56346. }
  56347. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56348. }
  56349. return this._effect;
  56350. };
  56351. /**
  56352. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56353. */
  56354. ParticleSystem.prototype.animate = function () {
  56355. if (!this._started)
  56356. return;
  56357. var effect = this._getEffect();
  56358. // Check
  56359. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56360. return;
  56361. if (this._currentRenderId === this._scene.getRenderId()) {
  56362. return;
  56363. }
  56364. this._currentRenderId = this._scene.getRenderId();
  56365. this._scaledUpdateSpeed = this.updateSpeed * this._scene.getAnimationRatio();
  56366. // determine the number of particles we need to create
  56367. var newParticles;
  56368. if (this.manualEmitCount > -1) {
  56369. newParticles = this.manualEmitCount;
  56370. this._newPartsExcess = 0;
  56371. this.manualEmitCount = 0;
  56372. }
  56373. else {
  56374. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56375. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56376. }
  56377. if (this._newPartsExcess > 1.0) {
  56378. newParticles += this._newPartsExcess >> 0;
  56379. this._newPartsExcess -= this._newPartsExcess >> 0;
  56380. }
  56381. this._alive = false;
  56382. if (!this._stopped) {
  56383. this._actualFrame += this._scaledUpdateSpeed;
  56384. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56385. this.stop();
  56386. }
  56387. else {
  56388. newParticles = 0;
  56389. }
  56390. this._update(newParticles);
  56391. // Stopped?
  56392. if (this._stopped) {
  56393. if (!this._alive) {
  56394. this._started = false;
  56395. if (this.onAnimationEnd) {
  56396. this.onAnimationEnd();
  56397. }
  56398. if (this.disposeOnStop) {
  56399. this._scene._toBeDisposed.push(this);
  56400. }
  56401. }
  56402. }
  56403. // Animation sheet
  56404. if (this._isAnimationSheetEnabled) {
  56405. this._appendParticleVertexes = this._appenedParticleVertexesWithSheet;
  56406. }
  56407. else {
  56408. this._appendParticleVertexes = this._appenedParticleVertexesNoSheet;
  56409. }
  56410. // Update VBO
  56411. var offset = 0;
  56412. for (var index = 0; index < this._particles.length; index++) {
  56413. var particle = this._particles[index];
  56414. this._appendParticleVertexes(offset, particle);
  56415. offset += 4;
  56416. }
  56417. if (this._vertexBuffer) {
  56418. this._vertexBuffer.update(this._vertexData);
  56419. }
  56420. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56421. this.stop();
  56422. }
  56423. };
  56424. ParticleSystem.prototype._appenedParticleVertexesWithSheet = function (offset, particle) {
  56425. this._appendParticleVertexWithAnimation(offset++, particle, 0, 0);
  56426. this._appendParticleVertexWithAnimation(offset++, particle, 1, 0);
  56427. this._appendParticleVertexWithAnimation(offset++, particle, 1, 1);
  56428. this._appendParticleVertexWithAnimation(offset++, particle, 0, 1);
  56429. };
  56430. ParticleSystem.prototype._appenedParticleVertexesNoSheet = function (offset, particle) {
  56431. this._appendParticleVertex(offset++, particle, 0, 0);
  56432. this._appendParticleVertex(offset++, particle, 1, 0);
  56433. this._appendParticleVertex(offset++, particle, 1, 1);
  56434. this._appendParticleVertex(offset++, particle, 0, 1);
  56435. };
  56436. /**
  56437. * Rebuilds the particle system.
  56438. */
  56439. ParticleSystem.prototype.rebuild = function () {
  56440. this._createIndexBuffer();
  56441. if (this._vertexBuffer) {
  56442. this._vertexBuffer._rebuild();
  56443. }
  56444. };
  56445. /**
  56446. * Is this system ready to be used/rendered
  56447. * @return true if the system is ready
  56448. */
  56449. ParticleSystem.prototype.isReady = function () {
  56450. var effect = this._getEffect();
  56451. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56452. return false;
  56453. }
  56454. return true;
  56455. };
  56456. /**
  56457. * Renders the particle system in its current state.
  56458. * @returns the current number of particles
  56459. */
  56460. ParticleSystem.prototype.render = function () {
  56461. var effect = this._getEffect();
  56462. // Check
  56463. if (!this.isReady() || !this._particles.length) {
  56464. return 0;
  56465. }
  56466. var engine = this._scene.getEngine();
  56467. // Render
  56468. engine.enableEffect(effect);
  56469. engine.setState(false);
  56470. var viewMatrix = this._scene.getViewMatrix();
  56471. effect.setTexture("diffuseSampler", this.particleTexture);
  56472. effect.setMatrix("view", viewMatrix);
  56473. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56474. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56475. var baseSize = this.particleTexture.getBaseSize();
  56476. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56477. }
  56478. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56479. if (this._scene.clipPlane) {
  56480. var clipPlane = this._scene.clipPlane;
  56481. var invView = viewMatrix.clone();
  56482. invView.invert();
  56483. effect.setMatrix("invView", invView);
  56484. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56485. }
  56486. // VBOs
  56487. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56488. // Draw order
  56489. if (this.blendMode === ParticleSystem.BLENDMODE_ONEONE) {
  56490. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56491. }
  56492. else {
  56493. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56494. }
  56495. if (this.forceDepthWrite) {
  56496. engine.setDepthWrite(true);
  56497. }
  56498. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56499. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56500. return this._particles.length;
  56501. };
  56502. /**
  56503. * Disposes the particle system and free the associated resources
  56504. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56505. */
  56506. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56507. if (disposeTexture === void 0) { disposeTexture = true; }
  56508. if (this._vertexBuffer) {
  56509. this._vertexBuffer.dispose();
  56510. this._vertexBuffer = null;
  56511. }
  56512. if (this._indexBuffer) {
  56513. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56514. this._indexBuffer = null;
  56515. }
  56516. if (disposeTexture && this.particleTexture) {
  56517. this.particleTexture.dispose();
  56518. this.particleTexture = null;
  56519. }
  56520. this._removeFromRoot();
  56521. // Remove from scene
  56522. var index = this._scene.particleSystems.indexOf(this);
  56523. if (index > -1) {
  56524. this._scene.particleSystems.splice(index, 1);
  56525. }
  56526. // Callback
  56527. this.onDisposeObservable.notifyObservers(this);
  56528. this.onDisposeObservable.clear();
  56529. };
  56530. /**
  56531. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56532. * @param radius The radius of the sphere to emit from
  56533. * @returns the emitter
  56534. */
  56535. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56536. if (radius === void 0) { radius = 1; }
  56537. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56538. this.particleEmitterType = particleEmitter;
  56539. return particleEmitter;
  56540. };
  56541. /**
  56542. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56543. * @param radius The radius of the sphere to emit from
  56544. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56545. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56546. * @returns the emitter
  56547. */
  56548. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56549. if (radius === void 0) { radius = 1; }
  56550. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56551. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56552. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56553. this.particleEmitterType = particleEmitter;
  56554. return particleEmitter;
  56555. };
  56556. /**
  56557. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56558. * @param radius The radius of the cone to emit from
  56559. * @param angle The base angle of the cone
  56560. * @returns the emitter
  56561. */
  56562. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56563. if (radius === void 0) { radius = 1; }
  56564. if (angle === void 0) { angle = Math.PI / 4; }
  56565. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56566. this.particleEmitterType = particleEmitter;
  56567. return particleEmitter;
  56568. };
  56569. // 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.
  56570. /**
  56571. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56572. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56573. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56574. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56575. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56576. * @returns the emitter
  56577. */
  56578. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56579. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56580. this.particleEmitterType = particleEmitter;
  56581. this.direction1 = direction1;
  56582. this.direction2 = direction2;
  56583. this.minEmitBox = minEmitBox;
  56584. this.maxEmitBox = maxEmitBox;
  56585. return particleEmitter;
  56586. };
  56587. // Clone
  56588. /**
  56589. * Clones the particle system.
  56590. * @param name The name of the cloned object
  56591. * @param newEmitter The new emitter to use
  56592. * @returns the cloned particle system
  56593. */
  56594. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56595. var custom = null;
  56596. var program = null;
  56597. if (this.customShader != null) {
  56598. program = this.customShader;
  56599. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56600. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56601. }
  56602. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56603. result.customShader = program;
  56604. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56605. if (newEmitter === undefined) {
  56606. newEmitter = this.emitter;
  56607. }
  56608. result.emitter = newEmitter;
  56609. if (this.particleTexture) {
  56610. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56611. }
  56612. if (!this.preventAutoStart) {
  56613. result.start();
  56614. }
  56615. return result;
  56616. };
  56617. /**
  56618. * Serializes the particle system to a JSON object.
  56619. * @returns the JSON object
  56620. */
  56621. ParticleSystem.prototype.serialize = function () {
  56622. var serializationObject = {};
  56623. serializationObject.name = this.name;
  56624. serializationObject.id = this.id;
  56625. // Emitter
  56626. if (this.emitter.position) {
  56627. var emitterMesh = this.emitter;
  56628. serializationObject.emitterId = emitterMesh.id;
  56629. }
  56630. else {
  56631. var emitterPosition = this.emitter;
  56632. serializationObject.emitter = emitterPosition.asArray();
  56633. }
  56634. serializationObject.capacity = this.getCapacity();
  56635. if (this.particleTexture) {
  56636. serializationObject.textureName = this.particleTexture.name;
  56637. }
  56638. // Animations
  56639. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  56640. // Particle system
  56641. serializationObject.minAngularSpeed = this.minAngularSpeed;
  56642. serializationObject.maxAngularSpeed = this.maxAngularSpeed;
  56643. serializationObject.minSize = this.minSize;
  56644. serializationObject.maxSize = this.maxSize;
  56645. serializationObject.minEmitPower = this.minEmitPower;
  56646. serializationObject.maxEmitPower = this.maxEmitPower;
  56647. serializationObject.minLifeTime = this.minLifeTime;
  56648. serializationObject.maxLifeTime = this.maxLifeTime;
  56649. serializationObject.emitRate = this.emitRate;
  56650. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56651. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56652. serializationObject.gravity = this.gravity.asArray();
  56653. serializationObject.direction1 = this.direction1.asArray();
  56654. serializationObject.direction2 = this.direction2.asArray();
  56655. serializationObject.color1 = this.color1.asArray();
  56656. serializationObject.color2 = this.color2.asArray();
  56657. serializationObject.colorDead = this.colorDead.asArray();
  56658. serializationObject.updateSpeed = this.updateSpeed;
  56659. serializationObject.targetStopDuration = this.targetStopDuration;
  56660. serializationObject.textureMask = this.textureMask.asArray();
  56661. serializationObject.blendMode = this.blendMode;
  56662. serializationObject.customShader = this.customShader;
  56663. serializationObject.preventAutoStart = this.preventAutoStart;
  56664. serializationObject.startSpriteCellID = this.startSpriteCellID;
  56665. serializationObject.endSpriteCellID = this.endSpriteCellID;
  56666. serializationObject.spriteCellLoop = this.spriteCellLoop;
  56667. serializationObject.spriteCellChangeSpeed = this.spriteCellChangeSpeed;
  56668. serializationObject.spriteCellWidth = this.spriteCellWidth;
  56669. serializationObject.spriteCellHeight = this.spriteCellHeight;
  56670. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56671. // Emitter
  56672. if (this.particleEmitterType) {
  56673. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  56674. }
  56675. return serializationObject;
  56676. };
  56677. /**
  56678. * Parses a JSON object to create a particle system.
  56679. * @param parsedParticleSystem The JSON object to parse
  56680. * @param scene The scene to create the particle system in
  56681. * @param rootUrl The root url to use to load external dependencies like texture
  56682. * @returns the Parsed particle system
  56683. */
  56684. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56685. var name = parsedParticleSystem.name;
  56686. var custom = null;
  56687. var program = null;
  56688. if (parsedParticleSystem.customShader) {
  56689. program = parsedParticleSystem.customShader;
  56690. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56691. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56692. }
  56693. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56694. particleSystem.customShader = program;
  56695. if (parsedParticleSystem.id) {
  56696. particleSystem.id = parsedParticleSystem.id;
  56697. }
  56698. // Auto start
  56699. if (parsedParticleSystem.preventAutoStart) {
  56700. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56701. }
  56702. // Texture
  56703. if (parsedParticleSystem.textureName) {
  56704. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56705. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56706. }
  56707. // Emitter
  56708. if (parsedParticleSystem.emitterId) {
  56709. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56710. }
  56711. else {
  56712. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56713. }
  56714. // Animations
  56715. if (parsedParticleSystem.animations) {
  56716. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56717. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56718. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56719. }
  56720. }
  56721. if (parsedParticleSystem.autoAnimate) {
  56722. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56723. }
  56724. // Particle system
  56725. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56726. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56727. particleSystem.minSize = parsedParticleSystem.minSize;
  56728. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56729. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56730. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56731. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56732. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56733. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56734. particleSystem.minEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.minEmitBox);
  56735. particleSystem.maxEmitBox = BABYLON.Vector3.FromArray(parsedParticleSystem.maxEmitBox);
  56736. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56737. particleSystem.direction1 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction1);
  56738. particleSystem.direction2 = BABYLON.Vector3.FromArray(parsedParticleSystem.direction2);
  56739. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56740. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56741. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56742. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56743. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56744. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56745. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56746. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56747. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56748. particleSystem.spriteCellLoop = parsedParticleSystem.spriteCellLoop;
  56749. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56750. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56751. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56752. if (!particleSystem.preventAutoStart) {
  56753. particleSystem.start();
  56754. }
  56755. return particleSystem;
  56756. };
  56757. /**
  56758. * Source color is added to the destination color without alpha affecting the result.
  56759. */
  56760. ParticleSystem.BLENDMODE_ONEONE = 0;
  56761. /**
  56762. * Blend current color and particle color using particle’s alpha.
  56763. */
  56764. ParticleSystem.BLENDMODE_STANDARD = 1;
  56765. return ParticleSystem;
  56766. }());
  56767. BABYLON.ParticleSystem = ParticleSystem;
  56768. })(BABYLON || (BABYLON = {}));
  56769. //# sourceMappingURL=babylon.particleSystem.js.map
  56770. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56771. var BABYLON;
  56772. (function (BABYLON) {
  56773. /**
  56774. * Particle emitter emitting particles from the inside of a box.
  56775. * It emits the particles randomly between 2 given directions.
  56776. */
  56777. var BoxParticleEmitter = /** @class */ (function () {
  56778. /**
  56779. * Creates a new instance BoxParticleEmitter
  56780. */
  56781. function BoxParticleEmitter() {
  56782. /**
  56783. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56784. */
  56785. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56786. /**
  56787. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56788. */
  56789. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56790. /**
  56791. * 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.
  56792. */
  56793. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56794. /**
  56795. * 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.
  56796. */
  56797. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56798. }
  56799. /**
  56800. * Called by the particle System when the direction is computed for the created particle.
  56801. * @param emitPower is the power of the particle (speed)
  56802. * @param worldMatrix is the world matrix of the particle system
  56803. * @param directionToUpdate is the direction vector to update with the result
  56804. * @param particle is the particle we are computed the direction for
  56805. */
  56806. BoxParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56807. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56808. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56809. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56810. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  56811. };
  56812. /**
  56813. * Called by the particle System when the position is computed for the created particle.
  56814. * @param worldMatrix is the world matrix of the particle system
  56815. * @param positionToUpdate is the position vector to update with the result
  56816. * @param particle is the particle we are computed the position for
  56817. */
  56818. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56819. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56820. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56821. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56822. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56823. };
  56824. /**
  56825. * Clones the current emitter and returns a copy of it
  56826. * @returns the new emitter
  56827. */
  56828. BoxParticleEmitter.prototype.clone = function () {
  56829. var newOne = new BoxParticleEmitter();
  56830. BABYLON.Tools.DeepCopy(this, newOne);
  56831. return newOne;
  56832. };
  56833. /**
  56834. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56835. * @param effect defines the update shader
  56836. */
  56837. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56838. effect.setVector3("direction1", this.direction1);
  56839. effect.setVector3("direction2", this.direction2);
  56840. effect.setVector3("minEmitBox", this.minEmitBox);
  56841. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56842. };
  56843. /**
  56844. * Returns a string to use to update the GPU particles update shader
  56845. * @returns a string containng the defines string
  56846. */
  56847. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56848. return "#define BOXEMITTER";
  56849. };
  56850. /**
  56851. * Returns the string "BoxEmitter"
  56852. * @returns a string containing the class name
  56853. */
  56854. BoxParticleEmitter.prototype.getClassName = function () {
  56855. return "BoxEmitter";
  56856. };
  56857. /**
  56858. * Serializes the particle system to a JSON object.
  56859. * @returns the JSON object
  56860. */
  56861. BoxParticleEmitter.prototype.serialize = function () {
  56862. var serializationObject = {};
  56863. serializationObject.type = this.getClassName();
  56864. serializationObject.direction1 = this.direction1.asArray();
  56865. serializationObject.direction2 = this.direction2.asArray();
  56866. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56867. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56868. return serializationObject;
  56869. };
  56870. /**
  56871. * Parse properties from a JSON object
  56872. * @param serializationObject defines the JSON object
  56873. */
  56874. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56875. this.direction1.copyFrom(serializationObject.direction1);
  56876. this.direction2.copyFrom(serializationObject.direction2);
  56877. this.minEmitBox.copyFrom(serializationObject.minEmitBox);
  56878. this.maxEmitBox.copyFrom(serializationObject.maxEmitBox);
  56879. };
  56880. return BoxParticleEmitter;
  56881. }());
  56882. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56883. })(BABYLON || (BABYLON = {}));
  56884. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56885. var BABYLON;
  56886. (function (BABYLON) {
  56887. /**
  56888. * Particle emitter emitting particles from the inside of a cone.
  56889. * It emits the particles alongside the cone volume from the base to the particle.
  56890. * The emission direction might be randomized.
  56891. */
  56892. var ConeParticleEmitter = /** @class */ (function () {
  56893. /**
  56894. * Creates a new instance ConeParticleEmitter
  56895. * @param radius the radius of the emission cone (1 by default)
  56896. * @param angles the cone base angle (PI by default)
  56897. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56898. */
  56899. function ConeParticleEmitter(radius,
  56900. /**
  56901. * The radius of the emission cone.
  56902. */
  56903. angle,
  56904. /**
  56905. * The cone base angle.
  56906. */
  56907. directionRandomizer) {
  56908. if (radius === void 0) { radius = 1; }
  56909. if (angle === void 0) { angle = Math.PI; }
  56910. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56911. this.angle = angle;
  56912. this.directionRandomizer = directionRandomizer;
  56913. this.radius = radius;
  56914. }
  56915. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56916. /**
  56917. * Gets the radius of the emission cone.
  56918. */
  56919. get: function () {
  56920. return this._radius;
  56921. },
  56922. /**
  56923. * Sets the radius of the emission cone.
  56924. */
  56925. set: function (value) {
  56926. this._radius = value;
  56927. if (this.angle !== 0) {
  56928. this._height = value / Math.tan(this.angle / 2);
  56929. }
  56930. else {
  56931. this._height = 1;
  56932. }
  56933. },
  56934. enumerable: true,
  56935. configurable: true
  56936. });
  56937. /**
  56938. * Called by the particle System when the direction is computed for the created particle.
  56939. * @param emitPower is the power of the particle (speed)
  56940. * @param worldMatrix is the world matrix of the particle system
  56941. * @param directionToUpdate is the direction vector to update with the result
  56942. * @param particle is the particle we are computed the direction for
  56943. */
  56944. ConeParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  56945. if (this.angle === 0) {
  56946. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, emitPower, 0, worldMatrix, directionToUpdate);
  56947. }
  56948. else {
  56949. // measure the direction Vector from the emitter to the particle.
  56950. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56951. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56952. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56953. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56954. direction.x += randX;
  56955. direction.y += randY;
  56956. direction.z += randZ;
  56957. direction.normalize();
  56958. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  56959. }
  56960. };
  56961. /**
  56962. * Called by the particle System when the position is computed for the created particle.
  56963. * @param worldMatrix is the world matrix of the particle system
  56964. * @param positionToUpdate is the position vector to update with the result
  56965. * @param particle is the particle we are computed the position for
  56966. */
  56967. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56968. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56969. var h = BABYLON.Scalar.RandomRange(0, 1);
  56970. // Better distribution in a cone at normal angles.
  56971. h = 1 - h * h;
  56972. var radius = BABYLON.Scalar.RandomRange(0, this._radius);
  56973. radius = radius * h;
  56974. var randX = radius * Math.sin(s);
  56975. var randZ = radius * Math.cos(s);
  56976. var randY = h * this._height;
  56977. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56978. };
  56979. /**
  56980. * Clones the current emitter and returns a copy of it
  56981. * @returns the new emitter
  56982. */
  56983. ConeParticleEmitter.prototype.clone = function () {
  56984. var newOne = new ConeParticleEmitter(this.radius, this.angle, this.directionRandomizer);
  56985. BABYLON.Tools.DeepCopy(this, newOne);
  56986. return newOne;
  56987. };
  56988. /**
  56989. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56990. * @param effect defines the update shader
  56991. */
  56992. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56993. effect.setFloat("radius", this.radius);
  56994. effect.setFloat("angle", this.angle);
  56995. effect.setFloat("height", this._height);
  56996. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56997. };
  56998. /**
  56999. * Returns a string to use to update the GPU particles update shader
  57000. * @returns a string containng the defines string
  57001. */
  57002. ConeParticleEmitter.prototype.getEffectDefines = function () {
  57003. return "#define CONEEMITTER";
  57004. };
  57005. /**
  57006. * Returns the string "BoxEmitter"
  57007. * @returns a string containing the class name
  57008. */
  57009. ConeParticleEmitter.prototype.getClassName = function () {
  57010. return "ConeEmitter";
  57011. };
  57012. /**
  57013. * Serializes the particle system to a JSON object.
  57014. * @returns the JSON object
  57015. */
  57016. ConeParticleEmitter.prototype.serialize = function () {
  57017. var serializationObject = {};
  57018. serializationObject.type = this.getClassName();
  57019. serializationObject.radius = this.radius;
  57020. serializationObject.angle = this.angle;
  57021. serializationObject.directionRandomizer = this.directionRandomizer;
  57022. return serializationObject;
  57023. };
  57024. /**
  57025. * Parse properties from a JSON object
  57026. * @param serializationObject defines the JSON object
  57027. */
  57028. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  57029. this.radius = serializationObject.radius;
  57030. this.angle = serializationObject.angle;
  57031. this.directionRandomizer = serializationObject.directionRandomizer;
  57032. };
  57033. return ConeParticleEmitter;
  57034. }());
  57035. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  57036. })(BABYLON || (BABYLON = {}));
  57037. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  57038. var BABYLON;
  57039. (function (BABYLON) {
  57040. /**
  57041. * Particle emitter emitting particles from the inside of a sphere.
  57042. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  57043. */
  57044. var SphereParticleEmitter = /** @class */ (function () {
  57045. /**
  57046. * Creates a new instance SphereParticleEmitter
  57047. * @param radius the radius of the emission sphere (1 by default)
  57048. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  57049. */
  57050. function SphereParticleEmitter(
  57051. /**
  57052. * The radius of the emission sphere.
  57053. */
  57054. radius,
  57055. /**
  57056. * How much to randomize the particle direction [0-1].
  57057. */
  57058. directionRandomizer) {
  57059. if (radius === void 0) { radius = 1; }
  57060. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  57061. this.radius = radius;
  57062. this.directionRandomizer = directionRandomizer;
  57063. }
  57064. /**
  57065. * Called by the particle System when the direction is computed for the created particle.
  57066. * @param emitPower is the power of the particle (speed)
  57067. * @param worldMatrix is the world matrix of the particle system
  57068. * @param directionToUpdate is the direction vector to update with the result
  57069. * @param particle is the particle we are computed the direction for
  57070. */
  57071. SphereParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57072. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  57073. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57074. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57075. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  57076. direction.x += randX;
  57077. direction.y += randY;
  57078. direction.z += randZ;
  57079. direction.normalize();
  57080. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x * emitPower, direction.y * emitPower, direction.z * emitPower, worldMatrix, directionToUpdate);
  57081. };
  57082. /**
  57083. * Called by the particle System when the position is computed for the created particle.
  57084. * @param worldMatrix is the world matrix of the particle system
  57085. * @param positionToUpdate is the position vector to update with the result
  57086. * @param particle is the particle we are computed the position for
  57087. */
  57088. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  57089. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  57090. var theta = BABYLON.Scalar.RandomRange(0, Math.PI);
  57091. var randRadius = BABYLON.Scalar.RandomRange(0, this.radius);
  57092. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  57093. var randY = randRadius * Math.cos(theta);
  57094. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  57095. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  57096. };
  57097. /**
  57098. * Clones the current emitter and returns a copy of it
  57099. * @returns the new emitter
  57100. */
  57101. SphereParticleEmitter.prototype.clone = function () {
  57102. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  57103. BABYLON.Tools.DeepCopy(this, newOne);
  57104. return newOne;
  57105. };
  57106. /**
  57107. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57108. * @param effect defines the update shader
  57109. */
  57110. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  57111. effect.setFloat("radius", this.radius);
  57112. effect.setFloat("directionRandomizer", this.directionRandomizer);
  57113. };
  57114. /**
  57115. * Returns a string to use to update the GPU particles update shader
  57116. * @returns a string containng the defines string
  57117. */
  57118. SphereParticleEmitter.prototype.getEffectDefines = function () {
  57119. return "#define SPHEREEMITTER";
  57120. };
  57121. /**
  57122. * Returns the string "SphereParticleEmitter"
  57123. * @returns a string containing the class name
  57124. */
  57125. SphereParticleEmitter.prototype.getClassName = function () {
  57126. return "SphereParticleEmitter";
  57127. };
  57128. /**
  57129. * Serializes the particle system to a JSON object.
  57130. * @returns the JSON object
  57131. */
  57132. SphereParticleEmitter.prototype.serialize = function () {
  57133. var serializationObject = {};
  57134. serializationObject.type = this.getClassName();
  57135. serializationObject.radius = this.radius;
  57136. serializationObject.directionRandomizer = this.directionRandomizer;
  57137. return serializationObject;
  57138. };
  57139. /**
  57140. * Parse properties from a JSON object
  57141. * @param serializationObject defines the JSON object
  57142. */
  57143. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  57144. this.radius = serializationObject.radius;
  57145. this.directionRandomizer = serializationObject.directionRandomizer;
  57146. };
  57147. return SphereParticleEmitter;
  57148. }());
  57149. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  57150. /**
  57151. * Particle emitter emitting particles from the inside of a sphere.
  57152. * It emits the particles randomly between two vectors.
  57153. */
  57154. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  57155. __extends(SphereDirectedParticleEmitter, _super);
  57156. /**
  57157. * Creates a new instance SphereDirectedParticleEmitter
  57158. * @param radius the radius of the emission sphere (1 by default)
  57159. * @param direction1 the min limit of the emission direction (up vector by default)
  57160. * @param direction2 the max limit of the emission direction (up vector by default)
  57161. */
  57162. function SphereDirectedParticleEmitter(radius,
  57163. /**
  57164. * The min limit of the emission direction.
  57165. */
  57166. direction1,
  57167. /**
  57168. * The max limit of the emission direction.
  57169. */
  57170. direction2) {
  57171. if (radius === void 0) { radius = 1; }
  57172. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57173. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57174. var _this = _super.call(this, radius) || this;
  57175. _this.direction1 = direction1;
  57176. _this.direction2 = direction2;
  57177. return _this;
  57178. }
  57179. /**
  57180. * Called by the particle System when the direction is computed for the created particle.
  57181. * @param emitPower is the power of the particle (speed)
  57182. * @param worldMatrix is the world matrix of the particle system
  57183. * @param directionToUpdate is the direction vector to update with the result
  57184. * @param particle is the particle we are computed the direction for
  57185. */
  57186. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (emitPower, worldMatrix, directionToUpdate, particle) {
  57187. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57188. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57189. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57190. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX * emitPower, randY * emitPower, randZ * emitPower, worldMatrix, directionToUpdate);
  57191. };
  57192. /**
  57193. * Clones the current emitter and returns a copy of it
  57194. * @returns the new emitter
  57195. */
  57196. SphereDirectedParticleEmitter.prototype.clone = function () {
  57197. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57198. BABYLON.Tools.DeepCopy(this, newOne);
  57199. return newOne;
  57200. };
  57201. /**
  57202. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57203. * @param effect defines the update shader
  57204. */
  57205. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57206. effect.setFloat("radius", this.radius);
  57207. effect.setVector3("direction1", this.direction1);
  57208. effect.setVector3("direction2", this.direction2);
  57209. };
  57210. /**
  57211. * Returns a string to use to update the GPU particles update shader
  57212. * @returns a string containng the defines string
  57213. */
  57214. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57215. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57216. };
  57217. /**
  57218. * Returns the string "SphereDirectedParticleEmitter"
  57219. * @returns a string containing the class name
  57220. */
  57221. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57222. return "SphereDirectedParticleEmitter";
  57223. };
  57224. /**
  57225. * Serializes the particle system to a JSON object.
  57226. * @returns the JSON object
  57227. */
  57228. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57229. var serializationObject = _super.prototype.serialize.call(this);
  57230. serializationObject.direction1 = this.direction1.asArray();
  57231. serializationObject.direction2 = this.direction2.asArray();
  57232. return serializationObject;
  57233. };
  57234. /**
  57235. * Parse properties from a JSON object
  57236. * @param serializationObject defines the JSON object
  57237. */
  57238. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57239. _super.prototype.parse.call(this, serializationObject);
  57240. this.direction1.copyFrom(serializationObject.direction1);
  57241. this.direction2.copyFrom(serializationObject.direction2);
  57242. };
  57243. return SphereDirectedParticleEmitter;
  57244. }(SphereParticleEmitter));
  57245. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57246. })(BABYLON || (BABYLON = {}));
  57247. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57248. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57249. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57250. s = arguments[i];
  57251. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57252. t[p] = s[p];
  57253. }
  57254. return t;
  57255. };
  57256. var BABYLON;
  57257. (function (BABYLON) {
  57258. /**
  57259. * This represents a GPU particle system in Babylon
  57260. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57261. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57262. */
  57263. var GPUParticleSystem = /** @class */ (function () {
  57264. /**
  57265. * Instantiates a GPU particle system.
  57266. * 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.
  57267. * @param name The name of the particle system
  57268. * @param capacity The max number of particles alive at the same time
  57269. * @param scene The scene the particle system belongs to
  57270. */
  57271. function GPUParticleSystem(name, options, scene) {
  57272. /**
  57273. * The emitter represents the Mesh or position we are attaching the particle system to.
  57274. */
  57275. this.emitter = null;
  57276. /**
  57277. * The rendering group used by the Particle system to chose when to render.
  57278. */
  57279. this.renderingGroupId = 0;
  57280. /**
  57281. * The layer mask we are rendering the particles through.
  57282. */
  57283. this.layerMask = 0x0FFFFFFF;
  57284. this._targetIndex = 0;
  57285. this._currentRenderId = -1;
  57286. this._started = false;
  57287. this._stopped = false;
  57288. this._timeDelta = 0;
  57289. this._attributesStrideSize = 14;
  57290. this._actualFrame = 0;
  57291. /**
  57292. * List of animations used by the particle system.
  57293. */
  57294. this.animations = [];
  57295. /**
  57296. * An event triggered when the system is disposed.
  57297. */
  57298. this.onDisposeObservable = new BABYLON.Observable();
  57299. /**
  57300. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57301. */
  57302. this.updateSpeed = 0.01;
  57303. /**
  57304. * The amount of time the particle system is running (depends of the overall update speed).
  57305. */
  57306. this.targetStopDuration = 0;
  57307. /**
  57308. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57309. */
  57310. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57311. /**
  57312. * Minimum life time of emitting particles.
  57313. */
  57314. this.minLifeTime = 1;
  57315. /**
  57316. * Maximum life time of emitting particles.
  57317. */
  57318. this.maxLifeTime = 1;
  57319. /**
  57320. * Minimum Size of emitting particles.
  57321. */
  57322. this.minSize = 1;
  57323. /**
  57324. * Maximum Size of emitting particles.
  57325. */
  57326. this.maxSize = 1;
  57327. /**
  57328. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57329. */
  57330. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57331. /**
  57332. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57333. */
  57334. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57335. /**
  57336. * Color the particle will have at the end of its lifetime.
  57337. */
  57338. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57339. /**
  57340. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57341. */
  57342. this.emitRate = 100;
  57343. /**
  57344. * You can use gravity if you want to give an orientation to your particles.
  57345. */
  57346. this.gravity = BABYLON.Vector3.Zero();
  57347. /**
  57348. * Minimum power of emitting particles.
  57349. */
  57350. this.minEmitPower = 1;
  57351. /**
  57352. * Maximum power of emitting particles.
  57353. */
  57354. this.maxEmitPower = 1;
  57355. /**
  57356. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57357. * to override the particles.
  57358. */
  57359. this.forceDepthWrite = false;
  57360. this.id = name;
  57361. this.name = name;
  57362. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57363. this._engine = this._scene.getEngine();
  57364. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57365. this._capacity = fullOptions.capacity;
  57366. this._activeCount = fullOptions.capacity;
  57367. this._currentActiveCount = 0;
  57368. this._scene.particleSystems.push(this);
  57369. this._updateEffectOptions = {
  57370. attributes: ["position", "age", "life", "seed", "size", "color", "direction"],
  57371. uniformsNames: ["currentCount", "timeDelta", "generalRandoms", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "gravity", "emitPower",
  57372. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "angle", "stopFactor"],
  57373. uniformBuffersNames: [],
  57374. samplers: ["randomSampler"],
  57375. defines: "",
  57376. fallbacks: null,
  57377. onCompiled: null,
  57378. onError: null,
  57379. indexParameters: null,
  57380. maxSimultaneousLights: 0,
  57381. transformFeedbackVaryings: ["outPosition", "outAge", "outLife", "outSeed", "outSize", "outColor", "outDirection"]
  57382. };
  57383. // Random data
  57384. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57385. var d = [];
  57386. for (var i = 0; i < maxTextureSize; ++i) {
  57387. d.push(Math.random());
  57388. d.push(Math.random());
  57389. d.push(Math.random());
  57390. d.push(Math.random());
  57391. }
  57392. 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);
  57393. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57394. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57395. this._randomTextureSize = maxTextureSize;
  57396. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57397. }
  57398. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57399. /**
  57400. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57401. */
  57402. get: function () {
  57403. if (!BABYLON.Engine.LastCreatedEngine) {
  57404. return false;
  57405. }
  57406. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57407. },
  57408. enumerable: true,
  57409. configurable: true
  57410. });
  57411. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57412. /**
  57413. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57414. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57415. */
  57416. get: function () {
  57417. if (this.particleEmitterType.direction1) {
  57418. return this.particleEmitterType.direction1;
  57419. }
  57420. return BABYLON.Vector3.Zero();
  57421. },
  57422. set: function (value) {
  57423. if (this.particleEmitterType.direction1) {
  57424. this.particleEmitterType.direction1 = value;
  57425. }
  57426. },
  57427. enumerable: true,
  57428. configurable: true
  57429. });
  57430. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57431. /**
  57432. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57433. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57434. */
  57435. get: function () {
  57436. if (this.particleEmitterType.direction2) {
  57437. return this.particleEmitterType.direction2;
  57438. }
  57439. return BABYLON.Vector3.Zero();
  57440. },
  57441. set: function (value) {
  57442. if (this.particleEmitterType.direction2) {
  57443. this.particleEmitterType.direction2 = value;
  57444. }
  57445. },
  57446. enumerable: true,
  57447. configurable: true
  57448. });
  57449. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57450. /**
  57451. * 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.
  57452. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57453. */
  57454. get: function () {
  57455. if (this.particleEmitterType.minEmitBox) {
  57456. return this.particleEmitterType.minEmitBox;
  57457. }
  57458. return BABYLON.Vector3.Zero();
  57459. },
  57460. set: function (value) {
  57461. if (this.particleEmitterType.minEmitBox) {
  57462. this.particleEmitterType.minEmitBox = value;
  57463. }
  57464. },
  57465. enumerable: true,
  57466. configurable: true
  57467. });
  57468. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57469. /**
  57470. * 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.
  57471. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57472. */
  57473. get: function () {
  57474. if (this.particleEmitterType.maxEmitBox) {
  57475. return this.particleEmitterType.maxEmitBox;
  57476. }
  57477. return BABYLON.Vector3.Zero();
  57478. },
  57479. set: function (value) {
  57480. if (this.particleEmitterType.maxEmitBox) {
  57481. this.particleEmitterType.maxEmitBox = value;
  57482. }
  57483. },
  57484. enumerable: true,
  57485. configurable: true
  57486. });
  57487. /**
  57488. * Gets the maximum number of particles active at the same time.
  57489. * @returns The max number of active particles.
  57490. */
  57491. GPUParticleSystem.prototype.getCapacity = function () {
  57492. return this._capacity;
  57493. };
  57494. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57495. /**
  57496. * Gets or set the number of active particles
  57497. */
  57498. get: function () {
  57499. return this._activeCount;
  57500. },
  57501. set: function (value) {
  57502. this._activeCount = Math.min(value, this._capacity);
  57503. },
  57504. enumerable: true,
  57505. configurable: true
  57506. });
  57507. /**
  57508. * Is this system ready to be used/rendered
  57509. * @return true if the system is ready
  57510. */
  57511. GPUParticleSystem.prototype.isReady = function () {
  57512. if (!this._updateEffect) {
  57513. this._recreateUpdateEffect();
  57514. this._recreateRenderEffect();
  57515. return false;
  57516. }
  57517. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57518. return false;
  57519. }
  57520. return true;
  57521. };
  57522. /**
  57523. * Gets Wether the system has been started.
  57524. * @returns True if it has been started, otherwise false.
  57525. */
  57526. GPUParticleSystem.prototype.isStarted = function () {
  57527. return this._started;
  57528. };
  57529. /**
  57530. * Starts the particle system and begins to emit.
  57531. */
  57532. GPUParticleSystem.prototype.start = function () {
  57533. this._started = true;
  57534. this._stopped = false;
  57535. };
  57536. /**
  57537. * Stops the particle system.
  57538. */
  57539. GPUParticleSystem.prototype.stop = function () {
  57540. this._stopped = true;
  57541. };
  57542. /**
  57543. * Remove all active particles
  57544. */
  57545. GPUParticleSystem.prototype.reset = function () {
  57546. this._releaseBuffers();
  57547. this._releaseVAOs();
  57548. this._currentActiveCount = 0;
  57549. this._targetIndex = 0;
  57550. };
  57551. /**
  57552. * Returns the string "GPUParticleSystem"
  57553. * @returns a string containing the class name
  57554. */
  57555. GPUParticleSystem.prototype.getClassName = function () {
  57556. return "GPUParticleSystem";
  57557. };
  57558. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57559. var updateVertexBuffers = {};
  57560. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57561. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57562. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57563. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 1);
  57564. updateVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1);
  57565. updateVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4);
  57566. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", 11, 3);
  57567. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57568. this._engine.bindArrayBuffer(null);
  57569. return vao;
  57570. };
  57571. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57572. var renderVertexBuffers = {};
  57573. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57574. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57575. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57576. renderVertexBuffers["size"] = source.createVertexBuffer("size", 6, 1, this._attributesStrideSize, true);
  57577. renderVertexBuffers["color"] = source.createVertexBuffer("color", 7, 4, this._attributesStrideSize, true);
  57578. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57579. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57580. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57581. this._engine.bindArrayBuffer(null);
  57582. return vao;
  57583. };
  57584. GPUParticleSystem.prototype._initialize = function (force) {
  57585. if (force === void 0) { force = false; }
  57586. if (this._buffer0 && !force) {
  57587. return;
  57588. }
  57589. var engine = this._scene.getEngine();
  57590. var data = new Array();
  57591. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57592. // position
  57593. data.push(0.0);
  57594. data.push(0.0);
  57595. data.push(0.0);
  57596. // Age and life
  57597. data.push(0.0); // create the particle as a dead one to create a new one at start
  57598. data.push(0.0);
  57599. // Seed
  57600. data.push(Math.random());
  57601. // Size
  57602. data.push(0.0);
  57603. // color
  57604. data.push(0.0);
  57605. data.push(0.0);
  57606. data.push(0.0);
  57607. data.push(0.0);
  57608. // direction
  57609. data.push(0.0);
  57610. data.push(0.0);
  57611. data.push(0.0);
  57612. }
  57613. // Sprite data
  57614. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57615. -0.5, 0.5, 0, 1,
  57616. -0.5, -0.5, 0, 0,
  57617. 0.5, -0.5, 1, 0]);
  57618. // Buffers
  57619. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57620. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57621. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57622. // Update VAO
  57623. this._updateVAO = [];
  57624. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57625. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57626. // Render VAO
  57627. this._renderVAO = [];
  57628. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57629. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57630. // Links
  57631. this._sourceBuffer = this._buffer0;
  57632. this._targetBuffer = this._buffer1;
  57633. };
  57634. /** @hidden */
  57635. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57636. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57637. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57638. return;
  57639. }
  57640. this._updateEffectOptions.defines = defines;
  57641. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57642. };
  57643. /** @hidden */
  57644. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57645. var defines = "";
  57646. if (this._scene.clipPlane) {
  57647. defines = "\n#define CLIPPLANE";
  57648. }
  57649. if (this._renderEffect && this._renderEffect.defines === defines) {
  57650. return;
  57651. }
  57652. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv"], ["view", "projection", "colorDead", "invView", "vClipPlane"], ["textureSampler"], this._scene.getEngine(), defines);
  57653. };
  57654. /**
  57655. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57656. */
  57657. GPUParticleSystem.prototype.animate = function () {
  57658. this._timeDelta = this.updateSpeed * this._scene.getAnimationRatio();
  57659. this._actualFrame += this._timeDelta;
  57660. if (!this._stopped) {
  57661. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57662. this.stop();
  57663. }
  57664. }
  57665. };
  57666. /**
  57667. * Renders the particle system in its current state.
  57668. * @returns the current number of particles
  57669. */
  57670. GPUParticleSystem.prototype.render = function () {
  57671. if (!this._started) {
  57672. return 0;
  57673. }
  57674. this._recreateUpdateEffect();
  57675. this._recreateRenderEffect();
  57676. if (!this.isReady()) {
  57677. return 0;
  57678. }
  57679. if (this._currentRenderId === this._scene.getRenderId()) {
  57680. return 0;
  57681. }
  57682. this._currentRenderId = this._scene.getRenderId();
  57683. // Get everything ready to render
  57684. this._initialize();
  57685. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + (this.emitRate * this._timeDelta) | 0);
  57686. // Enable update effect
  57687. this._engine.enableEffect(this._updateEffect);
  57688. this._engine.setState(false);
  57689. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57690. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57691. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57692. this._updateEffect.setFloat3("generalRandoms", Math.random(), Math.random(), Math.random());
  57693. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57694. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57695. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57696. this._updateEffect.setDirectColor4("color1", this.color1);
  57697. this._updateEffect.setDirectColor4("color2", this.color2);
  57698. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57699. this._updateEffect.setVector3("gravity", this.gravity);
  57700. if (this.particleEmitterType) {
  57701. this.particleEmitterType.applyToShader(this._updateEffect);
  57702. }
  57703. var emitterWM;
  57704. if (this.emitter.position) {
  57705. var emitterMesh = this.emitter;
  57706. emitterWM = emitterMesh.getWorldMatrix();
  57707. }
  57708. else {
  57709. var emitterPosition = this.emitter;
  57710. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57711. }
  57712. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57713. // Bind source VAO
  57714. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57715. // Update
  57716. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57717. this._engine.setRasterizerState(false);
  57718. this._engine.beginTransformFeedback();
  57719. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57720. this._engine.endTransformFeedback();
  57721. this._engine.setRasterizerState(true);
  57722. this._engine.bindTransformFeedbackBuffer(null);
  57723. // Enable render effect
  57724. this._engine.enableEffect(this._renderEffect);
  57725. var viewMatrix = this._scene.getViewMatrix();
  57726. this._renderEffect.setMatrix("view", viewMatrix);
  57727. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57728. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57729. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57730. if (this._scene.clipPlane) {
  57731. var clipPlane = this._scene.clipPlane;
  57732. var invView = viewMatrix.clone();
  57733. invView.invert();
  57734. this._renderEffect.setMatrix("invView", invView);
  57735. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57736. }
  57737. // Draw order
  57738. if (this.blendMode === BABYLON.ParticleSystem.BLENDMODE_ONEONE) {
  57739. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57740. }
  57741. else {
  57742. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57743. }
  57744. if (this.forceDepthWrite) {
  57745. this._engine.setDepthWrite(true);
  57746. }
  57747. // Bind source VAO
  57748. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  57749. // Render
  57750. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  57751. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  57752. // Switch VAOs
  57753. this._targetIndex++;
  57754. if (this._targetIndex === 2) {
  57755. this._targetIndex = 0;
  57756. }
  57757. // Switch buffers
  57758. var tmpBuffer = this._sourceBuffer;
  57759. this._sourceBuffer = this._targetBuffer;
  57760. this._targetBuffer = tmpBuffer;
  57761. return this._currentActiveCount;
  57762. };
  57763. /**
  57764. * Rebuilds the particle system
  57765. */
  57766. GPUParticleSystem.prototype.rebuild = function () {
  57767. this._initialize(true);
  57768. };
  57769. GPUParticleSystem.prototype._releaseBuffers = function () {
  57770. if (this._buffer0) {
  57771. this._buffer0.dispose();
  57772. this._buffer0 = null;
  57773. }
  57774. if (this._buffer1) {
  57775. this._buffer1.dispose();
  57776. this._buffer1 = null;
  57777. }
  57778. if (this._spriteBuffer) {
  57779. this._spriteBuffer.dispose();
  57780. this._spriteBuffer = null;
  57781. }
  57782. };
  57783. GPUParticleSystem.prototype._releaseVAOs = function () {
  57784. if (!this._updateVAO) {
  57785. return;
  57786. }
  57787. for (var index = 0; index < this._updateVAO.length; index++) {
  57788. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  57789. }
  57790. this._updateVAO = [];
  57791. for (var index = 0; index < this._renderVAO.length; index++) {
  57792. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  57793. }
  57794. this._renderVAO = [];
  57795. };
  57796. /**
  57797. * Disposes the particle system and free the associated resources
  57798. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  57799. */
  57800. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  57801. if (disposeTexture === void 0) { disposeTexture = true; }
  57802. var index = this._scene.particleSystems.indexOf(this);
  57803. if (index > -1) {
  57804. this._scene.particleSystems.splice(index, 1);
  57805. }
  57806. this._releaseBuffers();
  57807. this._releaseVAOs();
  57808. if (this._randomTexture) {
  57809. this._randomTexture.dispose();
  57810. this._randomTexture = null;
  57811. }
  57812. if (disposeTexture && this.particleTexture) {
  57813. this.particleTexture.dispose();
  57814. this.particleTexture = null;
  57815. }
  57816. // Callback
  57817. this.onDisposeObservable.notifyObservers(this);
  57818. this.onDisposeObservable.clear();
  57819. };
  57820. /**
  57821. * Clones the particle system.
  57822. * @param name The name of the cloned object
  57823. * @param newEmitter The new emitter to use
  57824. * @returns the cloned particle system
  57825. */
  57826. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  57827. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  57828. BABYLON.Tools.DeepCopy(this, result);
  57829. if (newEmitter === undefined) {
  57830. newEmitter = this.emitter;
  57831. }
  57832. result.emitter = newEmitter;
  57833. if (this.particleTexture) {
  57834. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  57835. }
  57836. return result;
  57837. };
  57838. /**
  57839. * Serializes the particle system to a JSON object.
  57840. * @returns the JSON object
  57841. */
  57842. GPUParticleSystem.prototype.serialize = function () {
  57843. var serializationObject = {};
  57844. serializationObject.name = this.name;
  57845. serializationObject.id = this.id;
  57846. // Emitter
  57847. if (this.emitter.position) {
  57848. var emitterMesh = this.emitter;
  57849. serializationObject.emitterId = emitterMesh.id;
  57850. }
  57851. else {
  57852. var emitterPosition = this.emitter;
  57853. serializationObject.emitter = emitterPosition.asArray();
  57854. }
  57855. serializationObject.capacity = this.getCapacity();
  57856. if (this.particleTexture) {
  57857. serializationObject.textureName = this.particleTexture.name;
  57858. }
  57859. // Animations
  57860. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  57861. // Particle system
  57862. serializationObject.activeParticleCount = this.activeParticleCount;
  57863. serializationObject.randomTextureSize = this._randomTextureSize;
  57864. serializationObject.minSize = this.minSize;
  57865. serializationObject.maxSize = this.maxSize;
  57866. serializationObject.minEmitPower = this.minEmitPower;
  57867. serializationObject.maxEmitPower = this.maxEmitPower;
  57868. serializationObject.minLifeTime = this.minLifeTime;
  57869. serializationObject.maxLifeTime = this.maxLifeTime;
  57870. serializationObject.emitRate = this.emitRate;
  57871. serializationObject.gravity = this.gravity.asArray();
  57872. serializationObject.color1 = this.color1.asArray();
  57873. serializationObject.color2 = this.color2.asArray();
  57874. serializationObject.colorDead = this.colorDead.asArray();
  57875. serializationObject.updateSpeed = this.updateSpeed;
  57876. serializationObject.targetStopDuration = this.targetStopDuration;
  57877. serializationObject.blendMode = this.blendMode;
  57878. // Emitter
  57879. if (this.particleEmitterType) {
  57880. serializationObject.particleEmitterType = this.particleEmitterType.serialize();
  57881. }
  57882. return serializationObject;
  57883. };
  57884. /**
  57885. * Parses a JSON object to create a GPU particle system.
  57886. * @param parsedParticleSystem The JSON object to parse
  57887. * @param scene The scene to create the particle system in
  57888. * @param rootUrl The root url to use to load external dependencies like texture
  57889. * @returns the parsed GPU particle system
  57890. */
  57891. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  57892. var name = parsedParticleSystem.name;
  57893. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  57894. if (parsedParticleSystem.id) {
  57895. particleSystem.id = parsedParticleSystem.id;
  57896. }
  57897. // Texture
  57898. if (parsedParticleSystem.textureName) {
  57899. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  57900. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  57901. }
  57902. // Emitter
  57903. if (parsedParticleSystem.emitterId) {
  57904. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  57905. }
  57906. else {
  57907. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  57908. }
  57909. // Animations
  57910. if (parsedParticleSystem.animations) {
  57911. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  57912. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  57913. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  57914. }
  57915. }
  57916. // Particle system
  57917. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  57918. particleSystem.minSize = parsedParticleSystem.minSize;
  57919. particleSystem.maxSize = parsedParticleSystem.maxSize;
  57920. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  57921. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  57922. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  57923. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  57924. particleSystem.emitRate = parsedParticleSystem.emitRate;
  57925. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  57926. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  57927. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  57928. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  57929. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  57930. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  57931. particleSystem.blendMode = parsedParticleSystem.blendMode;
  57932. // Emitter
  57933. if (parsedParticleSystem.particleEmitterType) {
  57934. var emitterType = void 0;
  57935. switch (parsedParticleSystem.particleEmitterType.type) {
  57936. case "SphereEmitter":
  57937. emitterType = new BABYLON.SphereParticleEmitter();
  57938. break;
  57939. case "SphereDirectedParticleEmitter":
  57940. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  57941. break;
  57942. case "ConeEmitter":
  57943. emitterType = new BABYLON.ConeParticleEmitter();
  57944. break;
  57945. case "BoxEmitter":
  57946. default:
  57947. emitterType = new BABYLON.BoxParticleEmitter();
  57948. break;
  57949. }
  57950. emitterType.parse(parsedParticleSystem.particleEmitterType);
  57951. particleSystem.particleEmitterType = emitterType;
  57952. }
  57953. return particleSystem;
  57954. };
  57955. return GPUParticleSystem;
  57956. }());
  57957. BABYLON.GPUParticleSystem = GPUParticleSystem;
  57958. })(BABYLON || (BABYLON = {}));
  57959. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  57960. var BABYLON;
  57961. (function (BABYLON) {
  57962. /**
  57963. * Represents one particle of a solid particle system.
  57964. */
  57965. var SolidParticle = /** @class */ (function () {
  57966. /**
  57967. * Creates a Solid Particle object.
  57968. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  57969. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  57970. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  57971. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  57972. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  57973. * @param shapeId (integer) is the model shape identifier in the SPS.
  57974. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  57975. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  57976. */
  57977. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  57978. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  57979. /**
  57980. * particle global index
  57981. */
  57982. this.idx = 0;
  57983. /**
  57984. * The color of the particle
  57985. */
  57986. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57987. /**
  57988. * The world space position of the particle.
  57989. */
  57990. this.position = BABYLON.Vector3.Zero();
  57991. /**
  57992. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  57993. */
  57994. this.rotation = BABYLON.Vector3.Zero();
  57995. /**
  57996. * The scaling of the particle.
  57997. */
  57998. this.scaling = BABYLON.Vector3.One();
  57999. /**
  58000. * The uvs of the particle.
  58001. */
  58002. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58003. /**
  58004. * The current speed of the particle.
  58005. */
  58006. this.velocity = BABYLON.Vector3.Zero();
  58007. /**
  58008. * The pivot point in the particle local space.
  58009. */
  58010. this.pivot = BABYLON.Vector3.Zero();
  58011. /**
  58012. * Must the particle be translated from its pivot point in its local space ?
  58013. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58014. * Default : false
  58015. */
  58016. this.translateFromPivot = false;
  58017. /**
  58018. * Is the particle active or not ?
  58019. */
  58020. this.alive = true;
  58021. /**
  58022. * Is the particle visible or not ?
  58023. */
  58024. this.isVisible = true;
  58025. /**
  58026. * Index of this particle in the global "positions" array (Internal use)
  58027. */
  58028. this._pos = 0;
  58029. /**
  58030. * Index of this particle in the global "indices" array (Internal use)
  58031. */
  58032. this._ind = 0;
  58033. /**
  58034. * ModelShape id of this particle
  58035. */
  58036. this.shapeId = 0;
  58037. /**
  58038. * Index of the particle in its shape id (Internal use)
  58039. */
  58040. this.idxInShape = 0;
  58041. /**
  58042. * Still set as invisible in order to skip useless computations (Internal use)
  58043. */
  58044. this._stillInvisible = false;
  58045. /**
  58046. * Last computed particle rotation matrix
  58047. */
  58048. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58049. /**
  58050. * Parent particle Id, if any.
  58051. * Default null.
  58052. */
  58053. this.parentId = null;
  58054. /**
  58055. * Internal global position in the SPS.
  58056. */
  58057. this._globalPosition = BABYLON.Vector3.Zero();
  58058. this.idx = particleIndex;
  58059. this._pos = positionIndex;
  58060. this._ind = indiceIndex;
  58061. this._model = model;
  58062. this.shapeId = shapeId;
  58063. this.idxInShape = idxInShape;
  58064. this._sps = sps;
  58065. if (modelBoundingInfo) {
  58066. this._modelBoundingInfo = modelBoundingInfo;
  58067. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58068. }
  58069. }
  58070. Object.defineProperty(SolidParticle.prototype, "scale", {
  58071. /**
  58072. * Legacy support, changed scale to scaling
  58073. */
  58074. get: function () {
  58075. return this.scaling;
  58076. },
  58077. /**
  58078. * Legacy support, changed scale to scaling
  58079. */
  58080. set: function (scale) {
  58081. this.scaling = scale;
  58082. },
  58083. enumerable: true,
  58084. configurable: true
  58085. });
  58086. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58087. /**
  58088. * Legacy support, changed quaternion to rotationQuaternion
  58089. */
  58090. get: function () {
  58091. return this.rotationQuaternion;
  58092. },
  58093. /**
  58094. * Legacy support, changed quaternion to rotationQuaternion
  58095. */
  58096. set: function (q) {
  58097. this.rotationQuaternion = q;
  58098. },
  58099. enumerable: true,
  58100. configurable: true
  58101. });
  58102. /**
  58103. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58104. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58105. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58106. * @returns true if it intersects
  58107. */
  58108. SolidParticle.prototype.intersectsMesh = function (target) {
  58109. if (!this._boundingInfo || !target._boundingInfo) {
  58110. return false;
  58111. }
  58112. if (this._sps._bSphereOnly) {
  58113. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58114. }
  58115. return this._boundingInfo.intersects(target._boundingInfo, false);
  58116. };
  58117. return SolidParticle;
  58118. }());
  58119. BABYLON.SolidParticle = SolidParticle;
  58120. /**
  58121. * Represents the shape of the model used by one particle of a solid particle system.
  58122. * SPS internal tool, don't use it manually.
  58123. */
  58124. var ModelShape = /** @class */ (function () {
  58125. /**
  58126. * 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.
  58127. * SPS internal tool, don't use it manually.
  58128. * @hidden
  58129. */
  58130. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58131. /**
  58132. * length of the shape in the model indices array (internal use)
  58133. */
  58134. this._indicesLength = 0;
  58135. this.shapeID = id;
  58136. this._shape = shape;
  58137. this._indicesLength = indicesLength;
  58138. this._shapeUV = shapeUV;
  58139. this._positionFunction = posFunction;
  58140. this._vertexFunction = vtxFunction;
  58141. }
  58142. return ModelShape;
  58143. }());
  58144. BABYLON.ModelShape = ModelShape;
  58145. /**
  58146. * Represents a Depth Sorted Particle in the solid particle system.
  58147. */
  58148. var DepthSortedParticle = /** @class */ (function () {
  58149. function DepthSortedParticle() {
  58150. /**
  58151. * Index of the particle in the "indices" array
  58152. */
  58153. this.ind = 0;
  58154. /**
  58155. * Length of the particle shape in the "indices" array
  58156. */
  58157. this.indicesLength = 0;
  58158. /**
  58159. * Squared distance from the particle to the camera
  58160. */
  58161. this.sqDistance = 0.0;
  58162. }
  58163. return DepthSortedParticle;
  58164. }());
  58165. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58166. })(BABYLON || (BABYLON = {}));
  58167. //# sourceMappingURL=babylon.solidParticle.js.map
  58168. var BABYLON;
  58169. (function (BABYLON) {
  58170. /**
  58171. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58172. *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.
  58173. * The SPS is also a particle system. It provides some methods to manage the particles.
  58174. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58175. *
  58176. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58177. */
  58178. var SolidParticleSystem = /** @class */ (function () {
  58179. /**
  58180. * Creates a SPS (Solid Particle System) object.
  58181. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58182. * @param scene (Scene) is the scene in which the SPS is added.
  58183. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58184. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58185. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58186. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58187. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58188. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58189. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58190. */
  58191. function SolidParticleSystem(name, scene, options) {
  58192. /**
  58193. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58194. * Example : var p = SPS.particles[i];
  58195. */
  58196. this.particles = new Array();
  58197. /**
  58198. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58199. */
  58200. this.nbParticles = 0;
  58201. /**
  58202. * If the particles must ever face the camera (default false). Useful for planar particles.
  58203. */
  58204. this.billboard = false;
  58205. /**
  58206. * Recompute normals when adding a shape
  58207. */
  58208. this.recomputeNormals = true;
  58209. /**
  58210. * This a counter ofr your own usage. It's not set by any SPS functions.
  58211. */
  58212. this.counter = 0;
  58213. /**
  58214. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58215. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58216. */
  58217. this.vars = {};
  58218. /**
  58219. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58220. */
  58221. this._bSphereOnly = false;
  58222. /**
  58223. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58224. */
  58225. this._bSphereRadiusFactor = 1.0;
  58226. this._positions = new Array();
  58227. this._indices = new Array();
  58228. this._normals = new Array();
  58229. this._colors = new Array();
  58230. this._uvs = new Array();
  58231. this._index = 0; // indices index
  58232. this._updatable = true;
  58233. this._pickable = false;
  58234. this._isVisibilityBoxLocked = false;
  58235. this._alwaysVisible = false;
  58236. this._depthSort = false;
  58237. this._shapeCounter = 0;
  58238. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58239. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58240. this._computeParticleColor = true;
  58241. this._computeParticleTexture = true;
  58242. this._computeParticleRotation = true;
  58243. this._computeParticleVertex = false;
  58244. this._computeBoundingBox = false;
  58245. this._depthSortParticles = true;
  58246. this._cam_axisZ = BABYLON.Vector3.Zero();
  58247. this._cam_axisY = BABYLON.Vector3.Zero();
  58248. this._cam_axisX = BABYLON.Vector3.Zero();
  58249. this._axisZ = BABYLON.Axis.Z;
  58250. this._camDir = BABYLON.Vector3.Zero();
  58251. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58252. this._rotMatrix = new BABYLON.Matrix();
  58253. this._invertMatrix = new BABYLON.Matrix();
  58254. this._rotated = BABYLON.Vector3.Zero();
  58255. this._quaternion = new BABYLON.Quaternion();
  58256. this._vertex = BABYLON.Vector3.Zero();
  58257. this._normal = BABYLON.Vector3.Zero();
  58258. this._yaw = 0.0;
  58259. this._pitch = 0.0;
  58260. this._roll = 0.0;
  58261. this._halfroll = 0.0;
  58262. this._halfpitch = 0.0;
  58263. this._halfyaw = 0.0;
  58264. this._sinRoll = 0.0;
  58265. this._cosRoll = 0.0;
  58266. this._sinPitch = 0.0;
  58267. this._cosPitch = 0.0;
  58268. this._sinYaw = 0.0;
  58269. this._cosYaw = 0.0;
  58270. this._mustUnrotateFixedNormals = false;
  58271. this._minimum = BABYLON.Vector3.Zero();
  58272. this._maximum = BABYLON.Vector3.Zero();
  58273. this._minBbox = BABYLON.Vector3.Zero();
  58274. this._maxBbox = BABYLON.Vector3.Zero();
  58275. this._particlesIntersect = false;
  58276. this._depthSortFunction = function (p1, p2) {
  58277. return (p2.sqDistance - p1.sqDistance);
  58278. };
  58279. this._needs32Bits = false;
  58280. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58281. this._scaledPivot = BABYLON.Vector3.Zero();
  58282. this._particleHasParent = false;
  58283. this.name = name;
  58284. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58285. this._camera = scene.activeCamera;
  58286. this._pickable = options ? options.isPickable : false;
  58287. this._depthSort = options ? options.enableDepthSort : false;
  58288. this._particlesIntersect = options ? options.particleIntersection : false;
  58289. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58290. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58291. if (options && options.updatable) {
  58292. this._updatable = options.updatable;
  58293. }
  58294. else {
  58295. this._updatable = true;
  58296. }
  58297. if (this._pickable) {
  58298. this.pickedParticles = [];
  58299. }
  58300. if (this._depthSort) {
  58301. this.depthSortedParticles = [];
  58302. }
  58303. }
  58304. /**
  58305. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58306. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58307. * @returns the created mesh
  58308. */
  58309. SolidParticleSystem.prototype.buildMesh = function () {
  58310. if (this.nbParticles === 0) {
  58311. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58312. this.addShape(triangle, 1);
  58313. triangle.dispose();
  58314. }
  58315. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58316. this._positions32 = new Float32Array(this._positions);
  58317. this._uvs32 = new Float32Array(this._uvs);
  58318. this._colors32 = new Float32Array(this._colors);
  58319. if (this.recomputeNormals) {
  58320. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58321. }
  58322. this._normals32 = new Float32Array(this._normals);
  58323. this._fixedNormal32 = new Float32Array(this._normals);
  58324. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58325. this._unrotateFixedNormals();
  58326. }
  58327. var vertexData = new BABYLON.VertexData();
  58328. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58329. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58330. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58331. if (this._uvs32.length > 0) {
  58332. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58333. }
  58334. if (this._colors32.length > 0) {
  58335. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58336. }
  58337. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58338. vertexData.applyToMesh(mesh, this._updatable);
  58339. this.mesh = mesh;
  58340. this.mesh.isPickable = this._pickable;
  58341. // free memory
  58342. if (!this._depthSort) {
  58343. this._indices = null;
  58344. }
  58345. this._positions = null;
  58346. this._normals = null;
  58347. this._uvs = null;
  58348. this._colors = null;
  58349. if (!this._updatable) {
  58350. this.particles.length = 0;
  58351. }
  58352. return mesh;
  58353. };
  58354. /**
  58355. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58356. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58357. * Thus the particles generated from `digest()` have their property `position` set yet.
  58358. * @param mesh ( Mesh ) is the mesh to be digested
  58359. * @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
  58360. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58361. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58362. * @returns the current SPS
  58363. */
  58364. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58365. var size = (options && options.facetNb) || 1;
  58366. var number = (options && options.number) || 0;
  58367. var delta = (options && options.delta) || 0;
  58368. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58369. var meshInd = mesh.getIndices();
  58370. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58371. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58372. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58373. var f = 0; // facet counter
  58374. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58375. // compute size from number
  58376. if (number) {
  58377. number = (number > totalFacets) ? totalFacets : number;
  58378. size = Math.round(totalFacets / number);
  58379. delta = 0;
  58380. }
  58381. else {
  58382. size = (size > totalFacets) ? totalFacets : size;
  58383. }
  58384. var facetPos = []; // submesh positions
  58385. var facetInd = []; // submesh indices
  58386. var facetUV = []; // submesh UV
  58387. var facetCol = []; // submesh colors
  58388. var barycenter = BABYLON.Vector3.Zero();
  58389. var sizeO = size;
  58390. while (f < totalFacets) {
  58391. size = sizeO + Math.floor((1 + delta) * Math.random());
  58392. if (f > totalFacets - size) {
  58393. size = totalFacets - f;
  58394. }
  58395. // reset temp arrays
  58396. facetPos.length = 0;
  58397. facetInd.length = 0;
  58398. facetUV.length = 0;
  58399. facetCol.length = 0;
  58400. // iterate over "size" facets
  58401. var fi = 0;
  58402. for (var j = f * 3; j < (f + size) * 3; j++) {
  58403. facetInd.push(fi);
  58404. var i = meshInd[j];
  58405. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58406. if (meshUV) {
  58407. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58408. }
  58409. if (meshCol) {
  58410. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58411. }
  58412. fi++;
  58413. }
  58414. // create a model shape for each single particle
  58415. var idx = this.nbParticles;
  58416. var shape = this._posToShape(facetPos);
  58417. var shapeUV = this._uvsToShapeUV(facetUV);
  58418. // compute the barycenter of the shape
  58419. var v;
  58420. for (v = 0; v < shape.length; v++) {
  58421. barycenter.addInPlace(shape[v]);
  58422. }
  58423. barycenter.scaleInPlace(1 / shape.length);
  58424. // shift the shape from its barycenter to the origin
  58425. for (v = 0; v < shape.length; v++) {
  58426. shape[v].subtractInPlace(barycenter);
  58427. }
  58428. var bInfo;
  58429. if (this._particlesIntersect) {
  58430. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58431. }
  58432. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58433. // add the particle in the SPS
  58434. var currentPos = this._positions.length;
  58435. var currentInd = this._indices.length;
  58436. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58437. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58438. // initialize the particle position
  58439. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58440. this._index += shape.length;
  58441. idx++;
  58442. this.nbParticles++;
  58443. this._shapeCounter++;
  58444. f += size;
  58445. }
  58446. return this;
  58447. };
  58448. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58449. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58450. var index = 0;
  58451. var idx = 0;
  58452. for (var p = 0; p < this.particles.length; p++) {
  58453. this._particle = this.particles[p];
  58454. this._shape = this._particle._model._shape;
  58455. if (this._particle.rotationQuaternion) {
  58456. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58457. }
  58458. else {
  58459. this._yaw = this._particle.rotation.y;
  58460. this._pitch = this._particle.rotation.x;
  58461. this._roll = this._particle.rotation.z;
  58462. this._quaternionRotationYPR();
  58463. }
  58464. this._quaternionToRotationMatrix();
  58465. this._rotMatrix.invertToRef(this._invertMatrix);
  58466. for (var pt = 0; pt < this._shape.length; pt++) {
  58467. idx = index + pt * 3;
  58468. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58469. this._fixedNormal32[idx] = this._normal.x;
  58470. this._fixedNormal32[idx + 1] = this._normal.y;
  58471. this._fixedNormal32[idx + 2] = this._normal.z;
  58472. }
  58473. index = idx + 3;
  58474. }
  58475. };
  58476. //reset copy
  58477. SolidParticleSystem.prototype._resetCopy = function () {
  58478. this._copy.position.x = 0;
  58479. this._copy.position.y = 0;
  58480. this._copy.position.z = 0;
  58481. this._copy.rotation.x = 0;
  58482. this._copy.rotation.y = 0;
  58483. this._copy.rotation.z = 0;
  58484. this._copy.rotationQuaternion = null;
  58485. this._copy.scaling.x = 1.0;
  58486. this._copy.scaling.y = 1.0;
  58487. this._copy.scaling.z = 1.0;
  58488. this._copy.uvs.x = 0;
  58489. this._copy.uvs.y = 0;
  58490. this._copy.uvs.z = 1.0;
  58491. this._copy.uvs.w = 1.0;
  58492. this._copy.color = null;
  58493. this._copy.translateFromPivot = false;
  58494. };
  58495. // _meshBuilder : inserts the shape model in the global SPS mesh
  58496. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58497. var i;
  58498. var u = 0;
  58499. var c = 0;
  58500. var n = 0;
  58501. this._resetCopy();
  58502. if (options && options.positionFunction) { // call to custom positionFunction
  58503. options.positionFunction(this._copy, idx, idxInShape);
  58504. this._mustUnrotateFixedNormals = true;
  58505. }
  58506. if (this._copy.rotationQuaternion) {
  58507. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58508. }
  58509. else {
  58510. this._yaw = this._copy.rotation.y;
  58511. this._pitch = this._copy.rotation.x;
  58512. this._roll = this._copy.rotation.z;
  58513. this._quaternionRotationYPR();
  58514. }
  58515. this._quaternionToRotationMatrix();
  58516. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58517. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58518. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58519. if (this._copy.translateFromPivot) {
  58520. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58521. }
  58522. else {
  58523. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58524. }
  58525. for (i = 0; i < shape.length; i++) {
  58526. this._vertex.x = shape[i].x;
  58527. this._vertex.y = shape[i].y;
  58528. this._vertex.z = shape[i].z;
  58529. if (options && options.vertexFunction) {
  58530. options.vertexFunction(this._copy, this._vertex, i);
  58531. }
  58532. this._vertex.x *= this._copy.scaling.x;
  58533. this._vertex.y *= this._copy.scaling.y;
  58534. this._vertex.z *= this._copy.scaling.z;
  58535. this._vertex.x -= this._scaledPivot.x;
  58536. this._vertex.y -= this._scaledPivot.y;
  58537. this._vertex.z -= this._scaledPivot.z;
  58538. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58539. this._rotated.addInPlace(this._pivotBackTranslation);
  58540. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58541. if (meshUV) {
  58542. 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);
  58543. u += 2;
  58544. }
  58545. if (this._copy.color) {
  58546. this._color = this._copy.color;
  58547. }
  58548. else if (meshCol && meshCol[c] !== undefined) {
  58549. this._color.r = meshCol[c];
  58550. this._color.g = meshCol[c + 1];
  58551. this._color.b = meshCol[c + 2];
  58552. this._color.a = meshCol[c + 3];
  58553. }
  58554. else {
  58555. this._color.r = 1.0;
  58556. this._color.g = 1.0;
  58557. this._color.b = 1.0;
  58558. this._color.a = 1.0;
  58559. }
  58560. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58561. c += 4;
  58562. if (!this.recomputeNormals && meshNor) {
  58563. this._normal.x = meshNor[n];
  58564. this._normal.y = meshNor[n + 1];
  58565. this._normal.z = meshNor[n + 2];
  58566. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58567. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58568. n += 3;
  58569. }
  58570. }
  58571. for (i = 0; i < meshInd.length; i++) {
  58572. var current_ind = p + meshInd[i];
  58573. indices.push(current_ind);
  58574. if (current_ind > 65535) {
  58575. this._needs32Bits = true;
  58576. }
  58577. }
  58578. if (this._pickable) {
  58579. var nbfaces = meshInd.length / 3;
  58580. for (i = 0; i < nbfaces; i++) {
  58581. this.pickedParticles.push({ idx: idx, faceId: i });
  58582. }
  58583. }
  58584. if (this._depthSort) {
  58585. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58586. }
  58587. return this._copy;
  58588. };
  58589. // returns a shape array from positions array
  58590. SolidParticleSystem.prototype._posToShape = function (positions) {
  58591. var shape = [];
  58592. for (var i = 0; i < positions.length; i += 3) {
  58593. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58594. }
  58595. return shape;
  58596. };
  58597. // returns a shapeUV array from a Vector4 uvs
  58598. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58599. var shapeUV = [];
  58600. if (uvs) {
  58601. for (var i = 0; i < uvs.length; i++)
  58602. shapeUV.push(uvs[i]);
  58603. }
  58604. return shapeUV;
  58605. };
  58606. // adds a new particle object in the particles array
  58607. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58608. if (bInfo === void 0) { bInfo = null; }
  58609. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58610. this.particles.push(sp);
  58611. return sp;
  58612. };
  58613. /**
  58614. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58615. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58616. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58617. * @param nb (positive integer) the number of particles to be created from this model
  58618. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58619. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58620. * @returns the number of shapes in the system
  58621. */
  58622. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58623. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58624. var meshInd = mesh.getIndices();
  58625. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58626. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58627. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58628. var bbInfo;
  58629. if (this._particlesIntersect) {
  58630. bbInfo = mesh.getBoundingInfo();
  58631. }
  58632. var shape = this._posToShape(meshPos);
  58633. var shapeUV = this._uvsToShapeUV(meshUV);
  58634. var posfunc = options ? options.positionFunction : null;
  58635. var vtxfunc = options ? options.vertexFunction : null;
  58636. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58637. // particles
  58638. var sp;
  58639. var currentCopy;
  58640. var idx = this.nbParticles;
  58641. for (var i = 0; i < nb; i++) {
  58642. var currentPos = this._positions.length;
  58643. var currentInd = this._indices.length;
  58644. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58645. if (this._updatable) {
  58646. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58647. sp.position.copyFrom(currentCopy.position);
  58648. sp.rotation.copyFrom(currentCopy.rotation);
  58649. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58650. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58651. }
  58652. if (currentCopy.color && sp.color) {
  58653. sp.color.copyFrom(currentCopy.color);
  58654. }
  58655. sp.scaling.copyFrom(currentCopy.scaling);
  58656. sp.uvs.copyFrom(currentCopy.uvs);
  58657. }
  58658. this._index += shape.length;
  58659. idx++;
  58660. }
  58661. this.nbParticles += nb;
  58662. this._shapeCounter++;
  58663. return this._shapeCounter - 1;
  58664. };
  58665. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58666. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58667. this._resetCopy();
  58668. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58669. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58670. }
  58671. if (this._copy.rotationQuaternion) {
  58672. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58673. }
  58674. else {
  58675. this._yaw = this._copy.rotation.y;
  58676. this._pitch = this._copy.rotation.x;
  58677. this._roll = this._copy.rotation.z;
  58678. this._quaternionRotationYPR();
  58679. }
  58680. this._quaternionToRotationMatrix();
  58681. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58682. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58683. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58684. if (this._copy.translateFromPivot) {
  58685. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58686. }
  58687. else {
  58688. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58689. }
  58690. this._shape = particle._model._shape;
  58691. for (var pt = 0; pt < this._shape.length; pt++) {
  58692. this._vertex.x = this._shape[pt].x;
  58693. this._vertex.y = this._shape[pt].y;
  58694. this._vertex.z = this._shape[pt].z;
  58695. if (particle._model._vertexFunction) {
  58696. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58697. }
  58698. this._vertex.x *= this._copy.scaling.x;
  58699. this._vertex.y *= this._copy.scaling.y;
  58700. this._vertex.z *= this._copy.scaling.z;
  58701. this._vertex.x -= this._scaledPivot.x;
  58702. this._vertex.y -= this._scaledPivot.y;
  58703. this._vertex.z -= this._scaledPivot.z;
  58704. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58705. this._rotated.addInPlace(this._pivotBackTranslation);
  58706. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58707. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58708. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58709. }
  58710. particle.position.x = 0.0;
  58711. particle.position.y = 0.0;
  58712. particle.position.z = 0.0;
  58713. particle.rotation.x = 0.0;
  58714. particle.rotation.y = 0.0;
  58715. particle.rotation.z = 0.0;
  58716. particle.rotationQuaternion = null;
  58717. particle.scaling.x = 1.0;
  58718. particle.scaling.y = 1.0;
  58719. particle.scaling.z = 1.0;
  58720. particle.uvs.x = 0.0;
  58721. particle.uvs.y = 0.0;
  58722. particle.uvs.z = 1.0;
  58723. particle.uvs.w = 1.0;
  58724. particle.pivot.x = 0.0;
  58725. particle.pivot.y = 0.0;
  58726. particle.pivot.z = 0.0;
  58727. particle.translateFromPivot = false;
  58728. particle.parentId = null;
  58729. };
  58730. /**
  58731. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58732. * @returns the SPS.
  58733. */
  58734. SolidParticleSystem.prototype.rebuildMesh = function () {
  58735. for (var p = 0; p < this.particles.length; p++) {
  58736. this._rebuildParticle(this.particles[p]);
  58737. }
  58738. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58739. return this;
  58740. };
  58741. /**
  58742. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58743. * This method calls `updateParticle()` for each particle of the SPS.
  58744. * For an animated SPS, it is usually called within the render loop.
  58745. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58746. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58747. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58748. * @returns the SPS.
  58749. */
  58750. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58751. if (start === void 0) { start = 0; }
  58752. if (end === void 0) { end = this.nbParticles - 1; }
  58753. if (update === void 0) { update = true; }
  58754. if (!this._updatable) {
  58755. return this;
  58756. }
  58757. // custom beforeUpdate
  58758. this.beforeUpdateParticles(start, end, update);
  58759. this._cam_axisX.x = 1.0;
  58760. this._cam_axisX.y = 0.0;
  58761. this._cam_axisX.z = 0.0;
  58762. this._cam_axisY.x = 0.0;
  58763. this._cam_axisY.y = 1.0;
  58764. this._cam_axisY.z = 0.0;
  58765. this._cam_axisZ.x = 0.0;
  58766. this._cam_axisZ.y = 0.0;
  58767. this._cam_axisZ.z = 1.0;
  58768. // cases when the World Matrix is to be computed first
  58769. if (this.billboard || this._depthSort) {
  58770. this.mesh.computeWorldMatrix(true);
  58771. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58772. }
  58773. // if the particles will always face the camera
  58774. if (this.billboard) {
  58775. // compute the camera position and un-rotate it by the current mesh rotation
  58776. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58777. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58778. this._cam_axisZ.normalize();
  58779. // same for camera up vector extracted from the cam view matrix
  58780. var view = this._camera.getViewMatrix(true);
  58781. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58782. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58783. this._cam_axisY.normalize();
  58784. this._cam_axisX.normalize();
  58785. }
  58786. // if depthSort, compute the camera global position in the mesh local system
  58787. if (this._depthSort) {
  58788. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58789. }
  58790. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58791. var idx = 0; // current position index in the global array positions32
  58792. var index = 0; // position start index in the global array positions32 of the current particle
  58793. var colidx = 0; // current color index in the global array colors32
  58794. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58795. var uvidx = 0; // current uv index in the global array uvs32
  58796. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58797. var pt = 0; // current index in the particle model shape
  58798. if (this.mesh.isFacetDataEnabled) {
  58799. this._computeBoundingBox = true;
  58800. }
  58801. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58802. if (this._computeBoundingBox) {
  58803. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58804. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58805. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58806. }
  58807. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58808. if (this.mesh._boundingInfo) {
  58809. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58810. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58811. }
  58812. }
  58813. }
  58814. // particle loop
  58815. index = this.particles[start]._pos;
  58816. var vpos = (index / 3) | 0;
  58817. colorIndex = vpos * 4;
  58818. uvIndex = vpos * 2;
  58819. for (var p = start; p <= end; p++) {
  58820. this._particle = this.particles[p];
  58821. this._shape = this._particle._model._shape;
  58822. this._shapeUV = this._particle._model._shapeUV;
  58823. // call to custom user function to update the particle properties
  58824. this.updateParticle(this._particle);
  58825. // camera-particle distance for depth sorting
  58826. if (this._depthSort && this._depthSortParticles) {
  58827. var dsp = this.depthSortedParticles[p];
  58828. dsp.ind = this._particle._ind;
  58829. dsp.indicesLength = this._particle._model._indicesLength;
  58830. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  58831. }
  58832. // skip the computations for inactive or already invisible particles
  58833. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  58834. // increment indexes for the next particle
  58835. pt = this._shape.length;
  58836. index += pt * 3;
  58837. colorIndex += pt * 4;
  58838. uvIndex += pt * 2;
  58839. continue;
  58840. }
  58841. if (this._particle.isVisible) {
  58842. this._particle._stillInvisible = false; // un-mark permanent invisibility
  58843. this._particleHasParent = (this._particle.parentId !== null);
  58844. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58845. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58846. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58847. // particle rotation matrix
  58848. if (this.billboard) {
  58849. this._particle.rotation.x = 0.0;
  58850. this._particle.rotation.y = 0.0;
  58851. }
  58852. if (this._computeParticleRotation || this.billboard) {
  58853. if (this._particle.rotationQuaternion) {
  58854. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58855. }
  58856. else {
  58857. this._yaw = this._particle.rotation.y;
  58858. this._pitch = this._particle.rotation.x;
  58859. this._roll = this._particle.rotation.z;
  58860. this._quaternionRotationYPR();
  58861. }
  58862. this._quaternionToRotationMatrix();
  58863. }
  58864. if (this._particleHasParent) {
  58865. this._parent = this.particles[this._particle.parentId];
  58866. 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];
  58867. 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];
  58868. 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];
  58869. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  58870. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  58871. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  58872. if (this._computeParticleRotation || this.billboard) {
  58873. 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];
  58874. 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];
  58875. 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];
  58876. 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];
  58877. 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];
  58878. 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];
  58879. 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];
  58880. 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];
  58881. 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];
  58882. }
  58883. }
  58884. else {
  58885. this._particle._globalPosition.x = this._particle.position.x;
  58886. this._particle._globalPosition.y = this._particle.position.y;
  58887. this._particle._globalPosition.z = this._particle.position.z;
  58888. if (this._computeParticleRotation || this.billboard) {
  58889. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  58890. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  58891. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  58892. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  58893. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  58894. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  58895. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  58896. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  58897. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  58898. }
  58899. }
  58900. if (this._particle.translateFromPivot) {
  58901. this._pivotBackTranslation.x = 0.0;
  58902. this._pivotBackTranslation.y = 0.0;
  58903. this._pivotBackTranslation.z = 0.0;
  58904. }
  58905. else {
  58906. this._pivotBackTranslation.x = this._scaledPivot.x;
  58907. this._pivotBackTranslation.y = this._scaledPivot.y;
  58908. this._pivotBackTranslation.z = this._scaledPivot.z;
  58909. }
  58910. // particle vertex loop
  58911. for (pt = 0; pt < this._shape.length; pt++) {
  58912. idx = index + pt * 3;
  58913. colidx = colorIndex + pt * 4;
  58914. uvidx = uvIndex + pt * 2;
  58915. this._vertex.x = this._shape[pt].x;
  58916. this._vertex.y = this._shape[pt].y;
  58917. this._vertex.z = this._shape[pt].z;
  58918. if (this._computeParticleVertex) {
  58919. this.updateParticleVertex(this._particle, this._vertex, pt);
  58920. }
  58921. // positions
  58922. this._vertex.x *= this._particle.scaling.x;
  58923. this._vertex.y *= this._particle.scaling.y;
  58924. this._vertex.z *= this._particle.scaling.z;
  58925. this._vertex.x -= this._scaledPivot.x;
  58926. this._vertex.y -= this._scaledPivot.y;
  58927. this._vertex.z -= this._scaledPivot.z;
  58928. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  58929. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  58930. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  58931. this._rotated.x += this._pivotBackTranslation.x;
  58932. this._rotated.y += this._pivotBackTranslation.y;
  58933. this._rotated.z += this._pivotBackTranslation.z;
  58934. 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;
  58935. 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;
  58936. 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;
  58937. if (this._computeBoundingBox) {
  58938. if (this._positions32[idx] < this._minimum.x) {
  58939. this._minimum.x = this._positions32[idx];
  58940. }
  58941. if (this._positions32[idx] > this._maximum.x) {
  58942. this._maximum.x = this._positions32[idx];
  58943. }
  58944. if (this._positions32[idx + 1] < this._minimum.y) {
  58945. this._minimum.y = this._positions32[idx + 1];
  58946. }
  58947. if (this._positions32[idx + 1] > this._maximum.y) {
  58948. this._maximum.y = this._positions32[idx + 1];
  58949. }
  58950. if (this._positions32[idx + 2] < this._minimum.z) {
  58951. this._minimum.z = this._positions32[idx + 2];
  58952. }
  58953. if (this._positions32[idx + 2] > this._maximum.z) {
  58954. this._maximum.z = this._positions32[idx + 2];
  58955. }
  58956. }
  58957. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  58958. if (!this._computeParticleVertex) {
  58959. this._normal.x = this._fixedNormal32[idx];
  58960. this._normal.y = this._fixedNormal32[idx + 1];
  58961. this._normal.z = this._fixedNormal32[idx + 2];
  58962. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  58963. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  58964. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  58965. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  58966. 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;
  58967. 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;
  58968. }
  58969. if (this._computeParticleColor && this._particle.color) {
  58970. this._colors32[colidx] = this._particle.color.r;
  58971. this._colors32[colidx + 1] = this._particle.color.g;
  58972. this._colors32[colidx + 2] = this._particle.color.b;
  58973. this._colors32[colidx + 3] = this._particle.color.a;
  58974. }
  58975. if (this._computeParticleTexture) {
  58976. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  58977. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  58978. }
  58979. }
  58980. }
  58981. // particle just set invisible : scaled to zero and positioned at the origin
  58982. else {
  58983. this._particle._stillInvisible = true; // mark the particle as invisible
  58984. for (pt = 0; pt < this._shape.length; pt++) {
  58985. idx = index + pt * 3;
  58986. colidx = colorIndex + pt * 4;
  58987. uvidx = uvIndex + pt * 2;
  58988. this._positions32[idx] = 0.0;
  58989. this._positions32[idx + 1] = 0.0;
  58990. this._positions32[idx + 2] = 0.0;
  58991. this._normals32[idx] = 0.0;
  58992. this._normals32[idx + 1] = 0.0;
  58993. this._normals32[idx + 2] = 0.0;
  58994. if (this._computeParticleColor && this._particle.color) {
  58995. this._colors32[colidx] = this._particle.color.r;
  58996. this._colors32[colidx + 1] = this._particle.color.g;
  58997. this._colors32[colidx + 2] = this._particle.color.b;
  58998. this._colors32[colidx + 3] = this._particle.color.a;
  58999. }
  59000. if (this._computeParticleTexture) {
  59001. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59002. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59003. }
  59004. }
  59005. }
  59006. // if the particle intersections must be computed : update the bbInfo
  59007. if (this._particlesIntersect) {
  59008. var bInfo = this._particle._boundingInfo;
  59009. var bBox = bInfo.boundingBox;
  59010. var bSphere = bInfo.boundingSphere;
  59011. if (!this._bSphereOnly) {
  59012. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59013. for (var b = 0; b < bBox.vectors.length; b++) {
  59014. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59015. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59016. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59017. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59018. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59019. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59020. 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;
  59021. 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;
  59022. 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;
  59023. }
  59024. bBox._update(this.mesh._worldMatrix);
  59025. }
  59026. // place and scale the particle bouding sphere in the SPS local system, then update it
  59027. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59028. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59029. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59030. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59031. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59032. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59033. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59034. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59035. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59036. 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));
  59037. bSphere._update(this.mesh._worldMatrix);
  59038. }
  59039. // increment indexes for the next particle
  59040. index = idx + 3;
  59041. colorIndex = colidx + 4;
  59042. uvIndex = uvidx + 2;
  59043. }
  59044. // if the VBO must be updated
  59045. if (update) {
  59046. if (this._computeParticleColor) {
  59047. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59048. }
  59049. if (this._computeParticleTexture) {
  59050. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59051. }
  59052. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59053. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59054. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59055. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59056. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59057. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59058. for (var i = 0; i < this._normals32.length; i++) {
  59059. this._fixedNormal32[i] = this._normals32[i];
  59060. }
  59061. }
  59062. if (!this.mesh.areNormalsFrozen) {
  59063. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59064. }
  59065. }
  59066. if (this._depthSort && this._depthSortParticles) {
  59067. this.depthSortedParticles.sort(this._depthSortFunction);
  59068. var dspl = this.depthSortedParticles.length;
  59069. var sorted = 0;
  59070. var lind = 0;
  59071. var sind = 0;
  59072. var sid = 0;
  59073. for (sorted = 0; sorted < dspl; sorted++) {
  59074. lind = this.depthSortedParticles[sorted].indicesLength;
  59075. sind = this.depthSortedParticles[sorted].ind;
  59076. for (var i = 0; i < lind; i++) {
  59077. this._indices32[sid] = this._indices[sind + i];
  59078. sid++;
  59079. }
  59080. }
  59081. this.mesh.updateIndices(this._indices32);
  59082. }
  59083. }
  59084. if (this._computeBoundingBox) {
  59085. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59086. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59087. }
  59088. this.afterUpdateParticles(start, end, update);
  59089. return this;
  59090. };
  59091. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59092. this._halfroll = this._roll * 0.5;
  59093. this._halfpitch = this._pitch * 0.5;
  59094. this._halfyaw = this._yaw * 0.5;
  59095. this._sinRoll = Math.sin(this._halfroll);
  59096. this._cosRoll = Math.cos(this._halfroll);
  59097. this._sinPitch = Math.sin(this._halfpitch);
  59098. this._cosPitch = Math.cos(this._halfpitch);
  59099. this._sinYaw = Math.sin(this._halfyaw);
  59100. this._cosYaw = Math.cos(this._halfyaw);
  59101. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59102. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59103. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59104. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59105. };
  59106. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59107. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59108. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59109. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59110. this._rotMatrix.m[3] = 0;
  59111. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59112. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59113. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59114. this._rotMatrix.m[7] = 0;
  59115. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59116. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59117. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59118. this._rotMatrix.m[11] = 0;
  59119. this._rotMatrix.m[12] = 0;
  59120. this._rotMatrix.m[13] = 0;
  59121. this._rotMatrix.m[14] = 0;
  59122. this._rotMatrix.m[15] = 1.0;
  59123. };
  59124. /**
  59125. * Disposes the SPS.
  59126. */
  59127. SolidParticleSystem.prototype.dispose = function () {
  59128. this.mesh.dispose();
  59129. this.vars = null;
  59130. // drop references to internal big arrays for the GC
  59131. this._positions = null;
  59132. this._indices = null;
  59133. this._normals = null;
  59134. this._uvs = null;
  59135. this._colors = null;
  59136. this._indices32 = null;
  59137. this._positions32 = null;
  59138. this._normals32 = null;
  59139. this._fixedNormal32 = null;
  59140. this._uvs32 = null;
  59141. this._colors32 = null;
  59142. this.pickedParticles = null;
  59143. };
  59144. /**
  59145. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59146. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59147. * @returns the SPS.
  59148. */
  59149. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59150. if (!this._isVisibilityBoxLocked) {
  59151. this.mesh.refreshBoundingInfo();
  59152. }
  59153. return this;
  59154. };
  59155. /**
  59156. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59157. * @param size the size (float) of the visibility box
  59158. * note : this doesn't lock the SPS mesh bounding box.
  59159. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59160. */
  59161. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59162. var vis = size / 2;
  59163. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59164. };
  59165. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59166. /**
  59167. * Gets whether the SPS as always visible or not
  59168. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59169. */
  59170. get: function () {
  59171. return this._alwaysVisible;
  59172. },
  59173. /**
  59174. * Sets the SPS as always visible or not
  59175. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59176. */
  59177. set: function (val) {
  59178. this._alwaysVisible = val;
  59179. this.mesh.alwaysSelectAsActiveMesh = val;
  59180. },
  59181. enumerable: true,
  59182. configurable: true
  59183. });
  59184. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59185. /**
  59186. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59187. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59188. */
  59189. get: function () {
  59190. return this._isVisibilityBoxLocked;
  59191. },
  59192. /**
  59193. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59194. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59195. */
  59196. set: function (val) {
  59197. this._isVisibilityBoxLocked = val;
  59198. var boundingInfo = this.mesh.getBoundingInfo();
  59199. boundingInfo.isLocked = val;
  59200. },
  59201. enumerable: true,
  59202. configurable: true
  59203. });
  59204. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59205. /**
  59206. * Gets if `setParticles()` computes the particle rotations or not.
  59207. * Default value : true. The SPS is faster when it's set to false.
  59208. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59209. */
  59210. get: function () {
  59211. return this._computeParticleRotation;
  59212. },
  59213. /**
  59214. * Tells to `setParticles()` to compute the particle rotations or not.
  59215. * Default value : true. The SPS is faster when it's set to false.
  59216. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59217. */
  59218. set: function (val) {
  59219. this._computeParticleRotation = val;
  59220. },
  59221. enumerable: true,
  59222. configurable: true
  59223. });
  59224. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59225. /**
  59226. * Gets if `setParticles()` computes the particle colors or not.
  59227. * Default value : true. The SPS is faster when it's set to false.
  59228. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59229. */
  59230. get: function () {
  59231. return this._computeParticleColor;
  59232. },
  59233. /**
  59234. * Tells to `setParticles()` to compute the particle colors or not.
  59235. * Default value : true. The SPS is faster when it's set to false.
  59236. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59237. */
  59238. set: function (val) {
  59239. this._computeParticleColor = val;
  59240. },
  59241. enumerable: true,
  59242. configurable: true
  59243. });
  59244. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59245. /**
  59246. * Gets if `setParticles()` computes the particle textures or not.
  59247. * Default value : true. The SPS is faster when it's set to false.
  59248. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59249. */
  59250. get: function () {
  59251. return this._computeParticleTexture;
  59252. },
  59253. set: function (val) {
  59254. this._computeParticleTexture = val;
  59255. },
  59256. enumerable: true,
  59257. configurable: true
  59258. });
  59259. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59260. /**
  59261. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59262. * Default value : false. The SPS is faster when it's set to false.
  59263. * Note : the particle custom vertex positions aren't stored values.
  59264. */
  59265. get: function () {
  59266. return this._computeParticleVertex;
  59267. },
  59268. /**
  59269. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59270. * Default value : false. The SPS is faster when it's set to false.
  59271. * Note : the particle custom vertex positions aren't stored values.
  59272. */
  59273. set: function (val) {
  59274. this._computeParticleVertex = val;
  59275. },
  59276. enumerable: true,
  59277. configurable: true
  59278. });
  59279. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59280. /**
  59281. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59282. */
  59283. get: function () {
  59284. return this._computeBoundingBox;
  59285. },
  59286. /**
  59287. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59288. */
  59289. set: function (val) {
  59290. this._computeBoundingBox = val;
  59291. },
  59292. enumerable: true,
  59293. configurable: true
  59294. });
  59295. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59296. /**
  59297. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59298. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59299. * Default : `true`
  59300. */
  59301. get: function () {
  59302. return this._depthSortParticles;
  59303. },
  59304. /**
  59305. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59306. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59307. * Default : `true`
  59308. */
  59309. set: function (val) {
  59310. this._depthSortParticles = val;
  59311. },
  59312. enumerable: true,
  59313. configurable: true
  59314. });
  59315. // =======================================================================
  59316. // Particle behavior logic
  59317. // these following methods may be overwritten by the user to fit his needs
  59318. /**
  59319. * This function does nothing. It may be overwritten to set all the particle first values.
  59320. * The SPS doesn't call this function, you may have to call it by your own.
  59321. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59322. */
  59323. SolidParticleSystem.prototype.initParticles = function () {
  59324. };
  59325. /**
  59326. * This function does nothing. It may be overwritten to recycle a particle.
  59327. * The SPS doesn't call this function, you may have to call it by your own.
  59328. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59329. * @param particle The particle to recycle
  59330. * @returns the recycled particle
  59331. */
  59332. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59333. return particle;
  59334. };
  59335. /**
  59336. * Updates a particle : this function should be overwritten by the user.
  59337. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59338. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59339. * @example : just set a particle position or velocity and recycle conditions
  59340. * @param particle The particle to update
  59341. * @returns the updated particle
  59342. */
  59343. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59344. return particle;
  59345. };
  59346. /**
  59347. * Updates a vertex of a particle : it can be overwritten by the user.
  59348. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59349. * @param particle the current particle
  59350. * @param vertex the current index of the current particle
  59351. * @param pt the index of the current vertex in the particle shape
  59352. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59353. * @example : just set a vertex particle position
  59354. * @returns the updated vertex
  59355. */
  59356. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59357. return vertex;
  59358. };
  59359. /**
  59360. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59361. * This does nothing and may be overwritten by the user.
  59362. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59363. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59364. * @param update the boolean update value actually passed to setParticles()
  59365. */
  59366. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59367. };
  59368. /**
  59369. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59370. * This will be passed three parameters.
  59371. * This does nothing and may be overwritten by the user.
  59372. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59373. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59374. * @param update the boolean update value actually passed to setParticles()
  59375. */
  59376. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59377. };
  59378. return SolidParticleSystem;
  59379. }());
  59380. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59381. })(BABYLON || (BABYLON = {}));
  59382. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59383. var BABYLON;
  59384. (function (BABYLON) {
  59385. var ShaderMaterial = /** @class */ (function (_super) {
  59386. __extends(ShaderMaterial, _super);
  59387. function ShaderMaterial(name, scene, shaderPath, options) {
  59388. var _this = _super.call(this, name, scene) || this;
  59389. _this._textures = {};
  59390. _this._textureArrays = {};
  59391. _this._floats = {};
  59392. _this._ints = {};
  59393. _this._floatsArrays = {};
  59394. _this._colors3 = {};
  59395. _this._colors3Arrays = {};
  59396. _this._colors4 = {};
  59397. _this._vectors2 = {};
  59398. _this._vectors3 = {};
  59399. _this._vectors4 = {};
  59400. _this._matrices = {};
  59401. _this._matrices3x3 = {};
  59402. _this._matrices2x2 = {};
  59403. _this._vectors2Arrays = {};
  59404. _this._vectors3Arrays = {};
  59405. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59406. _this._shaderPath = shaderPath;
  59407. options.needAlphaBlending = options.needAlphaBlending || false;
  59408. options.needAlphaTesting = options.needAlphaTesting || false;
  59409. options.attributes = options.attributes || ["position", "normal", "uv"];
  59410. options.uniforms = options.uniforms || ["worldViewProjection"];
  59411. options.uniformBuffers = options.uniformBuffers || [];
  59412. options.samplers = options.samplers || [];
  59413. options.defines = options.defines || [];
  59414. _this._options = options;
  59415. return _this;
  59416. }
  59417. ShaderMaterial.prototype.getClassName = function () {
  59418. return "ShaderMaterial";
  59419. };
  59420. ShaderMaterial.prototype.needAlphaBlending = function () {
  59421. return this._options.needAlphaBlending;
  59422. };
  59423. ShaderMaterial.prototype.needAlphaTesting = function () {
  59424. return this._options.needAlphaTesting;
  59425. };
  59426. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59427. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59428. this._options.uniforms.push(uniformName);
  59429. }
  59430. };
  59431. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59432. if (this._options.samplers.indexOf(name) === -1) {
  59433. this._options.samplers.push(name);
  59434. }
  59435. this._textures[name] = texture;
  59436. return this;
  59437. };
  59438. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59439. if (this._options.samplers.indexOf(name) === -1) {
  59440. this._options.samplers.push(name);
  59441. }
  59442. this._checkUniform(name);
  59443. this._textureArrays[name] = textures;
  59444. return this;
  59445. };
  59446. ShaderMaterial.prototype.setFloat = function (name, value) {
  59447. this._checkUniform(name);
  59448. this._floats[name] = value;
  59449. return this;
  59450. };
  59451. ShaderMaterial.prototype.setInt = function (name, value) {
  59452. this._checkUniform(name);
  59453. this._ints[name] = value;
  59454. return this;
  59455. };
  59456. ShaderMaterial.prototype.setFloats = function (name, value) {
  59457. this._checkUniform(name);
  59458. this._floatsArrays[name] = value;
  59459. return this;
  59460. };
  59461. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59462. this._checkUniform(name);
  59463. this._colors3[name] = value;
  59464. return this;
  59465. };
  59466. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59467. this._checkUniform(name);
  59468. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59469. color.toArray(arr, arr.length);
  59470. return arr;
  59471. }, []);
  59472. return this;
  59473. };
  59474. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59475. this._checkUniform(name);
  59476. this._colors4[name] = value;
  59477. return this;
  59478. };
  59479. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59480. this._checkUniform(name);
  59481. this._vectors2[name] = value;
  59482. return this;
  59483. };
  59484. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59485. this._checkUniform(name);
  59486. this._vectors3[name] = value;
  59487. return this;
  59488. };
  59489. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59490. this._checkUniform(name);
  59491. this._vectors4[name] = value;
  59492. return this;
  59493. };
  59494. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59495. this._checkUniform(name);
  59496. this._matrices[name] = value;
  59497. return this;
  59498. };
  59499. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59500. this._checkUniform(name);
  59501. this._matrices3x3[name] = value;
  59502. return this;
  59503. };
  59504. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59505. this._checkUniform(name);
  59506. this._matrices2x2[name] = value;
  59507. return this;
  59508. };
  59509. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59510. this._checkUniform(name);
  59511. this._vectors2Arrays[name] = value;
  59512. return this;
  59513. };
  59514. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59515. this._checkUniform(name);
  59516. this._vectors3Arrays[name] = value;
  59517. return this;
  59518. };
  59519. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59520. if (!mesh) {
  59521. return true;
  59522. }
  59523. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59524. return false;
  59525. }
  59526. return false;
  59527. };
  59528. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59529. var scene = this.getScene();
  59530. var engine = scene.getEngine();
  59531. if (!this.checkReadyOnEveryCall) {
  59532. if (this._renderId === scene.getRenderId()) {
  59533. if (this._checkCache(scene, mesh, useInstances)) {
  59534. return true;
  59535. }
  59536. }
  59537. }
  59538. // Instances
  59539. var defines = [];
  59540. var attribs = [];
  59541. var fallbacks = new BABYLON.EffectFallbacks();
  59542. if (useInstances) {
  59543. defines.push("#define INSTANCES");
  59544. }
  59545. for (var index = 0; index < this._options.defines.length; index++) {
  59546. defines.push(this._options.defines[index]);
  59547. }
  59548. for (var index = 0; index < this._options.attributes.length; index++) {
  59549. attribs.push(this._options.attributes[index]);
  59550. }
  59551. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59552. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59553. defines.push("#define VERTEXCOLOR");
  59554. }
  59555. // Bones
  59556. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59557. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59558. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59559. if (mesh.numBoneInfluencers > 4) {
  59560. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59561. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59562. }
  59563. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59564. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59565. fallbacks.addCPUSkinningFallback(0, mesh);
  59566. if (this._options.uniforms.indexOf("mBones") === -1) {
  59567. this._options.uniforms.push("mBones");
  59568. }
  59569. }
  59570. else {
  59571. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59572. }
  59573. // Textures
  59574. for (var name in this._textures) {
  59575. if (!this._textures[name].isReady()) {
  59576. return false;
  59577. }
  59578. }
  59579. // Alpha test
  59580. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59581. defines.push("#define ALPHATEST");
  59582. }
  59583. var previousEffect = this._effect;
  59584. var join = defines.join("\n");
  59585. this._effect = engine.createEffect(this._shaderPath, {
  59586. attributes: attribs,
  59587. uniformsNames: this._options.uniforms,
  59588. uniformBuffersNames: this._options.uniformBuffers,
  59589. samplers: this._options.samplers,
  59590. defines: join,
  59591. fallbacks: fallbacks,
  59592. onCompiled: this.onCompiled,
  59593. onError: this.onError
  59594. }, engine);
  59595. if (!this._effect.isReady()) {
  59596. return false;
  59597. }
  59598. if (previousEffect !== this._effect) {
  59599. scene.resetCachedMaterial();
  59600. }
  59601. this._renderId = scene.getRenderId();
  59602. return true;
  59603. };
  59604. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59605. var scene = this.getScene();
  59606. if (!this._effect) {
  59607. return;
  59608. }
  59609. if (this._options.uniforms.indexOf("world") !== -1) {
  59610. this._effect.setMatrix("world", world);
  59611. }
  59612. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59613. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59614. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59615. }
  59616. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59617. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59618. }
  59619. };
  59620. ShaderMaterial.prototype.bind = function (world, mesh) {
  59621. // Std values
  59622. this.bindOnlyWorldMatrix(world);
  59623. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59624. if (this._options.uniforms.indexOf("view") !== -1) {
  59625. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59626. }
  59627. if (this._options.uniforms.indexOf("projection") !== -1) {
  59628. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59629. }
  59630. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59631. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59632. }
  59633. // Bones
  59634. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59635. var name;
  59636. // Texture
  59637. for (name in this._textures) {
  59638. this._effect.setTexture(name, this._textures[name]);
  59639. }
  59640. // Texture arrays
  59641. for (name in this._textureArrays) {
  59642. this._effect.setTextureArray(name, this._textureArrays[name]);
  59643. }
  59644. // Int
  59645. for (name in this._ints) {
  59646. this._effect.setInt(name, this._ints[name]);
  59647. }
  59648. // Float
  59649. for (name in this._floats) {
  59650. this._effect.setFloat(name, this._floats[name]);
  59651. }
  59652. // Floats
  59653. for (name in this._floatsArrays) {
  59654. this._effect.setArray(name, this._floatsArrays[name]);
  59655. }
  59656. // Color3
  59657. for (name in this._colors3) {
  59658. this._effect.setColor3(name, this._colors3[name]);
  59659. }
  59660. for (name in this._colors3Arrays) {
  59661. this._effect.setArray3(name, this._colors3Arrays[name]);
  59662. }
  59663. // Color4
  59664. for (name in this._colors4) {
  59665. var color = this._colors4[name];
  59666. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59667. }
  59668. // Vector2
  59669. for (name in this._vectors2) {
  59670. this._effect.setVector2(name, this._vectors2[name]);
  59671. }
  59672. // Vector3
  59673. for (name in this._vectors3) {
  59674. this._effect.setVector3(name, this._vectors3[name]);
  59675. }
  59676. // Vector4
  59677. for (name in this._vectors4) {
  59678. this._effect.setVector4(name, this._vectors4[name]);
  59679. }
  59680. // Matrix
  59681. for (name in this._matrices) {
  59682. this._effect.setMatrix(name, this._matrices[name]);
  59683. }
  59684. // Matrix 3x3
  59685. for (name in this._matrices3x3) {
  59686. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59687. }
  59688. // Matrix 2x2
  59689. for (name in this._matrices2x2) {
  59690. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59691. }
  59692. // Vector2Array
  59693. for (name in this._vectors2Arrays) {
  59694. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59695. }
  59696. // Vector3Array
  59697. for (name in this._vectors3Arrays) {
  59698. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59699. }
  59700. }
  59701. this._afterBind(mesh);
  59702. };
  59703. ShaderMaterial.prototype.getActiveTextures = function () {
  59704. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59705. for (var name in this._textures) {
  59706. activeTextures.push(this._textures[name]);
  59707. }
  59708. for (var name in this._textureArrays) {
  59709. var array = this._textureArrays[name];
  59710. for (var index = 0; index < array.length; index++) {
  59711. activeTextures.push(array[index]);
  59712. }
  59713. }
  59714. return activeTextures;
  59715. };
  59716. ShaderMaterial.prototype.hasTexture = function (texture) {
  59717. if (_super.prototype.hasTexture.call(this, texture)) {
  59718. return true;
  59719. }
  59720. for (var name in this._textures) {
  59721. if (this._textures[name] === texture) {
  59722. return true;
  59723. }
  59724. }
  59725. for (var name in this._textureArrays) {
  59726. var array = this._textureArrays[name];
  59727. for (var index = 0; index < array.length; index++) {
  59728. if (array[index] === texture) {
  59729. return true;
  59730. }
  59731. }
  59732. }
  59733. return false;
  59734. };
  59735. ShaderMaterial.prototype.clone = function (name) {
  59736. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59737. return newShaderMaterial;
  59738. };
  59739. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59740. if (forceDisposeTextures) {
  59741. var name;
  59742. for (name in this._textures) {
  59743. this._textures[name].dispose();
  59744. }
  59745. for (name in this._textureArrays) {
  59746. var array = this._textureArrays[name];
  59747. for (var index = 0; index < array.length; index++) {
  59748. array[index].dispose();
  59749. }
  59750. }
  59751. }
  59752. this._textures = {};
  59753. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59754. };
  59755. ShaderMaterial.prototype.serialize = function () {
  59756. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59757. serializationObject.customType = "BABYLON.ShaderMaterial";
  59758. serializationObject.options = this._options;
  59759. serializationObject.shaderPath = this._shaderPath;
  59760. var name;
  59761. // Texture
  59762. serializationObject.textures = {};
  59763. for (name in this._textures) {
  59764. serializationObject.textures[name] = this._textures[name].serialize();
  59765. }
  59766. // Texture arrays
  59767. serializationObject.textureArrays = {};
  59768. for (name in this._textureArrays) {
  59769. serializationObject.textureArrays[name] = [];
  59770. var array = this._textureArrays[name];
  59771. for (var index = 0; index < array.length; index++) {
  59772. serializationObject.textureArrays[name].push(array[index].serialize());
  59773. }
  59774. }
  59775. // Float
  59776. serializationObject.floats = {};
  59777. for (name in this._floats) {
  59778. serializationObject.floats[name] = this._floats[name];
  59779. }
  59780. // Float s
  59781. serializationObject.FloatArrays = {};
  59782. for (name in this._floatsArrays) {
  59783. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59784. }
  59785. // Color3
  59786. serializationObject.colors3 = {};
  59787. for (name in this._colors3) {
  59788. serializationObject.colors3[name] = this._colors3[name].asArray();
  59789. }
  59790. // Color3 array
  59791. serializationObject.colors3Arrays = {};
  59792. for (name in this._colors3Arrays) {
  59793. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59794. }
  59795. // Color4
  59796. serializationObject.colors4 = {};
  59797. for (name in this._colors4) {
  59798. serializationObject.colors4[name] = this._colors4[name].asArray();
  59799. }
  59800. // Vector2
  59801. serializationObject.vectors2 = {};
  59802. for (name in this._vectors2) {
  59803. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59804. }
  59805. // Vector3
  59806. serializationObject.vectors3 = {};
  59807. for (name in this._vectors3) {
  59808. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59809. }
  59810. // Vector4
  59811. serializationObject.vectors4 = {};
  59812. for (name in this._vectors4) {
  59813. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59814. }
  59815. // Matrix
  59816. serializationObject.matrices = {};
  59817. for (name in this._matrices) {
  59818. serializationObject.matrices[name] = this._matrices[name].asArray();
  59819. }
  59820. // Matrix 3x3
  59821. serializationObject.matrices3x3 = {};
  59822. for (name in this._matrices3x3) {
  59823. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  59824. }
  59825. // Matrix 2x2
  59826. serializationObject.matrices2x2 = {};
  59827. for (name in this._matrices2x2) {
  59828. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  59829. }
  59830. // Vector2Array
  59831. serializationObject.vectors2Arrays = {};
  59832. for (name in this._vectors2Arrays) {
  59833. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  59834. }
  59835. // Vector3Array
  59836. serializationObject.vectors3Arrays = {};
  59837. for (name in this._vectors3Arrays) {
  59838. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  59839. }
  59840. return serializationObject;
  59841. };
  59842. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  59843. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  59844. var name;
  59845. // Texture
  59846. for (name in source.textures) {
  59847. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  59848. }
  59849. // Texture arrays
  59850. for (name in source.textureArrays) {
  59851. var array = source.textureArrays[name];
  59852. var textureArray = new Array();
  59853. for (var index = 0; index < array.length; index++) {
  59854. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  59855. }
  59856. material.setTextureArray(name, textureArray);
  59857. }
  59858. // Float
  59859. for (name in source.floats) {
  59860. material.setFloat(name, source.floats[name]);
  59861. }
  59862. // Float s
  59863. for (name in source.floatsArrays) {
  59864. material.setFloats(name, source.floatsArrays[name]);
  59865. }
  59866. // Color3
  59867. for (name in source.colors3) {
  59868. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  59869. }
  59870. // Color3 arrays
  59871. for (name in source.colors3Arrays) {
  59872. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  59873. if (i % 3 === 0) {
  59874. arr.push([num]);
  59875. }
  59876. else {
  59877. arr[arr.length - 1].push(num);
  59878. }
  59879. return arr;
  59880. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  59881. material.setColor3Array(name, colors);
  59882. }
  59883. // Color4
  59884. for (name in source.colors4) {
  59885. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  59886. }
  59887. // Vector2
  59888. for (name in source.vectors2) {
  59889. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  59890. }
  59891. // Vector3
  59892. for (name in source.vectors3) {
  59893. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  59894. }
  59895. // Vector4
  59896. for (name in source.vectors4) {
  59897. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  59898. }
  59899. // Matrix
  59900. for (name in source.matrices) {
  59901. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  59902. }
  59903. // Matrix 3x3
  59904. for (name in source.matrices3x3) {
  59905. material.setMatrix3x3(name, source.matrices3x3[name]);
  59906. }
  59907. // Matrix 2x2
  59908. for (name in source.matrices2x2) {
  59909. material.setMatrix2x2(name, source.matrices2x2[name]);
  59910. }
  59911. // Vector2Array
  59912. for (name in source.vectors2Arrays) {
  59913. material.setArray2(name, source.vectors2Arrays[name]);
  59914. }
  59915. // Vector3Array
  59916. for (name in source.vectors3Arrays) {
  59917. material.setArray3(name, source.vectors3Arrays[name]);
  59918. }
  59919. return material;
  59920. };
  59921. return ShaderMaterial;
  59922. }(BABYLON.Material));
  59923. BABYLON.ShaderMaterial = ShaderMaterial;
  59924. })(BABYLON || (BABYLON = {}));
  59925. //# sourceMappingURL=babylon.shaderMaterial.js.map
  59926. var BABYLON;
  59927. (function (BABYLON) {
  59928. var GroundMesh = /** @class */ (function (_super) {
  59929. __extends(GroundMesh, _super);
  59930. function GroundMesh(name, scene) {
  59931. var _this = _super.call(this, name, scene) || this;
  59932. _this.generateOctree = false;
  59933. return _this;
  59934. }
  59935. GroundMesh.prototype.getClassName = function () {
  59936. return "GroundMesh";
  59937. };
  59938. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  59939. get: function () {
  59940. return Math.min(this._subdivisionsX, this._subdivisionsY);
  59941. },
  59942. enumerable: true,
  59943. configurable: true
  59944. });
  59945. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  59946. get: function () {
  59947. return this._subdivisionsX;
  59948. },
  59949. enumerable: true,
  59950. configurable: true
  59951. });
  59952. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  59953. get: function () {
  59954. return this._subdivisionsY;
  59955. },
  59956. enumerable: true,
  59957. configurable: true
  59958. });
  59959. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  59960. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  59961. this._subdivisionsX = chunksCount;
  59962. this._subdivisionsY = chunksCount;
  59963. this.subdivide(chunksCount);
  59964. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  59965. };
  59966. /**
  59967. * Returns a height (y) value in the Worl system :
  59968. * the ground altitude at the coordinates (x, z) expressed in the World system.
  59969. * Returns the ground y position if (x, z) are outside the ground surface.
  59970. */
  59971. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  59972. var world = this.getWorldMatrix();
  59973. var invMat = BABYLON.Tmp.Matrix[5];
  59974. world.invertToRef(invMat);
  59975. var tmpVect = BABYLON.Tmp.Vector3[8];
  59976. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  59977. x = tmpVect.x;
  59978. z = tmpVect.z;
  59979. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  59980. return this.position.y;
  59981. }
  59982. if (!this._heightQuads || this._heightQuads.length == 0) {
  59983. this._initHeightQuads();
  59984. this._computeHeightQuads();
  59985. }
  59986. var facet = this._getFacetAt(x, z);
  59987. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  59988. // return y in the World system
  59989. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  59990. return tmpVect.y;
  59991. };
  59992. /**
  59993. * Returns a normalized vector (Vector3) orthogonal to the ground
  59994. * at the ground coordinates (x, z) expressed in the World system.
  59995. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  59996. */
  59997. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  59998. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  59999. this.getNormalAtCoordinatesToRef(x, z, normal);
  60000. return normal;
  60001. };
  60002. /**
  60003. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60004. * at the ground coordinates (x, z) expressed in the World system.
  60005. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60006. * Returns the GroundMesh.
  60007. */
  60008. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60009. var world = this.getWorldMatrix();
  60010. var tmpMat = BABYLON.Tmp.Matrix[5];
  60011. world.invertToRef(tmpMat);
  60012. var tmpVect = BABYLON.Tmp.Vector3[8];
  60013. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60014. x = tmpVect.x;
  60015. z = tmpVect.z;
  60016. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60017. return this;
  60018. }
  60019. if (!this._heightQuads || this._heightQuads.length == 0) {
  60020. this._initHeightQuads();
  60021. this._computeHeightQuads();
  60022. }
  60023. var facet = this._getFacetAt(x, z);
  60024. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60025. return this;
  60026. };
  60027. /**
  60028. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60029. * if the ground has been updated.
  60030. * This can be used in the render loop.
  60031. * Returns the GroundMesh.
  60032. */
  60033. GroundMesh.prototype.updateCoordinateHeights = function () {
  60034. if (!this._heightQuads || this._heightQuads.length == 0) {
  60035. this._initHeightQuads();
  60036. }
  60037. this._computeHeightQuads();
  60038. return this;
  60039. };
  60040. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60041. GroundMesh.prototype._getFacetAt = function (x, z) {
  60042. // retrieve col and row from x, z coordinates in the ground local system
  60043. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60044. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60045. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60046. var facet;
  60047. if (z < quad.slope.x * x + quad.slope.y) {
  60048. facet = quad.facet1;
  60049. }
  60050. else {
  60051. facet = quad.facet2;
  60052. }
  60053. return facet;
  60054. };
  60055. // Creates and populates the heightMap array with "facet" elements :
  60056. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60057. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60058. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60059. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60060. // Returns the GroundMesh.
  60061. GroundMesh.prototype._initHeightQuads = function () {
  60062. var subdivisionsX = this._subdivisionsX;
  60063. var subdivisionsY = this._subdivisionsY;
  60064. this._heightQuads = new Array();
  60065. for (var row = 0; row < subdivisionsY; row++) {
  60066. for (var col = 0; col < subdivisionsX; col++) {
  60067. 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) };
  60068. this._heightQuads[row * subdivisionsX + col] = quad;
  60069. }
  60070. }
  60071. return this;
  60072. };
  60073. // Compute each quad element values and update the the heightMap array :
  60074. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60075. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60076. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60077. // Returns the GroundMesh.
  60078. GroundMesh.prototype._computeHeightQuads = function () {
  60079. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60080. if (!positions) {
  60081. return this;
  60082. }
  60083. var v1 = BABYLON.Tmp.Vector3[3];
  60084. var v2 = BABYLON.Tmp.Vector3[2];
  60085. var v3 = BABYLON.Tmp.Vector3[1];
  60086. var v4 = BABYLON.Tmp.Vector3[0];
  60087. var v1v2 = BABYLON.Tmp.Vector3[4];
  60088. var v1v3 = BABYLON.Tmp.Vector3[5];
  60089. var v1v4 = BABYLON.Tmp.Vector3[6];
  60090. var norm1 = BABYLON.Tmp.Vector3[7];
  60091. var norm2 = BABYLON.Tmp.Vector3[8];
  60092. var i = 0;
  60093. var j = 0;
  60094. var k = 0;
  60095. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60096. var h = 0;
  60097. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60098. var d2 = 0;
  60099. var subdivisionsX = this._subdivisionsX;
  60100. var subdivisionsY = this._subdivisionsY;
  60101. for (var row = 0; row < subdivisionsY; row++) {
  60102. for (var col = 0; col < subdivisionsX; col++) {
  60103. i = col * 3;
  60104. j = row * (subdivisionsX + 1) * 3;
  60105. k = (row + 1) * (subdivisionsX + 1) * 3;
  60106. v1.x = positions[j + i];
  60107. v1.y = positions[j + i + 1];
  60108. v1.z = positions[j + i + 2];
  60109. v2.x = positions[j + i + 3];
  60110. v2.y = positions[j + i + 4];
  60111. v2.z = positions[j + i + 5];
  60112. v3.x = positions[k + i];
  60113. v3.y = positions[k + i + 1];
  60114. v3.z = positions[k + i + 2];
  60115. v4.x = positions[k + i + 3];
  60116. v4.y = positions[k + i + 4];
  60117. v4.z = positions[k + i + 5];
  60118. // 2D slope V1V4
  60119. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60120. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60121. // facet equations :
  60122. // we compute each facet normal vector
  60123. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60124. // we compute the value d by applying the equation to v1 which belongs to the plane
  60125. // then we store the facet equation in a Vector4
  60126. v2.subtractToRef(v1, v1v2);
  60127. v3.subtractToRef(v1, v1v3);
  60128. v4.subtractToRef(v1, v1v4);
  60129. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60130. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60131. norm1.normalize();
  60132. norm2.normalize();
  60133. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60134. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60135. var quad = this._heightQuads[row * subdivisionsX + col];
  60136. quad.slope.copyFromFloats(cd, h);
  60137. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60138. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60139. }
  60140. }
  60141. return this;
  60142. };
  60143. GroundMesh.prototype.serialize = function (serializationObject) {
  60144. _super.prototype.serialize.call(this, serializationObject);
  60145. serializationObject.subdivisionsX = this._subdivisionsX;
  60146. serializationObject.subdivisionsY = this._subdivisionsY;
  60147. serializationObject.minX = this._minX;
  60148. serializationObject.maxX = this._maxX;
  60149. serializationObject.minZ = this._minZ;
  60150. serializationObject.maxZ = this._maxZ;
  60151. serializationObject.width = this._width;
  60152. serializationObject.height = this._height;
  60153. };
  60154. GroundMesh.Parse = function (parsedMesh, scene) {
  60155. var result = new GroundMesh(parsedMesh.name, scene);
  60156. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60157. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60158. result._minX = parsedMesh.minX;
  60159. result._maxX = parsedMesh.maxX;
  60160. result._minZ = parsedMesh.minZ;
  60161. result._maxZ = parsedMesh.maxZ;
  60162. result._width = parsedMesh.width;
  60163. result._height = parsedMesh.height;
  60164. return result;
  60165. };
  60166. return GroundMesh;
  60167. }(BABYLON.Mesh));
  60168. BABYLON.GroundMesh = GroundMesh;
  60169. })(BABYLON || (BABYLON = {}));
  60170. //# sourceMappingURL=babylon.groundMesh.js.map
  60171. var BABYLON;
  60172. (function (BABYLON) {
  60173. /**
  60174. * Creates an instance based on a source mesh.
  60175. */
  60176. var InstancedMesh = /** @class */ (function (_super) {
  60177. __extends(InstancedMesh, _super);
  60178. function InstancedMesh(name, source) {
  60179. var _this = _super.call(this, name, source.getScene()) || this;
  60180. source.instances.push(_this);
  60181. _this._sourceMesh = source;
  60182. _this.position.copyFrom(source.position);
  60183. _this.rotation.copyFrom(source.rotation);
  60184. _this.scaling.copyFrom(source.scaling);
  60185. if (source.rotationQuaternion) {
  60186. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60187. }
  60188. _this.infiniteDistance = source.infiniteDistance;
  60189. _this.setPivotMatrix(source.getPivotMatrix());
  60190. _this.refreshBoundingInfo();
  60191. _this._syncSubMeshes();
  60192. return _this;
  60193. }
  60194. /**
  60195. * Returns the string "InstancedMesh".
  60196. */
  60197. InstancedMesh.prototype.getClassName = function () {
  60198. return "InstancedMesh";
  60199. };
  60200. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60201. // Methods
  60202. get: function () {
  60203. return this._sourceMesh.receiveShadows;
  60204. },
  60205. enumerable: true,
  60206. configurable: true
  60207. });
  60208. Object.defineProperty(InstancedMesh.prototype, "material", {
  60209. get: function () {
  60210. return this._sourceMesh.material;
  60211. },
  60212. enumerable: true,
  60213. configurable: true
  60214. });
  60215. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60216. get: function () {
  60217. return this._sourceMesh.visibility;
  60218. },
  60219. enumerable: true,
  60220. configurable: true
  60221. });
  60222. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60223. get: function () {
  60224. return this._sourceMesh.skeleton;
  60225. },
  60226. enumerable: true,
  60227. configurable: true
  60228. });
  60229. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60230. get: function () {
  60231. return this._sourceMesh.renderingGroupId;
  60232. },
  60233. set: function (value) {
  60234. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60235. return;
  60236. }
  60237. //no-op with warning
  60238. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60239. },
  60240. enumerable: true,
  60241. configurable: true
  60242. });
  60243. /**
  60244. * Returns the total number of vertices (integer).
  60245. */
  60246. InstancedMesh.prototype.getTotalVertices = function () {
  60247. return this._sourceMesh.getTotalVertices();
  60248. };
  60249. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60250. get: function () {
  60251. return this._sourceMesh;
  60252. },
  60253. enumerable: true,
  60254. configurable: true
  60255. });
  60256. /**
  60257. * Is this node ready to be used/rendered
  60258. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60259. * @return {boolean} is it ready
  60260. */
  60261. InstancedMesh.prototype.isReady = function (completeCheck) {
  60262. if (completeCheck === void 0) { completeCheck = false; }
  60263. return this._sourceMesh.isReady(completeCheck, true);
  60264. };
  60265. /**
  60266. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60267. */
  60268. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60269. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60270. };
  60271. /**
  60272. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60273. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60274. * The `data` are either a numeric array either a Float32Array.
  60275. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60276. * 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).
  60277. * Note that a new underlying VertexBuffer object is created each call.
  60278. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60279. *
  60280. * Possible `kind` values :
  60281. * - BABYLON.VertexBuffer.PositionKind
  60282. * - BABYLON.VertexBuffer.UVKind
  60283. * - BABYLON.VertexBuffer.UV2Kind
  60284. * - BABYLON.VertexBuffer.UV3Kind
  60285. * - BABYLON.VertexBuffer.UV4Kind
  60286. * - BABYLON.VertexBuffer.UV5Kind
  60287. * - BABYLON.VertexBuffer.UV6Kind
  60288. * - BABYLON.VertexBuffer.ColorKind
  60289. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60290. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60291. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60292. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60293. *
  60294. * Returns the Mesh.
  60295. */
  60296. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60297. if (this.sourceMesh) {
  60298. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60299. }
  60300. return this.sourceMesh;
  60301. };
  60302. /**
  60303. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60304. * If the mesh has no geometry, it is simply returned as it is.
  60305. * The `data` are either a numeric array either a Float32Array.
  60306. * No new underlying VertexBuffer object is created.
  60307. * 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.
  60308. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60309. *
  60310. * Possible `kind` values :
  60311. * - BABYLON.VertexBuffer.PositionKind
  60312. * - BABYLON.VertexBuffer.UVKind
  60313. * - BABYLON.VertexBuffer.UV2Kind
  60314. * - BABYLON.VertexBuffer.UV3Kind
  60315. * - BABYLON.VertexBuffer.UV4Kind
  60316. * - BABYLON.VertexBuffer.UV5Kind
  60317. * - BABYLON.VertexBuffer.UV6Kind
  60318. * - BABYLON.VertexBuffer.ColorKind
  60319. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60320. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60321. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60322. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60323. *
  60324. * Returns the Mesh.
  60325. */
  60326. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60327. if (this.sourceMesh) {
  60328. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60329. }
  60330. return this.sourceMesh;
  60331. };
  60332. /**
  60333. * Sets the mesh indices.
  60334. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60335. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60336. * This method creates a new index buffer each call.
  60337. * Returns the Mesh.
  60338. */
  60339. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60340. if (totalVertices === void 0) { totalVertices = null; }
  60341. if (this.sourceMesh) {
  60342. this.sourceMesh.setIndices(indices, totalVertices);
  60343. }
  60344. return this.sourceMesh;
  60345. };
  60346. /**
  60347. * Boolean : True if the mesh owns the requested kind of data.
  60348. */
  60349. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60350. return this._sourceMesh.isVerticesDataPresent(kind);
  60351. };
  60352. /**
  60353. * Returns an array of indices (IndicesArray).
  60354. */
  60355. InstancedMesh.prototype.getIndices = function () {
  60356. return this._sourceMesh.getIndices();
  60357. };
  60358. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60359. get: function () {
  60360. return this._sourceMesh._positions;
  60361. },
  60362. enumerable: true,
  60363. configurable: true
  60364. });
  60365. /**
  60366. * Sets a new updated BoundingInfo to the mesh.
  60367. * Returns the mesh.
  60368. */
  60369. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60370. var meshBB = this._sourceMesh.getBoundingInfo();
  60371. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60372. this._updateBoundingInfo();
  60373. return this;
  60374. };
  60375. InstancedMesh.prototype._preActivate = function () {
  60376. if (this._currentLOD) {
  60377. this._currentLOD._preActivate();
  60378. }
  60379. return this;
  60380. };
  60381. InstancedMesh.prototype._activate = function (renderId) {
  60382. if (this._currentLOD) {
  60383. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60384. }
  60385. return this;
  60386. };
  60387. /**
  60388. * Returns the current associated LOD AbstractMesh.
  60389. */
  60390. InstancedMesh.prototype.getLOD = function (camera) {
  60391. if (!camera) {
  60392. return this;
  60393. }
  60394. var boundingInfo = this.getBoundingInfo();
  60395. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60396. if (this._currentLOD === this.sourceMesh) {
  60397. return this;
  60398. }
  60399. return this._currentLOD;
  60400. };
  60401. InstancedMesh.prototype._syncSubMeshes = function () {
  60402. this.releaseSubMeshes();
  60403. if (this._sourceMesh.subMeshes) {
  60404. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60405. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60406. }
  60407. }
  60408. return this;
  60409. };
  60410. InstancedMesh.prototype._generatePointsArray = function () {
  60411. return this._sourceMesh._generatePointsArray();
  60412. };
  60413. /**
  60414. * Creates a new InstancedMesh from the current mesh.
  60415. * - name (string) : the cloned mesh name
  60416. * - newParent (optional Node) : the optional Node to parent the clone to.
  60417. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60418. *
  60419. * Returns the clone.
  60420. */
  60421. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60422. var result = this._sourceMesh.createInstance(name);
  60423. // Deep copy
  60424. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60425. // Bounding info
  60426. this.refreshBoundingInfo();
  60427. // Parent
  60428. if (newParent) {
  60429. result.parent = newParent;
  60430. }
  60431. if (!doNotCloneChildren) {
  60432. // Children
  60433. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60434. var mesh = this.getScene().meshes[index];
  60435. if (mesh.parent === this) {
  60436. mesh.clone(mesh.name, result);
  60437. }
  60438. }
  60439. }
  60440. result.computeWorldMatrix(true);
  60441. return result;
  60442. };
  60443. /**
  60444. * Disposes the InstancedMesh.
  60445. * Returns nothing.
  60446. */
  60447. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60448. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60449. // Remove from mesh
  60450. var index = this._sourceMesh.instances.indexOf(this);
  60451. this._sourceMesh.instances.splice(index, 1);
  60452. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60453. };
  60454. return InstancedMesh;
  60455. }(BABYLON.AbstractMesh));
  60456. BABYLON.InstancedMesh = InstancedMesh;
  60457. })(BABYLON || (BABYLON = {}));
  60458. //# sourceMappingURL=babylon.instancedMesh.js.map
  60459. var BABYLON;
  60460. (function (BABYLON) {
  60461. var LinesMesh = /** @class */ (function (_super) {
  60462. __extends(LinesMesh, _super);
  60463. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60464. if (scene === void 0) { scene = null; }
  60465. if (parent === void 0) { parent = null; }
  60466. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60467. _this.useVertexColor = useVertexColor;
  60468. _this.useVertexAlpha = useVertexAlpha;
  60469. _this.color = new BABYLON.Color3(1, 1, 1);
  60470. _this.alpha = 1;
  60471. if (source) {
  60472. _this.color = source.color.clone();
  60473. _this.alpha = source.alpha;
  60474. _this.useVertexColor = source.useVertexColor;
  60475. _this.useVertexAlpha = source.useVertexAlpha;
  60476. }
  60477. _this._intersectionThreshold = 0.1;
  60478. var defines = [];
  60479. var options = {
  60480. attributes: [BABYLON.VertexBuffer.PositionKind],
  60481. uniforms: ["world", "viewProjection"],
  60482. needAlphaBlending: true,
  60483. defines: defines
  60484. };
  60485. if (useVertexAlpha === false) {
  60486. options.needAlphaBlending = false;
  60487. }
  60488. if (!useVertexColor) {
  60489. options.uniforms.push("color");
  60490. }
  60491. else {
  60492. options.defines.push("#define VERTEXCOLOR");
  60493. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60494. }
  60495. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60496. return _this;
  60497. }
  60498. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60499. /**
  60500. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60501. * This margin is expressed in world space coordinates, so its value may vary.
  60502. * Default value is 0.1
  60503. * @returns the intersection Threshold value.
  60504. */
  60505. get: function () {
  60506. return this._intersectionThreshold;
  60507. },
  60508. /**
  60509. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60510. * This margin is expressed in world space coordinates, so its value may vary.
  60511. * @param value the new threshold to apply
  60512. */
  60513. set: function (value) {
  60514. if (this._intersectionThreshold === value) {
  60515. return;
  60516. }
  60517. this._intersectionThreshold = value;
  60518. if (this.geometry) {
  60519. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60520. }
  60521. },
  60522. enumerable: true,
  60523. configurable: true
  60524. });
  60525. /**
  60526. * Returns the string "LineMesh"
  60527. */
  60528. LinesMesh.prototype.getClassName = function () {
  60529. return "LinesMesh";
  60530. };
  60531. Object.defineProperty(LinesMesh.prototype, "material", {
  60532. get: function () {
  60533. return this._colorShader;
  60534. },
  60535. set: function (value) {
  60536. // Do nothing
  60537. },
  60538. enumerable: true,
  60539. configurable: true
  60540. });
  60541. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60542. get: function () {
  60543. return false;
  60544. },
  60545. enumerable: true,
  60546. configurable: true
  60547. });
  60548. LinesMesh.prototype.createInstance = function (name) {
  60549. throw new Error("LinesMeshes do not support createInstance.");
  60550. };
  60551. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60552. if (!this._geometry) {
  60553. return this;
  60554. }
  60555. // VBOs
  60556. this._geometry._bind(this._colorShader.getEffect());
  60557. // Color
  60558. if (!this.useVertexColor) {
  60559. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60560. }
  60561. return this;
  60562. };
  60563. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60564. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60565. return this;
  60566. }
  60567. var engine = this.getScene().getEngine();
  60568. // Draw order
  60569. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60570. return this;
  60571. };
  60572. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60573. this._colorShader.dispose();
  60574. _super.prototype.dispose.call(this, doNotRecurse);
  60575. };
  60576. /**
  60577. * Returns a new LineMesh object cloned from the current one.
  60578. */
  60579. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60580. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60581. };
  60582. return LinesMesh;
  60583. }(BABYLON.Mesh));
  60584. BABYLON.LinesMesh = LinesMesh;
  60585. })(BABYLON || (BABYLON = {}));
  60586. //# sourceMappingURL=babylon.linesMesh.js.map
  60587. var BABYLON;
  60588. (function (BABYLON) {
  60589. /**
  60590. * Class containing static functions to help procedurally build meshes
  60591. */
  60592. var MeshBuilder = /** @class */ (function () {
  60593. function MeshBuilder() {
  60594. }
  60595. MeshBuilder.updateSideOrientation = function (orientation) {
  60596. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60597. return BABYLON.Mesh.DOUBLESIDE;
  60598. }
  60599. if (orientation === undefined || orientation === null) {
  60600. return BABYLON.Mesh.FRONTSIDE;
  60601. }
  60602. return orientation;
  60603. };
  60604. /**
  60605. * Creates a box mesh
  60606. * * The parameter `size` sets the size (float) of each box side (default 1)
  60607. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60608. * * 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)
  60609. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60610. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60611. * * 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
  60612. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60613. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60614. * @param name defines the name of the mesh
  60615. * @param options defines the options used to create the mesh
  60616. * @param scene defines the hosting scene
  60617. * @returns the box mesh
  60618. */
  60619. MeshBuilder.CreateBox = function (name, options, scene) {
  60620. if (scene === void 0) { scene = null; }
  60621. var box = new BABYLON.Mesh(name, scene);
  60622. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60623. box._originalBuilderSideOrientation = options.sideOrientation;
  60624. var vertexData = BABYLON.VertexData.CreateBox(options);
  60625. vertexData.applyToMesh(box, options.updatable);
  60626. return box;
  60627. };
  60628. /**
  60629. * Creates a sphere mesh
  60630. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60631. * * 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`)
  60632. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60633. * * 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
  60634. * * 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)
  60635. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60636. * * 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
  60637. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60638. * @param name defines the name of the mesh
  60639. * @param options defines the options used to create the mesh
  60640. * @param scene defines the hosting scene
  60641. * @returns the sphere mesh
  60642. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60643. */
  60644. MeshBuilder.CreateSphere = function (name, options, scene) {
  60645. var sphere = new BABYLON.Mesh(name, scene);
  60646. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60647. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60648. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60649. vertexData.applyToMesh(sphere, options.updatable);
  60650. return sphere;
  60651. };
  60652. /**
  60653. * Creates a plane polygonal mesh. By default, this is a disc
  60654. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60655. * * 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
  60656. * * 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
  60657. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60658. * * 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
  60659. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60660. * @param name defines the name of the mesh
  60661. * @param options defines the options used to create the mesh
  60662. * @param scene defines the hosting scene
  60663. * @returns the plane polygonal mesh
  60664. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60665. */
  60666. MeshBuilder.CreateDisc = function (name, options, scene) {
  60667. if (scene === void 0) { scene = null; }
  60668. var disc = new BABYLON.Mesh(name, scene);
  60669. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60670. disc._originalBuilderSideOrientation = options.sideOrientation;
  60671. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60672. vertexData.applyToMesh(disc, options.updatable);
  60673. return disc;
  60674. };
  60675. /**
  60676. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60677. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60678. * * 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`)
  60679. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60680. * * 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
  60681. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60682. * * 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
  60683. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60684. * @param name defines the name of the mesh
  60685. * @param options defines the options used to create the mesh
  60686. * @param scene defines the hosting scene
  60687. * @returns the icosahedron mesh
  60688. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60689. */
  60690. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60691. var sphere = new BABYLON.Mesh(name, scene);
  60692. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60693. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60694. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60695. vertexData.applyToMesh(sphere, options.updatable);
  60696. return sphere;
  60697. };
  60698. ;
  60699. /**
  60700. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60701. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60702. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60703. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60704. * * 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
  60705. * * 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
  60706. * * 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
  60707. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60708. * * 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
  60709. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60710. * * 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
  60711. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60712. * * 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
  60713. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60714. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60715. * @param name defines the name of the mesh
  60716. * @param options defines the options used to create the mesh
  60717. * @param scene defines the hosting scene
  60718. * @returns the ribbon mesh
  60719. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60720. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60721. */
  60722. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60723. if (scene === void 0) { scene = null; }
  60724. var pathArray = options.pathArray;
  60725. var closeArray = options.closeArray;
  60726. var closePath = options.closePath;
  60727. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60728. var instance = options.instance;
  60729. var updatable = options.updatable;
  60730. if (instance) { // existing ribbon instance update
  60731. // positionFunction : ribbon case
  60732. // only pathArray and sideOrientation parameters are taken into account for positions update
  60733. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60734. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60735. var positionFunction = function (positions) {
  60736. var minlg = pathArray[0].length;
  60737. var i = 0;
  60738. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60739. for (var si = 1; si <= ns; si++) {
  60740. for (var p = 0; p < pathArray.length; p++) {
  60741. var path = pathArray[p];
  60742. var l = path.length;
  60743. minlg = (minlg < l) ? minlg : l;
  60744. var j = 0;
  60745. while (j < minlg) {
  60746. positions[i] = path[j].x;
  60747. positions[i + 1] = path[j].y;
  60748. positions[i + 2] = path[j].z;
  60749. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60750. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60751. }
  60752. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60753. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60754. }
  60755. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60756. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60757. }
  60758. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60759. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60760. }
  60761. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60762. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60763. }
  60764. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60765. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60766. }
  60767. j++;
  60768. i += 3;
  60769. }
  60770. if (instance._closePath) {
  60771. positions[i] = path[0].x;
  60772. positions[i + 1] = path[0].y;
  60773. positions[i + 2] = path[0].z;
  60774. i += 3;
  60775. }
  60776. }
  60777. }
  60778. };
  60779. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60780. positionFunction(positions);
  60781. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60782. instance._boundingInfo.update(instance._worldMatrix);
  60783. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60784. if (options.colors) {
  60785. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60786. for (var c = 0; c < options.colors.length; c++) {
  60787. colors[c * 4] = options.colors[c].r;
  60788. colors[c * 4 + 1] = options.colors[c].g;
  60789. colors[c * 4 + 2] = options.colors[c].b;
  60790. colors[c * 4 + 3] = options.colors[c].a;
  60791. }
  60792. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60793. }
  60794. if (options.uvs) {
  60795. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60796. for (var i = 0; i < options.uvs.length; i++) {
  60797. uvs[i * 2] = options.uvs[i].x;
  60798. uvs[i * 2 + 1] = options.uvs[i].y;
  60799. }
  60800. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60801. }
  60802. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60803. var indices = instance.getIndices();
  60804. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60805. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60806. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60807. if (instance._closePath) {
  60808. var indexFirst = 0;
  60809. var indexLast = 0;
  60810. for (var p = 0; p < pathArray.length; p++) {
  60811. indexFirst = instance._idx[p] * 3;
  60812. if (p + 1 < pathArray.length) {
  60813. indexLast = (instance._idx[p + 1] - 1) * 3;
  60814. }
  60815. else {
  60816. indexLast = normals.length - 3;
  60817. }
  60818. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60819. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60820. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60821. normals[indexLast] = normals[indexFirst];
  60822. normals[indexLast + 1] = normals[indexFirst + 1];
  60823. normals[indexLast + 2] = normals[indexFirst + 2];
  60824. }
  60825. }
  60826. if (!(instance.areNormalsFrozen)) {
  60827. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  60828. }
  60829. }
  60830. return instance;
  60831. }
  60832. else { // new ribbon creation
  60833. var ribbon = new BABYLON.Mesh(name, scene);
  60834. ribbon._originalBuilderSideOrientation = sideOrientation;
  60835. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  60836. if (closePath) {
  60837. ribbon._idx = vertexData._idx;
  60838. }
  60839. ribbon._closePath = closePath;
  60840. ribbon._closeArray = closeArray;
  60841. vertexData.applyToMesh(ribbon, updatable);
  60842. return ribbon;
  60843. }
  60844. };
  60845. /**
  60846. * Creates a cylinder or a cone mesh
  60847. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  60848. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  60849. * * 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.
  60850. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  60851. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  60852. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  60853. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  60854. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  60855. * * 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).
  60856. * * 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
  60857. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  60858. * * 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
  60859. * * 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.
  60860. * * If `enclose` is false, a ring surface is one element.
  60861. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  60862. * * 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
  60863. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60864. * * 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
  60865. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60866. * @param name defines the name of the mesh
  60867. * @param options defines the options used to create the mesh
  60868. * @param scene defines the hosting scene
  60869. * @returns the cylinder mesh
  60870. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  60871. */
  60872. MeshBuilder.CreateCylinder = function (name, options, scene) {
  60873. var cylinder = new BABYLON.Mesh(name, scene);
  60874. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60875. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  60876. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  60877. vertexData.applyToMesh(cylinder, options.updatable);
  60878. return cylinder;
  60879. };
  60880. /**
  60881. * Creates a torus mesh
  60882. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  60883. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  60884. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  60885. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60886. * * 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
  60887. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60888. * @param name defines the name of the mesh
  60889. * @param options defines the options used to create the mesh
  60890. * @param scene defines the hosting scene
  60891. * @returns the torus mesh
  60892. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  60893. */
  60894. MeshBuilder.CreateTorus = function (name, options, scene) {
  60895. var torus = new BABYLON.Mesh(name, scene);
  60896. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60897. torus._originalBuilderSideOrientation = options.sideOrientation;
  60898. var vertexData = BABYLON.VertexData.CreateTorus(options);
  60899. vertexData.applyToMesh(torus, options.updatable);
  60900. return torus;
  60901. };
  60902. /**
  60903. * Creates a torus knot mesh
  60904. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  60905. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  60906. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  60907. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  60908. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60909. * * 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
  60910. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  60911. * @param name defines the name of the mesh
  60912. * @param options defines the options used to create the mesh
  60913. * @param scene defines the hosting scene
  60914. * @returns the torus knot mesh
  60915. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  60916. */
  60917. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  60918. var torusKnot = new BABYLON.Mesh(name, scene);
  60919. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60920. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  60921. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  60922. vertexData.applyToMesh(torusKnot, options.updatable);
  60923. return torusKnot;
  60924. };
  60925. /**
  60926. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  60927. * * 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
  60928. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  60929. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  60930. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  60931. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  60932. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  60933. * * 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
  60934. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  60935. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60936. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  60937. * @param name defines the name of the new line system
  60938. * @param options defines the options used to create the line system
  60939. * @param scene defines the hosting scene
  60940. * @returns a new line system mesh
  60941. */
  60942. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  60943. var instance = options.instance;
  60944. var lines = options.lines;
  60945. var colors = options.colors;
  60946. if (instance) { // lines update
  60947. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60948. var vertexColor;
  60949. var lineColors;
  60950. if (colors) {
  60951. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60952. }
  60953. var i = 0;
  60954. var c = 0;
  60955. for (var l = 0; l < lines.length; l++) {
  60956. var points = lines[l];
  60957. for (var p = 0; p < points.length; p++) {
  60958. positions[i] = points[p].x;
  60959. positions[i + 1] = points[p].y;
  60960. positions[i + 2] = points[p].z;
  60961. if (colors && vertexColor) {
  60962. lineColors = colors[l];
  60963. vertexColor[c] = lineColors[p].r;
  60964. vertexColor[c + 1] = lineColors[p].g;
  60965. vertexColor[c + 2] = lineColors[p].b;
  60966. vertexColor[c + 3] = lineColors[p].a;
  60967. c += 4;
  60968. }
  60969. i += 3;
  60970. }
  60971. }
  60972. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60973. if (colors && vertexColor) {
  60974. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  60975. }
  60976. return instance;
  60977. }
  60978. // line system creation
  60979. var useVertexColor = (colors) ? true : false;
  60980. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  60981. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  60982. vertexData.applyToMesh(lineSystem, options.updatable);
  60983. return lineSystem;
  60984. };
  60985. /**
  60986. * Creates a line mesh
  60987. * 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
  60988. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  60989. * * The parameter `points` is an array successive Vector3
  60990. * * 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
  60991. * * The optional parameter `colors` is an array of successive Color4, one per line point
  60992. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  60993. * * When updating an instance, remember that only point positions can change, not the number of points
  60994. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60995. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  60996. * @param name defines the name of the new line system
  60997. * @param options defines the options used to create the line system
  60998. * @param scene defines the hosting scene
  60999. * @returns a new line mesh
  61000. */
  61001. MeshBuilder.CreateLines = function (name, options, scene) {
  61002. if (scene === void 0) { scene = null; }
  61003. var colors = (options.colors) ? [options.colors] : null;
  61004. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61005. return lines;
  61006. };
  61007. /**
  61008. * Creates a dashed line mesh
  61009. * * 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
  61010. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61011. * * The parameter `points` is an array successive Vector3
  61012. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61013. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61014. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61015. * * 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
  61016. * * When updating an instance, remember that only point positions can change, not the number of points
  61017. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61018. * @param name defines the name of the mesh
  61019. * @param options defines the options used to create the mesh
  61020. * @param scene defines the hosting scene
  61021. * @returns the dashed line mesh
  61022. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61023. */
  61024. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61025. if (scene === void 0) { scene = null; }
  61026. var points = options.points;
  61027. var instance = options.instance;
  61028. var gapSize = options.gapSize || 1;
  61029. var dashSize = options.dashSize || 3;
  61030. if (instance) { // dashed lines update
  61031. var positionFunction = function (positions) {
  61032. var curvect = BABYLON.Vector3.Zero();
  61033. var nbSeg = positions.length / 6;
  61034. var lg = 0;
  61035. var nb = 0;
  61036. var shft = 0;
  61037. var dashshft = 0;
  61038. var curshft = 0;
  61039. var p = 0;
  61040. var i = 0;
  61041. var j = 0;
  61042. for (i = 0; i < points.length - 1; i++) {
  61043. points[i + 1].subtractToRef(points[i], curvect);
  61044. lg += curvect.length();
  61045. }
  61046. shft = lg / nbSeg;
  61047. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61048. for (i = 0; i < points.length - 1; i++) {
  61049. points[i + 1].subtractToRef(points[i], curvect);
  61050. nb = Math.floor(curvect.length() / shft);
  61051. curvect.normalize();
  61052. j = 0;
  61053. while (j < nb && p < positions.length) {
  61054. curshft = shft * j;
  61055. positions[p] = points[i].x + curshft * curvect.x;
  61056. positions[p + 1] = points[i].y + curshft * curvect.y;
  61057. positions[p + 2] = points[i].z + curshft * curvect.z;
  61058. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61059. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61060. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61061. p += 6;
  61062. j++;
  61063. }
  61064. }
  61065. while (p < positions.length) {
  61066. positions[p] = points[i].x;
  61067. positions[p + 1] = points[i].y;
  61068. positions[p + 2] = points[i].z;
  61069. p += 3;
  61070. }
  61071. };
  61072. instance.updateMeshPositions(positionFunction, false);
  61073. return instance;
  61074. }
  61075. // dashed lines creation
  61076. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61077. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61078. vertexData.applyToMesh(dashedLines, options.updatable);
  61079. dashedLines.dashSize = dashSize;
  61080. dashedLines.gapSize = gapSize;
  61081. return dashedLines;
  61082. };
  61083. /**
  61084. * 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.
  61085. * * 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.
  61086. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61087. * * 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.
  61088. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61089. * * 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
  61090. * * 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
  61091. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61092. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61093. * * 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
  61094. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61095. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61096. * @param name defines the name of the mesh
  61097. * @param options defines the options used to create the mesh
  61098. * @param scene defines the hosting scene
  61099. * @returns the extruded shape mesh
  61100. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61101. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61102. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61103. */
  61104. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61105. if (scene === void 0) { scene = null; }
  61106. var path = options.path;
  61107. var shape = options.shape;
  61108. var scale = options.scale || 1;
  61109. var rotation = options.rotation || 0;
  61110. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61111. var updatable = options.updatable;
  61112. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61113. var instance = options.instance || null;
  61114. var invertUV = options.invertUV || false;
  61115. 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);
  61116. };
  61117. /**
  61118. * Creates an custom extruded shape mesh.
  61119. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61120. * * 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.
  61121. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61122. * * 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
  61123. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61124. * * 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
  61125. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61126. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61127. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61128. * * 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
  61129. * * 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
  61130. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61131. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61132. * * 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
  61133. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61134. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61135. * @param name defines the name of the mesh
  61136. * @param options defines the options used to create the mesh
  61137. * @param scene defines the hosting scene
  61138. * @returns the custom extruded shape mesh
  61139. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61140. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61141. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61142. */
  61143. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61144. var path = options.path;
  61145. var shape = options.shape;
  61146. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61147. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61148. var ribbonCloseArray = options.ribbonCloseArray || false;
  61149. var ribbonClosePath = options.ribbonClosePath || false;
  61150. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61151. var updatable = options.updatable;
  61152. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61153. var instance = options.instance;
  61154. var invertUV = options.invertUV || false;
  61155. 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);
  61156. };
  61157. /**
  61158. * Creates lathe mesh.
  61159. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61160. * * 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
  61161. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61162. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61163. * * 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
  61164. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  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. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61167. * * 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
  61168. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61169. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61170. * @param name defines the name of the mesh
  61171. * @param options defines the options used to create the mesh
  61172. * @param scene defines the hosting scene
  61173. * @returns the lathe mesh
  61174. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61175. */
  61176. MeshBuilder.CreateLathe = function (name, options, scene) {
  61177. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61178. var closed = (options.closed === undefined) ? true : options.closed;
  61179. var shape = options.shape;
  61180. var radius = options.radius || 1;
  61181. var tessellation = options.tessellation || 64;
  61182. var updatable = options.updatable;
  61183. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61184. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61185. var pi2 = Math.PI * 2;
  61186. var paths = new Array();
  61187. var invertUV = options.invertUV || false;
  61188. var i = 0;
  61189. var p = 0;
  61190. var step = pi2 / tessellation * arc;
  61191. var rotated;
  61192. var path = new Array();
  61193. for (i = 0; i <= tessellation; i++) {
  61194. var path = [];
  61195. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61196. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61197. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61198. }
  61199. for (p = 0; p < shape.length; p++) {
  61200. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61201. path.push(rotated);
  61202. }
  61203. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61204. 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));
  61205. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61206. }
  61207. paths.push(path);
  61208. }
  61209. // lathe ribbon
  61210. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61211. return lathe;
  61212. };
  61213. /**
  61214. * Creates a plane mesh
  61215. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61216. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61217. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61218. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61219. * * 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
  61220. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61221. * @param name defines the name of the mesh
  61222. * @param options defines the options used to create the mesh
  61223. * @param scene defines the hosting scene
  61224. * @returns the plane mesh
  61225. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61226. */
  61227. MeshBuilder.CreatePlane = function (name, options, scene) {
  61228. var plane = new BABYLON.Mesh(name, scene);
  61229. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61230. plane._originalBuilderSideOrientation = options.sideOrientation;
  61231. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61232. vertexData.applyToMesh(plane, options.updatable);
  61233. if (options.sourcePlane) {
  61234. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61235. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61236. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61237. plane.rotate(vectorProduct, product);
  61238. }
  61239. return plane;
  61240. };
  61241. /**
  61242. * Creates a ground mesh
  61243. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61244. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  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 ground mesh
  61250. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61251. */
  61252. MeshBuilder.CreateGround = function (name, options, scene) {
  61253. var ground = new BABYLON.GroundMesh(name, scene);
  61254. ground._setReady(false);
  61255. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61256. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61257. ground._width = options.width || 1;
  61258. ground._height = options.height || 1;
  61259. ground._maxX = ground._width / 2;
  61260. ground._maxZ = ground._height / 2;
  61261. ground._minX = -ground._maxX;
  61262. ground._minZ = -ground._maxZ;
  61263. var vertexData = BABYLON.VertexData.CreateGround(options);
  61264. vertexData.applyToMesh(ground, options.updatable);
  61265. ground._setReady(true);
  61266. return ground;
  61267. };
  61268. /**
  61269. * Creates a tiled ground mesh
  61270. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61271. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61272. * * 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
  61273. * * 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
  61274. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61275. * @param name defines the name of the mesh
  61276. * @param options defines the options used to create the mesh
  61277. * @param scene defines the hosting scene
  61278. * @returns the tiled ground mesh
  61279. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61280. */
  61281. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61282. var tiledGround = new BABYLON.Mesh(name, scene);
  61283. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61284. vertexData.applyToMesh(tiledGround, options.updatable);
  61285. return tiledGround;
  61286. };
  61287. /**
  61288. * Creates a ground mesh from a height map
  61289. * * The parameter `url` sets the URL of the height map image resource.
  61290. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61291. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61292. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61293. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61294. * * 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.
  61295. * * 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).
  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 url defines the url to the height map
  61299. * @param options defines the options used to create the mesh
  61300. * @param scene defines the hosting scene
  61301. * @returns the ground mesh
  61302. * @see http://doc.babylonjs.com/babylon101/height_map
  61303. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61304. */
  61305. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61306. var width = options.width || 10.0;
  61307. var height = options.height || 10.0;
  61308. var subdivisions = options.subdivisions || 1 | 0;
  61309. var minHeight = options.minHeight || 0.0;
  61310. var maxHeight = options.maxHeight || 1.0;
  61311. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61312. var updatable = options.updatable;
  61313. var onReady = options.onReady;
  61314. var ground = new BABYLON.GroundMesh(name, scene);
  61315. ground._subdivisionsX = subdivisions;
  61316. ground._subdivisionsY = subdivisions;
  61317. ground._width = width;
  61318. ground._height = height;
  61319. ground._maxX = ground._width / 2.0;
  61320. ground._maxZ = ground._height / 2.0;
  61321. ground._minX = -ground._maxX;
  61322. ground._minZ = -ground._maxZ;
  61323. ground._setReady(false);
  61324. var onload = function (img) {
  61325. // Getting height map data
  61326. var canvas = document.createElement("canvas");
  61327. var context = canvas.getContext("2d");
  61328. if (!context) {
  61329. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61330. }
  61331. if (scene.isDisposed) {
  61332. return;
  61333. }
  61334. var bufferWidth = img.width;
  61335. var bufferHeight = img.height;
  61336. canvas.width = bufferWidth;
  61337. canvas.height = bufferHeight;
  61338. context.drawImage(img, 0, 0);
  61339. // Create VertexData from map data
  61340. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61341. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61342. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61343. width: width, height: height,
  61344. subdivisions: subdivisions,
  61345. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61346. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61347. });
  61348. vertexData.applyToMesh(ground, updatable);
  61349. //execute ready callback, if set
  61350. if (onReady) {
  61351. onReady(ground);
  61352. }
  61353. ground._setReady(true);
  61354. };
  61355. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61356. return ground;
  61357. };
  61358. /**
  61359. * Creates a polygon mesh
  61360. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61361. * * 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
  61362. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61363. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61364. * * 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)
  61365. * * Remember you can only change the shape positions, not their number when updating a polygon
  61366. * @param name defines the name of the mesh
  61367. * @param options defines the options used to create the mesh
  61368. * @param scene defines the hosting scene
  61369. * @returns the polygon mesh
  61370. */
  61371. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61372. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61373. var shape = options.shape;
  61374. var holes = options.holes || [];
  61375. var depth = options.depth || 0;
  61376. var contours = [];
  61377. var hole = [];
  61378. for (var i = 0; i < shape.length; i++) {
  61379. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61380. }
  61381. var epsilon = 0.00000001;
  61382. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61383. contours.pop();
  61384. }
  61385. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61386. for (var hNb = 0; hNb < holes.length; hNb++) {
  61387. hole = [];
  61388. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61389. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61390. }
  61391. polygonTriangulation.addHole(hole);
  61392. }
  61393. var polygon = polygonTriangulation.build(options.updatable, depth);
  61394. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61395. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61396. vertexData.applyToMesh(polygon, options.updatable);
  61397. return polygon;
  61398. };
  61399. ;
  61400. /**
  61401. * Creates an extruded polygon mesh, with depth in the Y direction.
  61402. * * 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)
  61403. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61404. * @param name defines the name of the mesh
  61405. * @param options defines the options used to create the mesh
  61406. * @param scene defines the hosting scene
  61407. * @returns the polygon mesh
  61408. */
  61409. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61410. return MeshBuilder.CreatePolygon(name, options, scene);
  61411. };
  61412. ;
  61413. /**
  61414. * Creates a tube mesh.
  61415. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61416. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61417. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61418. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61419. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61420. * * 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)
  61421. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61422. * * 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
  61423. * * 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
  61424. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61425. * * 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
  61426. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61427. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61428. * @param name defines the name of the mesh
  61429. * @param options defines the options used to create the mesh
  61430. * @param scene defines the hosting scene
  61431. * @returns the tube mesh
  61432. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61433. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61434. */
  61435. MeshBuilder.CreateTube = function (name, options, scene) {
  61436. var path = options.path;
  61437. var instance = options.instance;
  61438. var radius = 1.0;
  61439. if (instance) {
  61440. radius = instance.radius;
  61441. }
  61442. if (options.radius !== undefined) {
  61443. radius = options.radius;
  61444. }
  61445. ;
  61446. var tessellation = options.tessellation || 64 | 0;
  61447. var radiusFunction = options.radiusFunction || null;
  61448. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61449. var invertUV = options.invertUV || false;
  61450. var updatable = options.updatable;
  61451. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61452. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61453. // tube geometry
  61454. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61455. var tangents = path3D.getTangents();
  61456. var normals = path3D.getNormals();
  61457. var distances = path3D.getDistances();
  61458. var pi2 = Math.PI * 2;
  61459. var step = pi2 / tessellation * arc;
  61460. var returnRadius = function () { return radius; };
  61461. var radiusFunctionFinal = radiusFunction || returnRadius;
  61462. var circlePath;
  61463. var rad;
  61464. var normal;
  61465. var rotated;
  61466. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61467. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61468. for (var i = 0; i < path.length; i++) {
  61469. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61470. circlePath = Array(); // current circle array
  61471. normal = normals[i]; // current normal
  61472. for (var t = 0; t < tessellation; t++) {
  61473. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61474. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61475. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61476. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61477. circlePath[t] = rotated;
  61478. }
  61479. circlePaths[index] = circlePath;
  61480. index++;
  61481. }
  61482. // cap
  61483. var capPath = function (nbPoints, pathIndex) {
  61484. var pointCap = Array();
  61485. for (var i = 0; i < nbPoints; i++) {
  61486. pointCap.push(path[pathIndex]);
  61487. }
  61488. return pointCap;
  61489. };
  61490. switch (cap) {
  61491. case BABYLON.Mesh.NO_CAP:
  61492. break;
  61493. case BABYLON.Mesh.CAP_START:
  61494. circlePaths[0] = capPath(tessellation, 0);
  61495. circlePaths[1] = circlePaths[2].slice(0);
  61496. break;
  61497. case BABYLON.Mesh.CAP_END:
  61498. circlePaths[index] = circlePaths[index - 1].slice(0);
  61499. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61500. break;
  61501. case BABYLON.Mesh.CAP_ALL:
  61502. circlePaths[0] = capPath(tessellation, 0);
  61503. circlePaths[1] = circlePaths[2].slice(0);
  61504. circlePaths[index] = circlePaths[index - 1].slice(0);
  61505. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61506. break;
  61507. default:
  61508. break;
  61509. }
  61510. return circlePaths;
  61511. };
  61512. var path3D;
  61513. var pathArray;
  61514. if (instance) { // tube update
  61515. var arc = options.arc || instance.arc;
  61516. path3D = (instance.path3D).update(path);
  61517. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61518. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61519. instance.path3D = path3D;
  61520. instance.pathArray = pathArray;
  61521. instance.arc = arc;
  61522. instance.radius = radius;
  61523. return instance;
  61524. }
  61525. // tube creation
  61526. path3D = new BABYLON.Path3D(path);
  61527. var newPathArray = new Array();
  61528. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61529. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61530. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61531. tube.pathArray = pathArray;
  61532. tube.path3D = path3D;
  61533. tube.tessellation = tessellation;
  61534. tube.cap = cap;
  61535. tube.arc = options.arc;
  61536. tube.radius = radius;
  61537. return tube;
  61538. };
  61539. /**
  61540. * Creates a polyhedron mesh
  61541. * * 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
  61542. * * The parameter `size` (positive float, default 1) sets the polygon size
  61543. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61544. * * 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`
  61545. * * 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
  61546. * * 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)`)
  61547. * * 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
  61548. * * 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
  61549. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61550. * * 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
  61551. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61552. * @param name defines the name of the mesh
  61553. * @param options defines the options used to create the mesh
  61554. * @param scene defines the hosting scene
  61555. * @returns the polyhedron mesh
  61556. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61557. */
  61558. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61559. var polyhedron = new BABYLON.Mesh(name, scene);
  61560. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61561. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61562. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61563. vertexData.applyToMesh(polyhedron, options.updatable);
  61564. return polyhedron;
  61565. };
  61566. /**
  61567. * Creates a decal mesh.
  61568. * 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
  61569. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61570. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61571. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61572. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61573. * @param name defines the name of the mesh
  61574. * @param sourceMesh defines the mesh where the decal must be applied
  61575. * @param options defines the options used to create the mesh
  61576. * @param scene defines the hosting scene
  61577. * @returns the decal mesh
  61578. * @see http://doc.babylonjs.com/how_to/decals
  61579. */
  61580. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61581. var indices = sourceMesh.getIndices();
  61582. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61583. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61584. var position = options.position || BABYLON.Vector3.Zero();
  61585. var normal = options.normal || BABYLON.Vector3.Up();
  61586. var size = options.size || BABYLON.Vector3.One();
  61587. var angle = options.angle || 0;
  61588. // Getting correct rotation
  61589. if (!normal) {
  61590. var target = new BABYLON.Vector3(0, 0, 1);
  61591. var camera = sourceMesh.getScene().activeCamera;
  61592. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61593. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61594. }
  61595. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61596. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61597. var pitch = Math.atan2(normal.y, len);
  61598. // Matrix
  61599. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61600. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61601. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61602. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61603. var vertexData = new BABYLON.VertexData();
  61604. vertexData.indices = [];
  61605. vertexData.positions = [];
  61606. vertexData.normals = [];
  61607. vertexData.uvs = [];
  61608. var currentVertexDataIndex = 0;
  61609. var extractDecalVector3 = function (indexId) {
  61610. var result = new BABYLON.PositionNormalVertex();
  61611. if (!indices || !positions || !normals) {
  61612. return result;
  61613. }
  61614. var vertexId = indices[indexId];
  61615. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61616. // Send vector to decal local world
  61617. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61618. // Get normal
  61619. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61620. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61621. return result;
  61622. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61623. var clip = function (vertices, axis) {
  61624. if (vertices.length === 0) {
  61625. return vertices;
  61626. }
  61627. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61628. var clipVertices = function (v0, v1) {
  61629. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61630. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61631. };
  61632. var result = new Array();
  61633. for (var index = 0; index < vertices.length; index += 3) {
  61634. var v1Out;
  61635. var v2Out;
  61636. var v3Out;
  61637. var total = 0;
  61638. var nV1 = null;
  61639. var nV2 = null;
  61640. var nV3 = null;
  61641. var nV4 = null;
  61642. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61643. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61644. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61645. v1Out = d1 > 0;
  61646. v2Out = d2 > 0;
  61647. v3Out = d3 > 0;
  61648. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61649. switch (total) {
  61650. case 0:
  61651. result.push(vertices[index]);
  61652. result.push(vertices[index + 1]);
  61653. result.push(vertices[index + 2]);
  61654. break;
  61655. case 1:
  61656. if (v1Out) {
  61657. nV1 = vertices[index + 1];
  61658. nV2 = vertices[index + 2];
  61659. nV3 = clipVertices(vertices[index], nV1);
  61660. nV4 = clipVertices(vertices[index], nV2);
  61661. }
  61662. if (v2Out) {
  61663. nV1 = vertices[index];
  61664. nV2 = vertices[index + 2];
  61665. nV3 = clipVertices(vertices[index + 1], nV1);
  61666. nV4 = clipVertices(vertices[index + 1], nV2);
  61667. result.push(nV3);
  61668. result.push(nV2.clone());
  61669. result.push(nV1.clone());
  61670. result.push(nV2.clone());
  61671. result.push(nV3.clone());
  61672. result.push(nV4);
  61673. break;
  61674. }
  61675. if (v3Out) {
  61676. nV1 = vertices[index];
  61677. nV2 = vertices[index + 1];
  61678. nV3 = clipVertices(vertices[index + 2], nV1);
  61679. nV4 = clipVertices(vertices[index + 2], nV2);
  61680. }
  61681. if (nV1 && nV2 && nV3 && nV4) {
  61682. result.push(nV1.clone());
  61683. result.push(nV2.clone());
  61684. result.push(nV3);
  61685. result.push(nV4);
  61686. result.push(nV3.clone());
  61687. result.push(nV2.clone());
  61688. }
  61689. break;
  61690. case 2:
  61691. if (!v1Out) {
  61692. nV1 = vertices[index].clone();
  61693. nV2 = clipVertices(nV1, vertices[index + 1]);
  61694. nV3 = clipVertices(nV1, vertices[index + 2]);
  61695. result.push(nV1);
  61696. result.push(nV2);
  61697. result.push(nV3);
  61698. }
  61699. if (!v2Out) {
  61700. nV1 = vertices[index + 1].clone();
  61701. nV2 = clipVertices(nV1, vertices[index + 2]);
  61702. nV3 = clipVertices(nV1, vertices[index]);
  61703. result.push(nV1);
  61704. result.push(nV2);
  61705. result.push(nV3);
  61706. }
  61707. if (!v3Out) {
  61708. nV1 = vertices[index + 2].clone();
  61709. nV2 = clipVertices(nV1, vertices[index]);
  61710. nV3 = clipVertices(nV1, vertices[index + 1]);
  61711. result.push(nV1);
  61712. result.push(nV2);
  61713. result.push(nV3);
  61714. }
  61715. break;
  61716. case 3:
  61717. break;
  61718. }
  61719. }
  61720. return result;
  61721. };
  61722. for (var index = 0; index < indices.length; index += 3) {
  61723. var faceVertices = new Array();
  61724. faceVertices.push(extractDecalVector3(index));
  61725. faceVertices.push(extractDecalVector3(index + 1));
  61726. faceVertices.push(extractDecalVector3(index + 2));
  61727. // Clip
  61728. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61729. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61730. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61731. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61732. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61733. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61734. if (faceVertices.length === 0) {
  61735. continue;
  61736. }
  61737. // Add UVs and get back to world
  61738. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61739. var vertex = faceVertices[vIndex];
  61740. //TODO check for Int32Array | Uint32Array | Uint16Array
  61741. vertexData.indices.push(currentVertexDataIndex);
  61742. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61743. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61744. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61745. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61746. currentVertexDataIndex++;
  61747. }
  61748. }
  61749. // Return mesh
  61750. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61751. vertexData.applyToMesh(decal);
  61752. decal.position = position.clone();
  61753. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61754. return decal;
  61755. };
  61756. // Privates
  61757. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61758. // extrusion geometry
  61759. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61760. var tangents = path3D.getTangents();
  61761. var normals = path3D.getNormals();
  61762. var binormals = path3D.getBinormals();
  61763. var distances = path3D.getDistances();
  61764. var angle = 0;
  61765. var returnScale = function () { return scale !== null ? scale : 1; };
  61766. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61767. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61768. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61769. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61770. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61771. for (var i = 0; i < curve.length; i++) {
  61772. var shapePath = new Array();
  61773. var angleStep = rotate(i, distances[i]);
  61774. var scaleRatio = scl(i, distances[i]);
  61775. for (var p = 0; p < shape.length; p++) {
  61776. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61777. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61778. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61779. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61780. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61781. shapePath[p] = rotated;
  61782. }
  61783. shapePaths[index] = shapePath;
  61784. angle += angleStep;
  61785. index++;
  61786. }
  61787. // cap
  61788. var capPath = function (shapePath) {
  61789. var pointCap = Array();
  61790. var barycenter = BABYLON.Vector3.Zero();
  61791. var i;
  61792. for (i = 0; i < shapePath.length; i++) {
  61793. barycenter.addInPlace(shapePath[i]);
  61794. }
  61795. barycenter.scaleInPlace(1.0 / shapePath.length);
  61796. for (i = 0; i < shapePath.length; i++) {
  61797. pointCap.push(barycenter);
  61798. }
  61799. return pointCap;
  61800. };
  61801. switch (cap) {
  61802. case BABYLON.Mesh.NO_CAP:
  61803. break;
  61804. case BABYLON.Mesh.CAP_START:
  61805. shapePaths[0] = capPath(shapePaths[2]);
  61806. shapePaths[1] = shapePaths[2];
  61807. break;
  61808. case BABYLON.Mesh.CAP_END:
  61809. shapePaths[index] = shapePaths[index - 1];
  61810. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61811. break;
  61812. case BABYLON.Mesh.CAP_ALL:
  61813. shapePaths[0] = capPath(shapePaths[2]);
  61814. shapePaths[1] = shapePaths[2];
  61815. shapePaths[index] = shapePaths[index - 1];
  61816. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61817. break;
  61818. default:
  61819. break;
  61820. }
  61821. return shapePaths;
  61822. };
  61823. var path3D;
  61824. var pathArray;
  61825. if (instance) { // instance update
  61826. path3D = (instance.path3D).update(curve);
  61827. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  61828. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  61829. return instance;
  61830. }
  61831. // extruded shape creation
  61832. path3D = new BABYLON.Path3D(curve);
  61833. var newShapePaths = new Array();
  61834. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61835. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  61836. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  61837. extrudedGeneric.pathArray = pathArray;
  61838. extrudedGeneric.path3D = path3D;
  61839. extrudedGeneric.cap = cap;
  61840. return extrudedGeneric;
  61841. };
  61842. return MeshBuilder;
  61843. }());
  61844. BABYLON.MeshBuilder = MeshBuilder;
  61845. })(BABYLON || (BABYLON = {}));
  61846. //# sourceMappingURL=babylon.meshBuilder.js.map
  61847. var BABYLON;
  61848. (function (BABYLON) {
  61849. /**
  61850. * Draco compression (https://google.github.io/draco/)
  61851. */
  61852. var DracoCompression = /** @class */ (function () {
  61853. /**
  61854. * Constructor
  61855. */
  61856. function DracoCompression() {
  61857. }
  61858. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  61859. /**
  61860. * Returns true if the decoder is available.
  61861. */
  61862. get: function () {
  61863. if (typeof DracoDecoderModule !== "undefined") {
  61864. return true;
  61865. }
  61866. var decoder = DracoCompression.Configuration.decoder;
  61867. if (decoder) {
  61868. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61869. return true;
  61870. }
  61871. if (decoder.fallbackUrl) {
  61872. return true;
  61873. }
  61874. }
  61875. return false;
  61876. },
  61877. enumerable: true,
  61878. configurable: true
  61879. });
  61880. /**
  61881. * Stop all async operations and release resources.
  61882. */
  61883. DracoCompression.prototype.dispose = function () {
  61884. };
  61885. /**
  61886. * Decode Draco compressed mesh data to vertex data.
  61887. * @param data The array buffer view for the Draco compression data
  61888. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  61889. * @returns A promise that resolves with the decoded vertex data
  61890. */
  61891. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  61892. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  61893. var module = wrappedModule.module;
  61894. var vertexData = new BABYLON.VertexData();
  61895. var buffer = new module.DecoderBuffer();
  61896. buffer.Init(data, data.byteLength);
  61897. var decoder = new module.Decoder();
  61898. var geometry;
  61899. var status;
  61900. try {
  61901. var type = decoder.GetEncodedGeometryType(buffer);
  61902. switch (type) {
  61903. case module.TRIANGULAR_MESH:
  61904. geometry = new module.Mesh();
  61905. status = decoder.DecodeBufferToMesh(buffer, geometry);
  61906. break;
  61907. case module.POINT_CLOUD:
  61908. geometry = new module.PointCloud();
  61909. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  61910. break;
  61911. default:
  61912. throw new Error("Invalid geometry type " + type);
  61913. }
  61914. if (!status.ok() || !geometry.ptr) {
  61915. throw new Error(status.error_msg());
  61916. }
  61917. var numPoints = geometry.num_points();
  61918. if (type === module.TRIANGULAR_MESH) {
  61919. var numFaces = geometry.num_faces();
  61920. var faceIndices = new module.DracoInt32Array();
  61921. try {
  61922. var indices = new Uint32Array(numFaces * 3);
  61923. for (var i = 0; i < numFaces; i++) {
  61924. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  61925. var offset = i * 3;
  61926. indices[offset + 0] = faceIndices.GetValue(0);
  61927. indices[offset + 1] = faceIndices.GetValue(1);
  61928. indices[offset + 2] = faceIndices.GetValue(2);
  61929. }
  61930. vertexData.indices = indices;
  61931. }
  61932. finally {
  61933. module.destroy(faceIndices);
  61934. }
  61935. }
  61936. for (var kind in attributes) {
  61937. var uniqueId = attributes[kind];
  61938. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  61939. var dracoData = new module.DracoFloat32Array();
  61940. try {
  61941. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  61942. var babylonData = new Float32Array(numPoints * attribute.num_components());
  61943. for (var i = 0; i < babylonData.length; i++) {
  61944. babylonData[i] = dracoData.GetValue(i);
  61945. }
  61946. vertexData.set(babylonData, kind);
  61947. }
  61948. finally {
  61949. module.destroy(dracoData);
  61950. }
  61951. }
  61952. }
  61953. finally {
  61954. if (geometry) {
  61955. module.destroy(geometry);
  61956. }
  61957. module.destroy(decoder);
  61958. module.destroy(buffer);
  61959. }
  61960. return vertexData;
  61961. });
  61962. };
  61963. DracoCompression._GetDecoderModule = function () {
  61964. if (!DracoCompression._DecoderModulePromise) {
  61965. var promise = null;
  61966. var config_1 = {};
  61967. if (typeof DracoDecoderModule !== "undefined") {
  61968. promise = Promise.resolve();
  61969. }
  61970. else {
  61971. var decoder = DracoCompression.Configuration.decoder;
  61972. if (decoder) {
  61973. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  61974. promise = Promise.all([
  61975. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  61976. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  61977. config_1.wasmBinary = data;
  61978. })
  61979. ]);
  61980. }
  61981. else if (decoder.fallbackUrl) {
  61982. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  61983. }
  61984. }
  61985. }
  61986. if (!promise) {
  61987. throw new Error("Draco decoder module is not available");
  61988. }
  61989. DracoCompression._DecoderModulePromise = promise.then(function () {
  61990. return new Promise(function (resolve) {
  61991. config_1.onModuleLoaded = function (decoderModule) {
  61992. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  61993. resolve({ module: decoderModule });
  61994. };
  61995. DracoDecoderModule(config_1);
  61996. });
  61997. });
  61998. }
  61999. return DracoCompression._DecoderModulePromise;
  62000. };
  62001. DracoCompression._LoadScriptAsync = function (url) {
  62002. return new Promise(function (resolve, reject) {
  62003. BABYLON.Tools.LoadScript(url, function () {
  62004. resolve();
  62005. }, function (message) {
  62006. reject(new Error(message));
  62007. });
  62008. });
  62009. };
  62010. DracoCompression._LoadFileAsync = function (url) {
  62011. return new Promise(function (resolve, reject) {
  62012. BABYLON.Tools.LoadFile(url, function (data) {
  62013. resolve(data);
  62014. }, undefined, undefined, true, function (request, exception) {
  62015. reject(exception);
  62016. });
  62017. });
  62018. };
  62019. /**
  62020. * The configuration.
  62021. */
  62022. DracoCompression.Configuration = {
  62023. decoder: {
  62024. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62025. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62026. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62027. }
  62028. };
  62029. return DracoCompression;
  62030. }());
  62031. BABYLON.DracoCompression = DracoCompression;
  62032. })(BABYLON || (BABYLON = {}));
  62033. //# sourceMappingURL=babylon.dracoCompression.js.map
  62034. var BABYLON;
  62035. (function (BABYLON) {
  62036. var AudioEngine = /** @class */ (function () {
  62037. function AudioEngine() {
  62038. this._audioContext = null;
  62039. this._audioContextInitialized = false;
  62040. this.canUseWebAudio = false;
  62041. this.WarnedWebAudioUnsupported = false;
  62042. this.unlocked = false;
  62043. this.isMP3supported = false;
  62044. this.isOGGsupported = false;
  62045. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62046. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62047. this.canUseWebAudio = true;
  62048. }
  62049. var audioElem = document.createElement('audio');
  62050. try {
  62051. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62052. this.isMP3supported = true;
  62053. }
  62054. }
  62055. catch (e) {
  62056. // protect error during capability check.
  62057. }
  62058. try {
  62059. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62060. this.isOGGsupported = true;
  62061. }
  62062. }
  62063. catch (e) {
  62064. // protect error during capability check.
  62065. }
  62066. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62067. this._unlockiOSaudio();
  62068. }
  62069. else {
  62070. this.unlocked = true;
  62071. }
  62072. }
  62073. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62074. get: function () {
  62075. if (!this._audioContextInitialized) {
  62076. this._initializeAudioContext();
  62077. }
  62078. return this._audioContext;
  62079. },
  62080. enumerable: true,
  62081. configurable: true
  62082. });
  62083. AudioEngine.prototype._unlockiOSaudio = function () {
  62084. var _this = this;
  62085. var unlockaudio = function () {
  62086. if (!_this.audioContext) {
  62087. return;
  62088. }
  62089. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62090. var source = _this.audioContext.createBufferSource();
  62091. source.buffer = buffer;
  62092. source.connect(_this.audioContext.destination);
  62093. source.start(0);
  62094. setTimeout(function () {
  62095. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62096. _this.unlocked = true;
  62097. window.removeEventListener('touchend', unlockaudio, false);
  62098. if (_this.onAudioUnlocked) {
  62099. _this.onAudioUnlocked();
  62100. }
  62101. }
  62102. }, 0);
  62103. };
  62104. window.addEventListener('touchend', unlockaudio, false);
  62105. };
  62106. AudioEngine.prototype._initializeAudioContext = function () {
  62107. try {
  62108. if (this.canUseWebAudio) {
  62109. this._audioContext = new AudioContext();
  62110. // create a global volume gain node
  62111. this.masterGain = this._audioContext.createGain();
  62112. this.masterGain.gain.value = 1;
  62113. this.masterGain.connect(this._audioContext.destination);
  62114. this._audioContextInitialized = true;
  62115. }
  62116. }
  62117. catch (e) {
  62118. this.canUseWebAudio = false;
  62119. BABYLON.Tools.Error("Web Audio: " + e.message);
  62120. }
  62121. };
  62122. AudioEngine.prototype.dispose = function () {
  62123. if (this.canUseWebAudio && this._audioContextInitialized) {
  62124. if (this._connectedAnalyser && this._audioContext) {
  62125. this._connectedAnalyser.stopDebugCanvas();
  62126. this._connectedAnalyser.dispose();
  62127. this.masterGain.disconnect();
  62128. this.masterGain.connect(this._audioContext.destination);
  62129. this._connectedAnalyser = null;
  62130. }
  62131. this.masterGain.gain.value = 1;
  62132. }
  62133. this.WarnedWebAudioUnsupported = false;
  62134. };
  62135. AudioEngine.prototype.getGlobalVolume = function () {
  62136. if (this.canUseWebAudio && this._audioContextInitialized) {
  62137. return this.masterGain.gain.value;
  62138. }
  62139. else {
  62140. return -1;
  62141. }
  62142. };
  62143. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62144. if (this.canUseWebAudio && this._audioContextInitialized) {
  62145. this.masterGain.gain.value = newVolume;
  62146. }
  62147. };
  62148. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62149. if (this._connectedAnalyser) {
  62150. this._connectedAnalyser.stopDebugCanvas();
  62151. }
  62152. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62153. this._connectedAnalyser = analyser;
  62154. this.masterGain.disconnect();
  62155. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62156. }
  62157. };
  62158. return AudioEngine;
  62159. }());
  62160. BABYLON.AudioEngine = AudioEngine;
  62161. })(BABYLON || (BABYLON = {}));
  62162. //# sourceMappingURL=babylon.audioEngine.js.map
  62163. var BABYLON;
  62164. (function (BABYLON) {
  62165. var Sound = /** @class */ (function () {
  62166. /**
  62167. * Create a sound and attach it to a scene
  62168. * @param name Name of your sound
  62169. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer
  62170. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62171. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62172. */
  62173. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62174. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62175. var _this = this;
  62176. this.autoplay = false;
  62177. this.loop = false;
  62178. this.useCustomAttenuation = false;
  62179. this.spatialSound = false;
  62180. this.refDistance = 1;
  62181. this.rolloffFactor = 1;
  62182. this.maxDistance = 100;
  62183. this.distanceModel = "linear";
  62184. this._panningModel = "equalpower";
  62185. this._playbackRate = 1;
  62186. this._streaming = false;
  62187. this._startTime = 0;
  62188. this._startOffset = 0;
  62189. this._position = BABYLON.Vector3.Zero();
  62190. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62191. this._volume = 1;
  62192. this._isReadyToPlay = false;
  62193. this.isPlaying = false;
  62194. this.isPaused = false;
  62195. this._isDirectional = false;
  62196. // Used if you'd like to create a directional sound.
  62197. // If not set, the sound will be omnidirectional
  62198. this._coneInnerAngle = 360;
  62199. this._coneOuterAngle = 360;
  62200. this._coneOuterGain = 0;
  62201. this._isOutputConnected = false;
  62202. this._urlType = "Unknown";
  62203. this.name = name;
  62204. this._scene = scene;
  62205. this._readyToPlayCallback = readyToPlayCallback;
  62206. // Default custom attenuation function is a linear attenuation
  62207. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62208. if (currentDistance < maxDistance) {
  62209. return currentVolume * (1 - currentDistance / maxDistance);
  62210. }
  62211. else {
  62212. return 0;
  62213. }
  62214. };
  62215. if (options) {
  62216. this.autoplay = options.autoplay || false;
  62217. this.loop = options.loop || false;
  62218. // if volume === 0, we need another way to check this option
  62219. if (options.volume !== undefined) {
  62220. this._volume = options.volume;
  62221. }
  62222. this.spatialSound = options.spatialSound || false;
  62223. this.maxDistance = options.maxDistance || 100;
  62224. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62225. this.rolloffFactor = options.rolloffFactor || 1;
  62226. this.refDistance = options.refDistance || 1;
  62227. this.distanceModel = options.distanceModel || "linear";
  62228. this._playbackRate = options.playbackRate || 1;
  62229. this._streaming = options.streaming || false;
  62230. }
  62231. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62232. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62233. this._soundGain.gain.value = this._volume;
  62234. this._inputAudioNode = this._soundGain;
  62235. this._ouputAudioNode = this._soundGain;
  62236. if (this.spatialSound) {
  62237. this._createSpatialParameters();
  62238. }
  62239. this._scene.mainSoundTrack.AddSound(this);
  62240. var validParameter = true;
  62241. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62242. if (urlOrArrayBuffer) {
  62243. try {
  62244. if (typeof (urlOrArrayBuffer) === "string")
  62245. this._urlType = "String";
  62246. if (Array.isArray(urlOrArrayBuffer))
  62247. this._urlType = "Array";
  62248. if (urlOrArrayBuffer instanceof ArrayBuffer)
  62249. this._urlType = "ArrayBuffer";
  62250. var urls = [];
  62251. var codecSupportedFound = false;
  62252. switch (this._urlType) {
  62253. case "ArrayBuffer":
  62254. if (urlOrArrayBuffer.byteLength > 0) {
  62255. codecSupportedFound = true;
  62256. this._soundLoaded(urlOrArrayBuffer);
  62257. }
  62258. break;
  62259. case "String":
  62260. urls.push(urlOrArrayBuffer);
  62261. case "Array":
  62262. if (urls.length === 0)
  62263. urls = urlOrArrayBuffer;
  62264. // If we found a supported format, we load it immediately and stop the loop
  62265. for (var i = 0; i < urls.length; i++) {
  62266. var url = urls[i];
  62267. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62268. codecSupportedFound = true;
  62269. }
  62270. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62271. codecSupportedFound = true;
  62272. }
  62273. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62274. codecSupportedFound = true;
  62275. }
  62276. if (url.indexOf("blob:") !== -1) {
  62277. codecSupportedFound = true;
  62278. }
  62279. if (codecSupportedFound) {
  62280. // Loading sound using XHR2
  62281. if (!this._streaming) {
  62282. this._scene._loadFile(url, function (data) {
  62283. _this._soundLoaded(data);
  62284. }, undefined, true, true, function (exception) {
  62285. if (exception) {
  62286. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62287. }
  62288. BABYLON.Tools.Error("Sound creation aborted.");
  62289. _this._scene.mainSoundTrack.RemoveSound(_this);
  62290. });
  62291. }
  62292. // Streaming sound using HTML5 Audio tag
  62293. else {
  62294. this._htmlAudioElement = new Audio(url);
  62295. this._htmlAudioElement.controls = false;
  62296. this._htmlAudioElement.loop = this.loop;
  62297. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62298. this._htmlAudioElement.preload = "auto";
  62299. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62300. _this._isReadyToPlay = true;
  62301. if (_this.autoplay) {
  62302. _this.play();
  62303. }
  62304. if (_this._readyToPlayCallback) {
  62305. _this._readyToPlayCallback();
  62306. }
  62307. });
  62308. document.body.appendChild(this._htmlAudioElement);
  62309. }
  62310. break;
  62311. }
  62312. }
  62313. break;
  62314. default:
  62315. validParameter = false;
  62316. break;
  62317. }
  62318. if (!validParameter) {
  62319. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62320. }
  62321. else {
  62322. if (!codecSupportedFound) {
  62323. this._isReadyToPlay = true;
  62324. // Simulating a ready to play event to avoid breaking code path
  62325. if (this._readyToPlayCallback) {
  62326. window.setTimeout(function () {
  62327. if (_this._readyToPlayCallback) {
  62328. _this._readyToPlayCallback();
  62329. }
  62330. }, 1000);
  62331. }
  62332. }
  62333. }
  62334. }
  62335. catch (ex) {
  62336. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62337. this._scene.mainSoundTrack.RemoveSound(this);
  62338. }
  62339. }
  62340. }
  62341. else {
  62342. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62343. this._scene.mainSoundTrack.AddSound(this);
  62344. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62345. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62346. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62347. }
  62348. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62349. if (this._readyToPlayCallback) {
  62350. window.setTimeout(function () {
  62351. if (_this._readyToPlayCallback) {
  62352. _this._readyToPlayCallback();
  62353. }
  62354. }, 1000);
  62355. }
  62356. }
  62357. }
  62358. Sound.prototype.dispose = function () {
  62359. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62360. if (this.isPlaying) {
  62361. this.stop();
  62362. }
  62363. this._isReadyToPlay = false;
  62364. if (this.soundTrackId === -1) {
  62365. this._scene.mainSoundTrack.RemoveSound(this);
  62366. }
  62367. else {
  62368. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62369. }
  62370. if (this._soundGain) {
  62371. this._soundGain.disconnect();
  62372. this._soundGain = null;
  62373. }
  62374. if (this._soundPanner) {
  62375. this._soundPanner.disconnect();
  62376. this._soundPanner = null;
  62377. }
  62378. if (this._soundSource) {
  62379. this._soundSource.disconnect();
  62380. this._soundSource = null;
  62381. }
  62382. this._audioBuffer = null;
  62383. if (this._htmlAudioElement) {
  62384. this._htmlAudioElement.pause();
  62385. this._htmlAudioElement.src = "";
  62386. document.body.removeChild(this._htmlAudioElement);
  62387. }
  62388. if (this._connectedMesh && this._registerFunc) {
  62389. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62390. this._connectedMesh = null;
  62391. }
  62392. }
  62393. };
  62394. Sound.prototype.isReady = function () {
  62395. return this._isReadyToPlay;
  62396. };
  62397. Sound.prototype._soundLoaded = function (audioData) {
  62398. var _this = this;
  62399. if (!BABYLON.Engine.audioEngine.audioContext) {
  62400. return;
  62401. }
  62402. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62403. _this._audioBuffer = buffer;
  62404. _this._isReadyToPlay = true;
  62405. if (_this.autoplay) {
  62406. _this.play();
  62407. }
  62408. if (_this._readyToPlayCallback) {
  62409. _this._readyToPlayCallback();
  62410. }
  62411. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62412. };
  62413. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62414. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62415. this._audioBuffer = audioBuffer;
  62416. this._isReadyToPlay = true;
  62417. }
  62418. };
  62419. Sound.prototype.updateOptions = function (options) {
  62420. if (options) {
  62421. this.loop = options.loop || this.loop;
  62422. this.maxDistance = options.maxDistance || this.maxDistance;
  62423. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62424. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62425. this.refDistance = options.refDistance || this.refDistance;
  62426. this.distanceModel = options.distanceModel || this.distanceModel;
  62427. this._playbackRate = options.playbackRate || this._playbackRate;
  62428. this._updateSpatialParameters();
  62429. if (this.isPlaying) {
  62430. if (this._streaming) {
  62431. this._htmlAudioElement.playbackRate = this._playbackRate;
  62432. }
  62433. else {
  62434. if (this._soundSource) {
  62435. this._soundSource.playbackRate.value = this._playbackRate;
  62436. }
  62437. }
  62438. }
  62439. }
  62440. };
  62441. Sound.prototype._createSpatialParameters = function () {
  62442. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62443. if (this._scene.headphone) {
  62444. this._panningModel = "HRTF";
  62445. }
  62446. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62447. this._updateSpatialParameters();
  62448. this._soundPanner.connect(this._ouputAudioNode);
  62449. this._inputAudioNode = this._soundPanner;
  62450. }
  62451. };
  62452. Sound.prototype._updateSpatialParameters = function () {
  62453. if (this.spatialSound && this._soundPanner) {
  62454. if (this.useCustomAttenuation) {
  62455. // Tricks to disable in a way embedded Web Audio attenuation
  62456. this._soundPanner.distanceModel = "linear";
  62457. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62458. this._soundPanner.refDistance = 1;
  62459. this._soundPanner.rolloffFactor = 1;
  62460. this._soundPanner.panningModel = this._panningModel;
  62461. }
  62462. else {
  62463. this._soundPanner.distanceModel = this.distanceModel;
  62464. this._soundPanner.maxDistance = this.maxDistance;
  62465. this._soundPanner.refDistance = this.refDistance;
  62466. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62467. this._soundPanner.panningModel = this._panningModel;
  62468. }
  62469. }
  62470. };
  62471. Sound.prototype.switchPanningModelToHRTF = function () {
  62472. this._panningModel = "HRTF";
  62473. this._switchPanningModel();
  62474. };
  62475. Sound.prototype.switchPanningModelToEqualPower = function () {
  62476. this._panningModel = "equalpower";
  62477. this._switchPanningModel();
  62478. };
  62479. Sound.prototype._switchPanningModel = function () {
  62480. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62481. this._soundPanner.panningModel = this._panningModel;
  62482. }
  62483. };
  62484. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62485. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62486. if (this._isOutputConnected) {
  62487. this._ouputAudioNode.disconnect();
  62488. }
  62489. this._ouputAudioNode.connect(soundTrackAudioNode);
  62490. this._isOutputConnected = true;
  62491. }
  62492. };
  62493. /**
  62494. * Transform this sound into a directional source
  62495. * @param coneInnerAngle Size of the inner cone in degree
  62496. * @param coneOuterAngle Size of the outer cone in degree
  62497. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62498. */
  62499. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62500. if (coneOuterAngle < coneInnerAngle) {
  62501. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62502. return;
  62503. }
  62504. this._coneInnerAngle = coneInnerAngle;
  62505. this._coneOuterAngle = coneOuterAngle;
  62506. this._coneOuterGain = coneOuterGain;
  62507. this._isDirectional = true;
  62508. if (this.isPlaying && this.loop) {
  62509. this.stop();
  62510. this.play();
  62511. }
  62512. };
  62513. Sound.prototype.setPosition = function (newPosition) {
  62514. this._position = newPosition;
  62515. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62516. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62517. }
  62518. };
  62519. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62520. this._localDirection = newLocalDirection;
  62521. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62522. this._updateDirection();
  62523. }
  62524. };
  62525. Sound.prototype._updateDirection = function () {
  62526. if (!this._connectedMesh || !this._soundPanner) {
  62527. return;
  62528. }
  62529. var mat = this._connectedMesh.getWorldMatrix();
  62530. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62531. direction.normalize();
  62532. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62533. };
  62534. Sound.prototype.updateDistanceFromListener = function () {
  62535. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62536. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62537. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62538. }
  62539. };
  62540. Sound.prototype.setAttenuationFunction = function (callback) {
  62541. this._customAttenuationFunction = callback;
  62542. };
  62543. /**
  62544. * Play the sound
  62545. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62546. * @param offset (optional) Start the sound setting it at a specific time
  62547. */
  62548. Sound.prototype.play = function (time, offset) {
  62549. var _this = this;
  62550. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62551. try {
  62552. if (this._startOffset < 0) {
  62553. time = -this._startOffset;
  62554. this._startOffset = 0;
  62555. }
  62556. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62557. if (!this._soundSource || !this._streamingSource) {
  62558. if (this.spatialSound && this._soundPanner) {
  62559. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62560. if (this._isDirectional) {
  62561. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62562. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62563. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62564. if (this._connectedMesh) {
  62565. this._updateDirection();
  62566. }
  62567. else {
  62568. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62569. }
  62570. }
  62571. }
  62572. }
  62573. if (this._streaming) {
  62574. if (!this._streamingSource) {
  62575. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62576. this._htmlAudioElement.onended = function () { _this._onended(); };
  62577. this._htmlAudioElement.playbackRate = this._playbackRate;
  62578. }
  62579. this._streamingSource.disconnect();
  62580. this._streamingSource.connect(this._inputAudioNode);
  62581. this._htmlAudioElement.play();
  62582. }
  62583. else {
  62584. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62585. this._soundSource.buffer = this._audioBuffer;
  62586. this._soundSource.connect(this._inputAudioNode);
  62587. this._soundSource.loop = this.loop;
  62588. this._soundSource.playbackRate.value = this._playbackRate;
  62589. this._soundSource.onended = function () { _this._onended(); };
  62590. if (this._soundSource.buffer) {
  62591. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62592. }
  62593. }
  62594. this._startTime = startTime;
  62595. this.isPlaying = true;
  62596. this.isPaused = false;
  62597. }
  62598. catch (ex) {
  62599. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62600. }
  62601. }
  62602. };
  62603. Sound.prototype._onended = function () {
  62604. this.isPlaying = false;
  62605. if (this.onended) {
  62606. this.onended();
  62607. }
  62608. };
  62609. /**
  62610. * Stop the sound
  62611. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62612. */
  62613. Sound.prototype.stop = function (time) {
  62614. if (this.isPlaying) {
  62615. if (this._streaming) {
  62616. this._htmlAudioElement.pause();
  62617. // Test needed for Firefox or it will generate an Invalid State Error
  62618. if (this._htmlAudioElement.currentTime > 0) {
  62619. this._htmlAudioElement.currentTime = 0;
  62620. }
  62621. }
  62622. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62623. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62624. this._soundSource.stop(stopTime);
  62625. this._soundSource.onended = function () { };
  62626. if (!this.isPaused) {
  62627. this._startOffset = 0;
  62628. }
  62629. }
  62630. this.isPlaying = false;
  62631. }
  62632. };
  62633. Sound.prototype.pause = function () {
  62634. if (this.isPlaying) {
  62635. this.isPaused = true;
  62636. if (this._streaming) {
  62637. this._htmlAudioElement.pause();
  62638. }
  62639. else if (BABYLON.Engine.audioEngine.audioContext) {
  62640. this.stop(0);
  62641. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62642. }
  62643. }
  62644. };
  62645. Sound.prototype.setVolume = function (newVolume, time) {
  62646. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62647. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62648. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62649. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62650. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62651. }
  62652. else {
  62653. this._soundGain.gain.value = newVolume;
  62654. }
  62655. }
  62656. this._volume = newVolume;
  62657. };
  62658. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62659. this._playbackRate = newPlaybackRate;
  62660. if (this.isPlaying) {
  62661. if (this._streaming) {
  62662. this._htmlAudioElement.playbackRate = this._playbackRate;
  62663. }
  62664. else if (this._soundSource) {
  62665. this._soundSource.playbackRate.value = this._playbackRate;
  62666. }
  62667. }
  62668. };
  62669. Sound.prototype.getVolume = function () {
  62670. return this._volume;
  62671. };
  62672. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62673. var _this = this;
  62674. if (this._connectedMesh && this._registerFunc) {
  62675. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62676. this._registerFunc = null;
  62677. }
  62678. this._connectedMesh = meshToConnectTo;
  62679. if (!this.spatialSound) {
  62680. this.spatialSound = true;
  62681. this._createSpatialParameters();
  62682. if (this.isPlaying && this.loop) {
  62683. this.stop();
  62684. this.play();
  62685. }
  62686. }
  62687. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62688. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62689. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62690. };
  62691. Sound.prototype.detachFromMesh = function () {
  62692. if (this._connectedMesh && this._registerFunc) {
  62693. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62694. this._registerFunc = null;
  62695. this._connectedMesh = null;
  62696. }
  62697. };
  62698. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62699. if (!node.getBoundingInfo) {
  62700. return;
  62701. }
  62702. var mesh = node;
  62703. var boundingInfo = mesh.getBoundingInfo();
  62704. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62705. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62706. this._updateDirection();
  62707. }
  62708. };
  62709. Sound.prototype.clone = function () {
  62710. var _this = this;
  62711. if (!this._streaming) {
  62712. var setBufferAndRun = function () {
  62713. if (_this._isReadyToPlay) {
  62714. clonedSound._audioBuffer = _this.getAudioBuffer();
  62715. clonedSound._isReadyToPlay = true;
  62716. if (clonedSound.autoplay) {
  62717. clonedSound.play();
  62718. }
  62719. }
  62720. else {
  62721. window.setTimeout(setBufferAndRun, 300);
  62722. }
  62723. };
  62724. var currentOptions = {
  62725. autoplay: this.autoplay, loop: this.loop,
  62726. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62727. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62728. refDistance: this.refDistance, distanceModel: this.distanceModel
  62729. };
  62730. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62731. if (this.useCustomAttenuation) {
  62732. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62733. }
  62734. clonedSound.setPosition(this._position);
  62735. clonedSound.setPlaybackRate(this._playbackRate);
  62736. setBufferAndRun();
  62737. return clonedSound;
  62738. }
  62739. // Can't clone a streaming sound
  62740. else {
  62741. return null;
  62742. }
  62743. };
  62744. Sound.prototype.getAudioBuffer = function () {
  62745. return this._audioBuffer;
  62746. };
  62747. Sound.prototype.serialize = function () {
  62748. var serializationObject = {
  62749. name: this.name,
  62750. url: this.name,
  62751. autoplay: this.autoplay,
  62752. loop: this.loop,
  62753. volume: this._volume,
  62754. spatialSound: this.spatialSound,
  62755. maxDistance: this.maxDistance,
  62756. rolloffFactor: this.rolloffFactor,
  62757. refDistance: this.refDistance,
  62758. distanceModel: this.distanceModel,
  62759. playbackRate: this._playbackRate,
  62760. panningModel: this._panningModel,
  62761. soundTrackId: this.soundTrackId
  62762. };
  62763. if (this.spatialSound) {
  62764. if (this._connectedMesh)
  62765. serializationObject.connectedMeshId = this._connectedMesh.id;
  62766. serializationObject.position = this._position.asArray();
  62767. serializationObject.refDistance = this.refDistance;
  62768. serializationObject.distanceModel = this.distanceModel;
  62769. serializationObject.isDirectional = this._isDirectional;
  62770. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  62771. serializationObject.coneInnerAngle = this._coneInnerAngle;
  62772. serializationObject.coneOuterAngle = this._coneOuterAngle;
  62773. serializationObject.coneOuterGain = this._coneOuterGain;
  62774. }
  62775. return serializationObject;
  62776. };
  62777. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  62778. var soundName = parsedSound.name;
  62779. var soundUrl;
  62780. if (parsedSound.url) {
  62781. soundUrl = rootUrl + parsedSound.url;
  62782. }
  62783. else {
  62784. soundUrl = rootUrl + soundName;
  62785. }
  62786. var options = {
  62787. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  62788. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  62789. rolloffFactor: parsedSound.rolloffFactor,
  62790. refDistance: parsedSound.refDistance,
  62791. distanceModel: parsedSound.distanceModel,
  62792. playbackRate: parsedSound.playbackRate
  62793. };
  62794. var newSound;
  62795. if (!sourceSound) {
  62796. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  62797. scene._addPendingData(newSound);
  62798. }
  62799. else {
  62800. var setBufferAndRun = function () {
  62801. if (sourceSound._isReadyToPlay) {
  62802. newSound._audioBuffer = sourceSound.getAudioBuffer();
  62803. newSound._isReadyToPlay = true;
  62804. if (newSound.autoplay) {
  62805. newSound.play();
  62806. }
  62807. }
  62808. else {
  62809. window.setTimeout(setBufferAndRun, 300);
  62810. }
  62811. };
  62812. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  62813. setBufferAndRun();
  62814. }
  62815. if (parsedSound.position) {
  62816. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  62817. newSound.setPosition(soundPosition);
  62818. }
  62819. if (parsedSound.isDirectional) {
  62820. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  62821. if (parsedSound.localDirectionToMesh) {
  62822. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  62823. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  62824. }
  62825. }
  62826. if (parsedSound.connectedMeshId) {
  62827. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  62828. if (connectedMesh) {
  62829. newSound.attachToMesh(connectedMesh);
  62830. }
  62831. }
  62832. return newSound;
  62833. };
  62834. return Sound;
  62835. }());
  62836. BABYLON.Sound = Sound;
  62837. })(BABYLON || (BABYLON = {}));
  62838. //# sourceMappingURL=babylon.sound.js.map
  62839. var BABYLON;
  62840. (function (BABYLON) {
  62841. var SoundTrack = /** @class */ (function () {
  62842. function SoundTrack(scene, options) {
  62843. this.id = -1;
  62844. this._isMainTrack = false;
  62845. this._isInitialized = false;
  62846. this._scene = scene;
  62847. this.soundCollection = new Array();
  62848. this._options = options;
  62849. if (!this._isMainTrack) {
  62850. this._scene.soundTracks.push(this);
  62851. this.id = this._scene.soundTracks.length - 1;
  62852. }
  62853. }
  62854. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  62855. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62856. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  62857. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  62858. if (this._options) {
  62859. if (this._options.volume) {
  62860. this._outputAudioNode.gain.value = this._options.volume;
  62861. }
  62862. if (this._options.mainTrack) {
  62863. this._isMainTrack = this._options.mainTrack;
  62864. }
  62865. }
  62866. this._isInitialized = true;
  62867. }
  62868. };
  62869. SoundTrack.prototype.dispose = function () {
  62870. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  62871. if (this._connectedAnalyser) {
  62872. this._connectedAnalyser.stopDebugCanvas();
  62873. }
  62874. while (this.soundCollection.length) {
  62875. this.soundCollection[0].dispose();
  62876. }
  62877. if (this._outputAudioNode) {
  62878. this._outputAudioNode.disconnect();
  62879. }
  62880. this._outputAudioNode = null;
  62881. }
  62882. };
  62883. SoundTrack.prototype.AddSound = function (sound) {
  62884. if (!this._isInitialized) {
  62885. this._initializeSoundTrackAudioGraph();
  62886. }
  62887. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62888. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  62889. }
  62890. if (sound.soundTrackId) {
  62891. if (sound.soundTrackId === -1) {
  62892. this._scene.mainSoundTrack.RemoveSound(sound);
  62893. }
  62894. else {
  62895. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  62896. }
  62897. }
  62898. this.soundCollection.push(sound);
  62899. sound.soundTrackId = this.id;
  62900. };
  62901. SoundTrack.prototype.RemoveSound = function (sound) {
  62902. var index = this.soundCollection.indexOf(sound);
  62903. if (index !== -1) {
  62904. this.soundCollection.splice(index, 1);
  62905. }
  62906. };
  62907. SoundTrack.prototype.setVolume = function (newVolume) {
  62908. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62909. this._outputAudioNode.gain.value = newVolume;
  62910. }
  62911. };
  62912. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  62913. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62914. for (var i = 0; i < this.soundCollection.length; i++) {
  62915. this.soundCollection[i].switchPanningModelToHRTF();
  62916. }
  62917. }
  62918. };
  62919. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  62920. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62921. for (var i = 0; i < this.soundCollection.length; i++) {
  62922. this.soundCollection[i].switchPanningModelToEqualPower();
  62923. }
  62924. }
  62925. };
  62926. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  62927. if (this._connectedAnalyser) {
  62928. this._connectedAnalyser.stopDebugCanvas();
  62929. }
  62930. this._connectedAnalyser = analyser;
  62931. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  62932. this._outputAudioNode.disconnect();
  62933. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  62934. }
  62935. };
  62936. return SoundTrack;
  62937. }());
  62938. BABYLON.SoundTrack = SoundTrack;
  62939. })(BABYLON || (BABYLON = {}));
  62940. //# sourceMappingURL=babylon.soundtrack.js.map
  62941. var BABYLON;
  62942. (function (BABYLON) {
  62943. /**
  62944. * Class used to work with sound analyzer using fast fourier transform (FFT)
  62945. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  62946. */
  62947. var Analyser = /** @class */ (function () {
  62948. /**
  62949. * Creates a new analyser
  62950. * @param scene defines hosting scene
  62951. */
  62952. function Analyser(scene) {
  62953. /**
  62954. * Gets or sets the smoothing
  62955. * @ignorenaming
  62956. */
  62957. this.SMOOTHING = 0.75;
  62958. /**
  62959. * Gets or sets the FFT table size
  62960. * @ignorenaming
  62961. */
  62962. this.FFT_SIZE = 512;
  62963. /**
  62964. * Gets or sets the bar graph amplitude
  62965. * @ignorenaming
  62966. */
  62967. this.BARGRAPHAMPLITUDE = 256;
  62968. /**
  62969. * Gets or sets the position of the debug canvas
  62970. * @ignorenaming
  62971. */
  62972. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  62973. /**
  62974. * Gets or sets the debug canvas size
  62975. * @ignorenaming
  62976. */
  62977. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  62978. this._scene = scene;
  62979. this._audioEngine = BABYLON.Engine.audioEngine;
  62980. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  62981. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  62982. this._webAudioAnalyser.minDecibels = -140;
  62983. this._webAudioAnalyser.maxDecibels = 0;
  62984. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62985. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  62986. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  62987. }
  62988. }
  62989. /**
  62990. * Get the number of data values you will have to play with for the visualization
  62991. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  62992. * @returns a number
  62993. */
  62994. Analyser.prototype.getFrequencyBinCount = function () {
  62995. if (this._audioEngine.canUseWebAudio) {
  62996. return this._webAudioAnalyser.frequencyBinCount;
  62997. }
  62998. else {
  62999. return 0;
  63000. }
  63001. };
  63002. /**
  63003. * Gets the current frequency data as a byte array
  63004. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63005. * @returns a Uint8Array
  63006. */
  63007. Analyser.prototype.getByteFrequencyData = function () {
  63008. if (this._audioEngine.canUseWebAudio) {
  63009. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63010. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63011. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63012. }
  63013. return this._byteFreqs;
  63014. };
  63015. /**
  63016. * Gets the current waveform as a byte array
  63017. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63018. * @returns a Uint8Array
  63019. */
  63020. Analyser.prototype.getByteTimeDomainData = function () {
  63021. if (this._audioEngine.canUseWebAudio) {
  63022. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63023. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63024. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63025. }
  63026. return this._byteTime;
  63027. };
  63028. /**
  63029. * Gets the current frequency data as a float array
  63030. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63031. * @returns a Float32Array
  63032. */
  63033. Analyser.prototype.getFloatFrequencyData = function () {
  63034. if (this._audioEngine.canUseWebAudio) {
  63035. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63036. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63037. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63038. }
  63039. return this._floatFreqs;
  63040. };
  63041. /**
  63042. * Renders the debug canvas
  63043. */
  63044. Analyser.prototype.drawDebugCanvas = function () {
  63045. var _this = this;
  63046. if (this._audioEngine.canUseWebAudio) {
  63047. if (!this._debugCanvas) {
  63048. this._debugCanvas = document.createElement("canvas");
  63049. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63050. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63051. this._debugCanvas.style.position = "absolute";
  63052. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63053. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63054. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63055. document.body.appendChild(this._debugCanvas);
  63056. this._registerFunc = function () {
  63057. _this.drawDebugCanvas();
  63058. };
  63059. this._scene.registerBeforeRender(this._registerFunc);
  63060. }
  63061. if (this._registerFunc && this._debugCanvasContext) {
  63062. var workingArray = this.getByteFrequencyData();
  63063. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63064. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63065. // Draw the frequency domain chart.
  63066. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63067. var value = workingArray[i];
  63068. var percent = value / this.BARGRAPHAMPLITUDE;
  63069. var height = this.DEBUGCANVASSIZE.height * percent;
  63070. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63071. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63072. var hue = i / this.getFrequencyBinCount() * 360;
  63073. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63074. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63075. }
  63076. }
  63077. }
  63078. };
  63079. /**
  63080. * Stops rendering the debug canvas and removes it
  63081. */
  63082. Analyser.prototype.stopDebugCanvas = function () {
  63083. if (this._debugCanvas) {
  63084. if (this._registerFunc) {
  63085. this._scene.unregisterBeforeRender(this._registerFunc);
  63086. this._registerFunc = null;
  63087. }
  63088. document.body.removeChild(this._debugCanvas);
  63089. this._debugCanvas = null;
  63090. this._debugCanvasContext = null;
  63091. }
  63092. };
  63093. /**
  63094. * Connects two audio nodes
  63095. * @param inputAudioNode defines first node to connect
  63096. * @param outputAudioNode defines second node to connect
  63097. */
  63098. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63099. if (this._audioEngine.canUseWebAudio) {
  63100. inputAudioNode.connect(this._webAudioAnalyser);
  63101. this._webAudioAnalyser.connect(outputAudioNode);
  63102. }
  63103. };
  63104. /**
  63105. * Releases all associated resources
  63106. */
  63107. Analyser.prototype.dispose = function () {
  63108. if (this._audioEngine.canUseWebAudio) {
  63109. this._webAudioAnalyser.disconnect();
  63110. }
  63111. };
  63112. return Analyser;
  63113. }());
  63114. BABYLON.Analyser = Analyser;
  63115. })(BABYLON || (BABYLON = {}));
  63116. //# sourceMappingURL=babylon.analyser.js.map
  63117. var BABYLON;
  63118. (function (BABYLON) {
  63119. var CubeTexture = /** @class */ (function (_super) {
  63120. __extends(CubeTexture, _super);
  63121. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension) {
  63122. if (extensions === void 0) { extensions = null; }
  63123. if (noMipmap === void 0) { noMipmap = false; }
  63124. if (files === void 0) { files = null; }
  63125. if (onLoad === void 0) { onLoad = null; }
  63126. if (onError === void 0) { onError = null; }
  63127. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63128. if (prefiltered === void 0) { prefiltered = false; }
  63129. if (forcedExtension === void 0) { forcedExtension = null; }
  63130. var _this = _super.call(this, scene) || this;
  63131. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63132. /**
  63133. * Gets or sets the center of the bounding box associated with the cube texture
  63134. * It must define where the camera used to render the texture was set
  63135. */
  63136. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63137. _this._rotationY = 0;
  63138. _this.name = rootUrl;
  63139. _this.url = rootUrl;
  63140. _this._noMipmap = noMipmap;
  63141. _this.hasAlpha = false;
  63142. _this._format = format;
  63143. _this._prefiltered = prefiltered;
  63144. _this.isCube = true;
  63145. _this._textureMatrix = BABYLON.Matrix.Identity();
  63146. if (prefiltered) {
  63147. _this.gammaSpace = false;
  63148. }
  63149. if (!rootUrl && !files) {
  63150. return _this;
  63151. }
  63152. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63153. var lastDot = rootUrl.lastIndexOf(".");
  63154. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63155. var isDDS = (extension === ".dds");
  63156. if (!files) {
  63157. if (!isDDS && !extensions) {
  63158. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63159. }
  63160. files = [];
  63161. if (extensions) {
  63162. for (var index = 0; index < extensions.length; index++) {
  63163. files.push(rootUrl + extensions[index]);
  63164. }
  63165. }
  63166. }
  63167. _this._files = files;
  63168. if (!_this._texture) {
  63169. if (!scene.useDelayedTextureLoading) {
  63170. if (prefiltered) {
  63171. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, _this.lodGenerationScale, _this.lodGenerationOffset, onLoad, onError, format, forcedExtension);
  63172. }
  63173. else {
  63174. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension);
  63175. }
  63176. }
  63177. else {
  63178. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63179. }
  63180. }
  63181. else if (onLoad) {
  63182. if (_this._texture.isReady) {
  63183. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63184. }
  63185. else {
  63186. _this._texture.onLoadedObservable.add(onLoad);
  63187. }
  63188. }
  63189. return _this;
  63190. }
  63191. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63192. get: function () {
  63193. return this._boundingBoxSize;
  63194. },
  63195. /**
  63196. * Gets or sets the size of the bounding box associated with the cube texture
  63197. * When defined, the cubemap will switch to local mode
  63198. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63199. * @example https://www.babylonjs-playground.com/#RNASML
  63200. */
  63201. set: function (value) {
  63202. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63203. return;
  63204. }
  63205. this._boundingBoxSize = value;
  63206. var scene = this.getScene();
  63207. if (scene) {
  63208. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63209. }
  63210. },
  63211. enumerable: true,
  63212. configurable: true
  63213. });
  63214. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63215. /**
  63216. * Gets texture matrix rotation angle around Y axis radians.
  63217. */
  63218. get: function () {
  63219. return this._rotationY;
  63220. },
  63221. /**
  63222. * Sets texture matrix rotation angle around Y axis in radians.
  63223. */
  63224. set: function (value) {
  63225. this._rotationY = value;
  63226. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63227. },
  63228. enumerable: true,
  63229. configurable: true
  63230. });
  63231. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63232. var rootUrlKey = "";
  63233. files.forEach(function (url) { return rootUrlKey += url; });
  63234. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63235. };
  63236. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension) {
  63237. if (forcedExtension === void 0) { forcedExtension = null; }
  63238. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension);
  63239. };
  63240. // Methods
  63241. CubeTexture.prototype.delayLoad = function () {
  63242. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63243. return;
  63244. }
  63245. var scene = this.getScene();
  63246. if (!scene) {
  63247. return;
  63248. }
  63249. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63250. this._texture = this._getFromCache(this.url, this._noMipmap);
  63251. if (!this._texture) {
  63252. if (this._prefiltered) {
  63253. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format);
  63254. }
  63255. else {
  63256. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63257. }
  63258. }
  63259. };
  63260. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63261. return this._textureMatrix;
  63262. };
  63263. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63264. this._textureMatrix = value;
  63265. };
  63266. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63267. var texture = BABYLON.SerializationHelper.Parse(function () {
  63268. var prefiltered = false;
  63269. if (parsedTexture.prefiltered) {
  63270. prefiltered = parsedTexture.prefiltered;
  63271. }
  63272. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63273. }, parsedTexture, scene);
  63274. // Local Cubemaps
  63275. if (parsedTexture.boundingBoxPosition) {
  63276. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63277. }
  63278. if (parsedTexture.boundingBoxSize) {
  63279. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63280. }
  63281. // Animations
  63282. if (parsedTexture.animations) {
  63283. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63284. var parsedAnimation = parsedTexture.animations[animationIndex];
  63285. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63286. }
  63287. }
  63288. return texture;
  63289. };
  63290. CubeTexture.prototype.clone = function () {
  63291. var _this = this;
  63292. return BABYLON.SerializationHelper.Clone(function () {
  63293. var scene = _this.getScene();
  63294. if (!scene) {
  63295. return _this;
  63296. }
  63297. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63298. }, this);
  63299. };
  63300. __decorate([
  63301. BABYLON.serialize("rotationY")
  63302. ], CubeTexture.prototype, "_rotationY", void 0);
  63303. return CubeTexture;
  63304. }(BABYLON.BaseTexture));
  63305. BABYLON.CubeTexture = CubeTexture;
  63306. })(BABYLON || (BABYLON = {}));
  63307. //# sourceMappingURL=babylon.cubeTexture.js.map
  63308. var BABYLON;
  63309. (function (BABYLON) {
  63310. var RenderTargetTexture = /** @class */ (function (_super) {
  63311. __extends(RenderTargetTexture, _super);
  63312. /**
  63313. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63314. * or used a shadow, depth texture...
  63315. * @param name The friendly name of the texture
  63316. * @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)
  63317. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63318. * @param generateMipMaps True if mip maps need to be generated after render.
  63319. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63320. * @param type The type of the buffer in the RTT (int, half float, float...)
  63321. * @param isCube True if a cube texture needs to be created
  63322. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63323. * @param generateDepthBuffer True to generate a depth buffer
  63324. * @param generateStencilBuffer True to generate a stencil buffer
  63325. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63326. */
  63327. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti) {
  63328. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63329. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63330. if (isCube === void 0) { isCube = false; }
  63331. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63332. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63333. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63334. if (isMulti === void 0) { isMulti = false; }
  63335. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63336. _this.isCube = isCube;
  63337. /**
  63338. * Use this list to define the list of mesh you want to render.
  63339. */
  63340. _this.renderList = new Array();
  63341. _this.renderParticles = true;
  63342. _this.renderSprites = false;
  63343. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63344. _this.ignoreCameraViewport = false;
  63345. // Events
  63346. /**
  63347. * An event triggered when the texture is unbind.
  63348. */
  63349. _this.onBeforeBindObservable = new BABYLON.Observable();
  63350. /**
  63351. * An event triggered when the texture is unbind.
  63352. */
  63353. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63354. /**
  63355. * An event triggered before rendering the texture
  63356. */
  63357. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63358. /**
  63359. * An event triggered after rendering the texture
  63360. */
  63361. _this.onAfterRenderObservable = new BABYLON.Observable();
  63362. /**
  63363. * An event triggered after the texture clear
  63364. */
  63365. _this.onClearObservable = new BABYLON.Observable();
  63366. _this._currentRefreshId = -1;
  63367. _this._refreshRate = 1;
  63368. _this._samples = 1;
  63369. /**
  63370. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63371. * It must define where the camera used to render the texture is set
  63372. */
  63373. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63374. scene = _this.getScene();
  63375. if (!scene) {
  63376. return _this;
  63377. }
  63378. _this._engine = scene.getEngine();
  63379. _this.name = name;
  63380. _this.isRenderTarget = true;
  63381. _this._initialSizeParameter = size;
  63382. _this._processSizeParameter(size);
  63383. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63384. });
  63385. _this._generateMipMaps = generateMipMaps ? true : false;
  63386. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63387. // Rendering groups
  63388. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63389. if (isMulti) {
  63390. return _this;
  63391. }
  63392. _this._renderTargetOptions = {
  63393. generateMipMaps: generateMipMaps,
  63394. type: type,
  63395. samplingMode: samplingMode,
  63396. generateDepthBuffer: generateDepthBuffer,
  63397. generateStencilBuffer: generateStencilBuffer
  63398. };
  63399. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63400. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63401. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63402. }
  63403. if (isCube) {
  63404. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63405. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63406. _this._textureMatrix = BABYLON.Matrix.Identity();
  63407. }
  63408. else {
  63409. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63410. }
  63411. return _this;
  63412. }
  63413. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63414. get: function () {
  63415. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63416. },
  63417. enumerable: true,
  63418. configurable: true
  63419. });
  63420. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63421. get: function () {
  63422. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63423. },
  63424. enumerable: true,
  63425. configurable: true
  63426. });
  63427. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63428. get: function () {
  63429. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63430. },
  63431. enumerable: true,
  63432. configurable: true
  63433. });
  63434. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63435. set: function (callback) {
  63436. if (this._onAfterUnbindObserver) {
  63437. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63438. }
  63439. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63440. },
  63441. enumerable: true,
  63442. configurable: true
  63443. });
  63444. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63445. set: function (callback) {
  63446. if (this._onBeforeRenderObserver) {
  63447. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63448. }
  63449. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63450. },
  63451. enumerable: true,
  63452. configurable: true
  63453. });
  63454. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63455. set: function (callback) {
  63456. if (this._onAfterRenderObserver) {
  63457. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63458. }
  63459. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63460. },
  63461. enumerable: true,
  63462. configurable: true
  63463. });
  63464. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63465. set: function (callback) {
  63466. if (this._onClearObserver) {
  63467. this.onClearObservable.remove(this._onClearObserver);
  63468. }
  63469. this._onClearObserver = this.onClearObservable.add(callback);
  63470. },
  63471. enumerable: true,
  63472. configurable: true
  63473. });
  63474. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63475. get: function () {
  63476. return this._renderTargetOptions;
  63477. },
  63478. enumerable: true,
  63479. configurable: true
  63480. });
  63481. RenderTargetTexture.prototype._onRatioRescale = function () {
  63482. if (this._sizeRatio) {
  63483. this.resize(this._initialSizeParameter);
  63484. }
  63485. };
  63486. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63487. get: function () {
  63488. return this._boundingBoxSize;
  63489. },
  63490. /**
  63491. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63492. * When defined, the cubemap will switch to local mode
  63493. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63494. * @example https://www.babylonjs-playground.com/#RNASML
  63495. */
  63496. set: function (value) {
  63497. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63498. return;
  63499. }
  63500. this._boundingBoxSize = value;
  63501. var scene = this.getScene();
  63502. if (scene) {
  63503. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63504. }
  63505. },
  63506. enumerable: true,
  63507. configurable: true
  63508. });
  63509. /**
  63510. * Creates a depth stencil texture.
  63511. * This is only available in WebGL 2 or with the depth texture extension available.
  63512. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63513. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63514. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63515. */
  63516. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63517. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63518. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63519. if (generateStencil === void 0) { generateStencil = false; }
  63520. if (!this.getScene()) {
  63521. return;
  63522. }
  63523. var engine = this.getScene().getEngine();
  63524. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63525. bilinearFiltering: bilinearFiltering,
  63526. comparisonFunction: comparisonFunction,
  63527. generateStencil: generateStencil,
  63528. isCube: this.isCube
  63529. });
  63530. engine.setFrameBufferDepthStencilTexture(this);
  63531. };
  63532. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63533. if (size.ratio) {
  63534. this._sizeRatio = size.ratio;
  63535. this._size = {
  63536. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63537. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63538. };
  63539. }
  63540. else {
  63541. this._size = size;
  63542. }
  63543. };
  63544. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63545. get: function () {
  63546. return this._samples;
  63547. },
  63548. set: function (value) {
  63549. if (this._samples === value) {
  63550. return;
  63551. }
  63552. var scene = this.getScene();
  63553. if (!scene) {
  63554. return;
  63555. }
  63556. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63557. },
  63558. enumerable: true,
  63559. configurable: true
  63560. });
  63561. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63562. this._currentRefreshId = -1;
  63563. };
  63564. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63565. get: function () {
  63566. return this._refreshRate;
  63567. },
  63568. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63569. set: function (value) {
  63570. this._refreshRate = value;
  63571. this.resetRefreshCounter();
  63572. },
  63573. enumerable: true,
  63574. configurable: true
  63575. });
  63576. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63577. if (!this._postProcessManager) {
  63578. var scene = this.getScene();
  63579. if (!scene) {
  63580. return;
  63581. }
  63582. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63583. this._postProcesses = new Array();
  63584. }
  63585. this._postProcesses.push(postProcess);
  63586. this._postProcesses[0].autoClear = false;
  63587. };
  63588. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63589. if (!this._postProcesses) {
  63590. return;
  63591. }
  63592. if (dispose) {
  63593. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63594. var postProcess = _a[_i];
  63595. postProcess.dispose();
  63596. }
  63597. }
  63598. this._postProcesses = [];
  63599. };
  63600. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63601. if (!this._postProcesses) {
  63602. return;
  63603. }
  63604. var index = this._postProcesses.indexOf(postProcess);
  63605. if (index === -1) {
  63606. return;
  63607. }
  63608. this._postProcesses.splice(index, 1);
  63609. if (this._postProcesses.length > 0) {
  63610. this._postProcesses[0].autoClear = false;
  63611. }
  63612. };
  63613. RenderTargetTexture.prototype._shouldRender = function () {
  63614. if (this._currentRefreshId === -1) { // At least render once
  63615. this._currentRefreshId = 1;
  63616. return true;
  63617. }
  63618. if (this.refreshRate === this._currentRefreshId) {
  63619. this._currentRefreshId = 1;
  63620. return true;
  63621. }
  63622. this._currentRefreshId++;
  63623. return false;
  63624. };
  63625. RenderTargetTexture.prototype.getRenderSize = function () {
  63626. if (this._size.width) {
  63627. return this._size.width;
  63628. }
  63629. return this._size;
  63630. };
  63631. RenderTargetTexture.prototype.getRenderWidth = function () {
  63632. if (this._size.width) {
  63633. return this._size.width;
  63634. }
  63635. return this._size;
  63636. };
  63637. RenderTargetTexture.prototype.getRenderHeight = function () {
  63638. if (this._size.width) {
  63639. return this._size.height;
  63640. }
  63641. return this._size;
  63642. };
  63643. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63644. get: function () {
  63645. return true;
  63646. },
  63647. enumerable: true,
  63648. configurable: true
  63649. });
  63650. RenderTargetTexture.prototype.scale = function (ratio) {
  63651. var newSize = this.getRenderSize() * ratio;
  63652. this.resize(newSize);
  63653. };
  63654. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63655. if (this.isCube) {
  63656. return this._textureMatrix;
  63657. }
  63658. return _super.prototype.getReflectionTextureMatrix.call(this);
  63659. };
  63660. RenderTargetTexture.prototype.resize = function (size) {
  63661. this.releaseInternalTexture();
  63662. var scene = this.getScene();
  63663. if (!scene) {
  63664. return;
  63665. }
  63666. this._processSizeParameter(size);
  63667. if (this.isCube) {
  63668. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63669. }
  63670. else {
  63671. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63672. }
  63673. };
  63674. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63675. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63676. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63677. var scene = this.getScene();
  63678. if (!scene) {
  63679. return;
  63680. }
  63681. var engine = scene.getEngine();
  63682. if (this.useCameraPostProcesses !== undefined) {
  63683. useCameraPostProcess = this.useCameraPostProcesses;
  63684. }
  63685. if (this._waitingRenderList) {
  63686. this.renderList = [];
  63687. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63688. var id = this._waitingRenderList[index];
  63689. var mesh_1 = scene.getMeshByID(id);
  63690. if (mesh_1) {
  63691. this.renderList.push(mesh_1);
  63692. }
  63693. }
  63694. delete this._waitingRenderList;
  63695. }
  63696. // Is predicate defined?
  63697. if (this.renderListPredicate) {
  63698. if (this.renderList) {
  63699. this.renderList.splice(0); // Clear previous renderList
  63700. }
  63701. else {
  63702. this.renderList = [];
  63703. }
  63704. var scene = this.getScene();
  63705. if (!scene) {
  63706. return;
  63707. }
  63708. var sceneMeshes = scene.meshes;
  63709. for (var index = 0; index < sceneMeshes.length; index++) {
  63710. var mesh = sceneMeshes[index];
  63711. if (this.renderListPredicate(mesh)) {
  63712. this.renderList.push(mesh);
  63713. }
  63714. }
  63715. }
  63716. this.onBeforeBindObservable.notifyObservers(this);
  63717. // Set custom projection.
  63718. // Needs to be before binding to prevent changing the aspect ratio.
  63719. var camera;
  63720. if (this.activeCamera) {
  63721. camera = this.activeCamera;
  63722. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63723. if (this.activeCamera !== scene.activeCamera) {
  63724. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  63725. }
  63726. }
  63727. else {
  63728. camera = scene.activeCamera;
  63729. if (camera) {
  63730. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  63731. }
  63732. }
  63733. // Prepare renderingManager
  63734. this._renderingManager.reset();
  63735. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  63736. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  63737. var sceneRenderId = scene.getRenderId();
  63738. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  63739. var mesh = currentRenderList[meshIndex];
  63740. if (mesh) {
  63741. if (!mesh.isReady(this.refreshRate === 0)) {
  63742. this.resetRefreshCounter();
  63743. continue;
  63744. }
  63745. mesh._preActivateForIntermediateRendering(sceneRenderId);
  63746. var isMasked = void 0;
  63747. if (!this.renderList && camera) {
  63748. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  63749. }
  63750. else {
  63751. isMasked = false;
  63752. }
  63753. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  63754. mesh._activate(sceneRenderId);
  63755. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  63756. var subMesh = mesh.subMeshes[subIndex];
  63757. scene._activeIndices.addCount(subMesh.indexCount, false);
  63758. this._renderingManager.dispatch(subMesh, mesh);
  63759. }
  63760. }
  63761. }
  63762. }
  63763. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  63764. var particleSystem = scene.particleSystems[particleIndex];
  63765. var emitter = particleSystem.emitter;
  63766. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  63767. continue;
  63768. }
  63769. if (currentRenderList.indexOf(emitter) >= 0) {
  63770. this._renderingManager.dispatchParticles(particleSystem);
  63771. }
  63772. }
  63773. if (this.isCube) {
  63774. for (var face = 0; face < 6; face++) {
  63775. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63776. scene.incrementRenderId();
  63777. scene.resetCachedMaterial();
  63778. }
  63779. }
  63780. else {
  63781. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  63782. }
  63783. this.onAfterUnbindObservable.notifyObservers(this);
  63784. if (scene.activeCamera) {
  63785. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  63786. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  63787. }
  63788. engine.setViewport(scene.activeCamera.viewport);
  63789. }
  63790. scene.resetCachedMaterial();
  63791. };
  63792. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  63793. var minimum = 128;
  63794. var x = renderDimension * scale;
  63795. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  63796. // Ensure we don't exceed the render dimension (while staying POT)
  63797. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  63798. };
  63799. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  63800. var _this = this;
  63801. if (!this._texture) {
  63802. return;
  63803. }
  63804. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  63805. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  63806. });
  63807. };
  63808. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  63809. var scene = this.getScene();
  63810. if (!scene) {
  63811. return;
  63812. }
  63813. var engine = scene.getEngine();
  63814. if (!this._texture) {
  63815. return;
  63816. }
  63817. // Bind
  63818. if (this._postProcessManager) {
  63819. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  63820. }
  63821. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  63822. if (this._texture) {
  63823. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  63824. }
  63825. }
  63826. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  63827. // Clear
  63828. if (this.onClearObservable.hasObservers()) {
  63829. this.onClearObservable.notifyObservers(engine);
  63830. }
  63831. else {
  63832. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  63833. }
  63834. if (!this._doNotChangeAspectRatio) {
  63835. scene.updateTransformMatrix(true);
  63836. }
  63837. // Render
  63838. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  63839. if (this._postProcessManager) {
  63840. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  63841. }
  63842. else if (useCameraPostProcess) {
  63843. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  63844. }
  63845. if (!this._doNotChangeAspectRatio) {
  63846. scene.updateTransformMatrix(true);
  63847. }
  63848. // Dump ?
  63849. if (dumpForDebug) {
  63850. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  63851. }
  63852. // Unbind
  63853. if (!this.isCube || faceIndex === 5) {
  63854. if (this.isCube) {
  63855. if (faceIndex === 5) {
  63856. engine.generateMipMapsForCubemap(this._texture);
  63857. }
  63858. }
  63859. this.unbindFrameBuffer(engine, faceIndex);
  63860. }
  63861. else {
  63862. this.onAfterRenderObservable.notifyObservers(faceIndex);
  63863. }
  63864. };
  63865. /**
  63866. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  63867. * This allowed control for front to back rendering or reversly depending of the special needs.
  63868. *
  63869. * @param renderingGroupId The rendering group id corresponding to its index
  63870. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  63871. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  63872. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  63873. */
  63874. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  63875. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  63876. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  63877. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  63878. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  63879. };
  63880. /**
  63881. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  63882. *
  63883. * @param renderingGroupId The rendering group id corresponding to its index
  63884. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  63885. */
  63886. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  63887. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  63888. };
  63889. RenderTargetTexture.prototype.clone = function () {
  63890. var textureSize = this.getSize();
  63891. 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);
  63892. // Base texture
  63893. newTexture.hasAlpha = this.hasAlpha;
  63894. newTexture.level = this.level;
  63895. // RenderTarget Texture
  63896. newTexture.coordinatesMode = this.coordinatesMode;
  63897. if (this.renderList) {
  63898. newTexture.renderList = this.renderList.slice(0);
  63899. }
  63900. return newTexture;
  63901. };
  63902. RenderTargetTexture.prototype.serialize = function () {
  63903. if (!this.name) {
  63904. return null;
  63905. }
  63906. var serializationObject = _super.prototype.serialize.call(this);
  63907. serializationObject.renderTargetSize = this.getRenderSize();
  63908. serializationObject.renderList = [];
  63909. if (this.renderList) {
  63910. for (var index = 0; index < this.renderList.length; index++) {
  63911. serializationObject.renderList.push(this.renderList[index].id);
  63912. }
  63913. }
  63914. return serializationObject;
  63915. };
  63916. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  63917. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  63918. var objBuffer = this.getInternalTexture();
  63919. var scene = this.getScene();
  63920. if (objBuffer && scene) {
  63921. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  63922. }
  63923. };
  63924. RenderTargetTexture.prototype.dispose = function () {
  63925. if (this._postProcessManager) {
  63926. this._postProcessManager.dispose();
  63927. this._postProcessManager = null;
  63928. }
  63929. this.clearPostProcesses(true);
  63930. if (this._resizeObserver) {
  63931. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  63932. this._resizeObserver = null;
  63933. }
  63934. this.renderList = null;
  63935. // Remove from custom render targets
  63936. var scene = this.getScene();
  63937. if (!scene) {
  63938. return;
  63939. }
  63940. var index = scene.customRenderTargets.indexOf(this);
  63941. if (index >= 0) {
  63942. scene.customRenderTargets.splice(index, 1);
  63943. }
  63944. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  63945. var camera = _a[_i];
  63946. index = camera.customRenderTargets.indexOf(this);
  63947. if (index >= 0) {
  63948. camera.customRenderTargets.splice(index, 1);
  63949. }
  63950. }
  63951. _super.prototype.dispose.call(this);
  63952. };
  63953. RenderTargetTexture.prototype._rebuild = function () {
  63954. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  63955. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  63956. }
  63957. if (this._postProcessManager) {
  63958. this._postProcessManager._rebuild();
  63959. }
  63960. };
  63961. /**
  63962. * Clear the info related to rendering groups preventing retention point in material dispose.
  63963. */
  63964. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  63965. if (this._renderingManager) {
  63966. this._renderingManager.freeRenderingGroups();
  63967. }
  63968. };
  63969. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  63970. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  63971. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  63972. return RenderTargetTexture;
  63973. }(BABYLON.Texture));
  63974. BABYLON.RenderTargetTexture = RenderTargetTexture;
  63975. })(BABYLON || (BABYLON = {}));
  63976. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  63977. var BABYLON;
  63978. (function (BABYLON) {
  63979. ;
  63980. var MultiRenderTarget = /** @class */ (function (_super) {
  63981. __extends(MultiRenderTarget, _super);
  63982. function MultiRenderTarget(name, size, count, scene, options) {
  63983. var _this = this;
  63984. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  63985. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  63986. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  63987. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  63988. _this._engine = scene.getEngine();
  63989. if (!_this.isSupported) {
  63990. _this.dispose();
  63991. return;
  63992. }
  63993. var types = [];
  63994. var samplingModes = [];
  63995. for (var i = 0; i < count; i++) {
  63996. if (options && options.types && options.types[i] !== undefined) {
  63997. types.push(options.types[i]);
  63998. }
  63999. else {
  64000. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64001. }
  64002. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64003. samplingModes.push(options.samplingModes[i]);
  64004. }
  64005. else {
  64006. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64007. }
  64008. }
  64009. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64010. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64011. _this._size = size;
  64012. _this._multiRenderTargetOptions = {
  64013. samplingModes: samplingModes,
  64014. generateMipMaps: generateMipMaps,
  64015. generateDepthBuffer: generateDepthBuffer,
  64016. generateStencilBuffer: generateStencilBuffer,
  64017. generateDepthTexture: generateDepthTexture,
  64018. types: types,
  64019. textureCount: count
  64020. };
  64021. _this._createInternalTextures();
  64022. _this._createTextures();
  64023. return _this;
  64024. }
  64025. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64026. get: function () {
  64027. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64028. },
  64029. enumerable: true,
  64030. configurable: true
  64031. });
  64032. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64033. get: function () {
  64034. return this._textures;
  64035. },
  64036. enumerable: true,
  64037. configurable: true
  64038. });
  64039. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64040. get: function () {
  64041. return this._textures[this._textures.length - 1];
  64042. },
  64043. enumerable: true,
  64044. configurable: true
  64045. });
  64046. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64047. set: function (wrap) {
  64048. if (this._textures) {
  64049. for (var i = 0; i < this._textures.length; i++) {
  64050. this._textures[i].wrapU = wrap;
  64051. }
  64052. }
  64053. },
  64054. enumerable: true,
  64055. configurable: true
  64056. });
  64057. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64058. set: function (wrap) {
  64059. if (this._textures) {
  64060. for (var i = 0; i < this._textures.length; i++) {
  64061. this._textures[i].wrapV = wrap;
  64062. }
  64063. }
  64064. },
  64065. enumerable: true,
  64066. configurable: true
  64067. });
  64068. MultiRenderTarget.prototype._rebuild = function () {
  64069. this.releaseInternalTextures();
  64070. this._createInternalTextures();
  64071. for (var i = 0; i < this._internalTextures.length; i++) {
  64072. var texture = this._textures[i];
  64073. texture._texture = this._internalTextures[i];
  64074. }
  64075. // Keeps references to frame buffer and stencil/depth buffer
  64076. this._texture = this._internalTextures[0];
  64077. };
  64078. MultiRenderTarget.prototype._createInternalTextures = function () {
  64079. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64080. };
  64081. MultiRenderTarget.prototype._createTextures = function () {
  64082. this._textures = [];
  64083. for (var i = 0; i < this._internalTextures.length; i++) {
  64084. var texture = new BABYLON.Texture(null, this.getScene());
  64085. texture._texture = this._internalTextures[i];
  64086. this._textures.push(texture);
  64087. }
  64088. // Keeps references to frame buffer and stencil/depth buffer
  64089. this._texture = this._internalTextures[0];
  64090. };
  64091. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64092. get: function () {
  64093. return this._samples;
  64094. },
  64095. set: function (value) {
  64096. if (this._samples === value) {
  64097. return;
  64098. }
  64099. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64100. },
  64101. enumerable: true,
  64102. configurable: true
  64103. });
  64104. MultiRenderTarget.prototype.resize = function (size) {
  64105. this.releaseInternalTextures();
  64106. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64107. this._createInternalTextures();
  64108. };
  64109. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64110. var _this = this;
  64111. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64112. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64113. });
  64114. };
  64115. MultiRenderTarget.prototype.dispose = function () {
  64116. this.releaseInternalTextures();
  64117. _super.prototype.dispose.call(this);
  64118. };
  64119. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64120. if (!this._internalTextures) {
  64121. return;
  64122. }
  64123. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64124. if (this._internalTextures[i] !== undefined) {
  64125. this._internalTextures[i].dispose();
  64126. this._internalTextures.splice(i, 1);
  64127. }
  64128. }
  64129. };
  64130. return MultiRenderTarget;
  64131. }(BABYLON.RenderTargetTexture));
  64132. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64133. })(BABYLON || (BABYLON = {}));
  64134. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64135. var BABYLON;
  64136. (function (BABYLON) {
  64137. var MirrorTexture = /** @class */ (function (_super) {
  64138. __extends(MirrorTexture, _super);
  64139. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64140. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64141. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64142. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64143. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64144. _this.scene = scene;
  64145. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64146. _this._transformMatrix = BABYLON.Matrix.Zero();
  64147. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64148. _this._adaptiveBlurKernel = 0;
  64149. _this._blurKernelX = 0;
  64150. _this._blurKernelY = 0;
  64151. _this._blurRatio = 1.0;
  64152. _this.ignoreCameraViewport = true;
  64153. _this._updateGammaSpace();
  64154. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64155. _this._updateGammaSpace;
  64156. });
  64157. _this.onBeforeRenderObservable.add(function () {
  64158. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64159. _this._savedViewMatrix = scene.getViewMatrix();
  64160. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64161. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64162. scene.clipPlane = _this.mirrorPlane;
  64163. scene.getEngine().cullBackFaces = false;
  64164. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64165. });
  64166. _this.onAfterRenderObservable.add(function () {
  64167. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64168. scene.getEngine().cullBackFaces = true;
  64169. scene._mirroredCameraPosition = null;
  64170. delete scene.clipPlane;
  64171. });
  64172. return _this;
  64173. }
  64174. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64175. get: function () {
  64176. return this._blurRatio;
  64177. },
  64178. set: function (value) {
  64179. if (this._blurRatio === value) {
  64180. return;
  64181. }
  64182. this._blurRatio = value;
  64183. this._preparePostProcesses();
  64184. },
  64185. enumerable: true,
  64186. configurable: true
  64187. });
  64188. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64189. set: function (value) {
  64190. this._adaptiveBlurKernel = value;
  64191. this._autoComputeBlurKernel();
  64192. },
  64193. enumerable: true,
  64194. configurable: true
  64195. });
  64196. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64197. set: function (value) {
  64198. this.blurKernelX = value;
  64199. this.blurKernelY = value;
  64200. },
  64201. enumerable: true,
  64202. configurable: true
  64203. });
  64204. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64205. get: function () {
  64206. return this._blurKernelX;
  64207. },
  64208. set: function (value) {
  64209. if (this._blurKernelX === value) {
  64210. return;
  64211. }
  64212. this._blurKernelX = value;
  64213. this._preparePostProcesses();
  64214. },
  64215. enumerable: true,
  64216. configurable: true
  64217. });
  64218. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64219. get: function () {
  64220. return this._blurKernelY;
  64221. },
  64222. set: function (value) {
  64223. if (this._blurKernelY === value) {
  64224. return;
  64225. }
  64226. this._blurKernelY = value;
  64227. this._preparePostProcesses();
  64228. },
  64229. enumerable: true,
  64230. configurable: true
  64231. });
  64232. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64233. var engine = this.getScene().getEngine();
  64234. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64235. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64236. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64237. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64238. };
  64239. MirrorTexture.prototype._onRatioRescale = function () {
  64240. if (this._sizeRatio) {
  64241. this.resize(this._initialSizeParameter);
  64242. if (!this._adaptiveBlurKernel) {
  64243. this._preparePostProcesses();
  64244. }
  64245. }
  64246. if (this._adaptiveBlurKernel) {
  64247. this._autoComputeBlurKernel();
  64248. }
  64249. };
  64250. MirrorTexture.prototype._updateGammaSpace = function () {
  64251. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64252. };
  64253. MirrorTexture.prototype._preparePostProcesses = function () {
  64254. this.clearPostProcesses(true);
  64255. if (this._blurKernelX && this._blurKernelY) {
  64256. var engine = this.getScene().getEngine();
  64257. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64258. 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);
  64259. this._blurX.autoClear = false;
  64260. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64261. this._blurX.inputTexture = this._texture;
  64262. }
  64263. else {
  64264. this._blurX.alwaysForcePOT = true;
  64265. }
  64266. 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);
  64267. this._blurY.autoClear = false;
  64268. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64269. this.addPostProcess(this._blurX);
  64270. this.addPostProcess(this._blurY);
  64271. }
  64272. else {
  64273. if (this._blurY) {
  64274. this.removePostProcess(this._blurY);
  64275. this._blurY.dispose();
  64276. this._blurY = null;
  64277. }
  64278. if (this._blurX) {
  64279. this.removePostProcess(this._blurX);
  64280. this._blurX.dispose();
  64281. this._blurX = null;
  64282. }
  64283. }
  64284. };
  64285. MirrorTexture.prototype.clone = function () {
  64286. var scene = this.getScene();
  64287. if (!scene) {
  64288. return this;
  64289. }
  64290. var textureSize = this.getSize();
  64291. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64292. // Base texture
  64293. newTexture.hasAlpha = this.hasAlpha;
  64294. newTexture.level = this.level;
  64295. // Mirror Texture
  64296. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64297. if (this.renderList) {
  64298. newTexture.renderList = this.renderList.slice(0);
  64299. }
  64300. return newTexture;
  64301. };
  64302. MirrorTexture.prototype.serialize = function () {
  64303. if (!this.name) {
  64304. return null;
  64305. }
  64306. var serializationObject = _super.prototype.serialize.call(this);
  64307. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64308. return serializationObject;
  64309. };
  64310. MirrorTexture.prototype.dispose = function () {
  64311. _super.prototype.dispose.call(this);
  64312. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64313. };
  64314. return MirrorTexture;
  64315. }(BABYLON.RenderTargetTexture));
  64316. BABYLON.MirrorTexture = MirrorTexture;
  64317. })(BABYLON || (BABYLON = {}));
  64318. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64319. var BABYLON;
  64320. (function (BABYLON) {
  64321. /**
  64322. * Creates a refraction texture used by refraction channel of the standard material.
  64323. * @param name the texture name
  64324. * @param size size of the underlying texture
  64325. * @param scene root scene
  64326. */
  64327. var RefractionTexture = /** @class */ (function (_super) {
  64328. __extends(RefractionTexture, _super);
  64329. function RefractionTexture(name, size, scene, generateMipMaps) {
  64330. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64331. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64332. _this.depth = 2.0;
  64333. _this.onBeforeRenderObservable.add(function () {
  64334. scene.clipPlane = _this.refractionPlane;
  64335. });
  64336. _this.onAfterRenderObservable.add(function () {
  64337. delete scene.clipPlane;
  64338. });
  64339. return _this;
  64340. }
  64341. RefractionTexture.prototype.clone = function () {
  64342. var scene = this.getScene();
  64343. if (!scene) {
  64344. return this;
  64345. }
  64346. var textureSize = this.getSize();
  64347. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64348. // Base texture
  64349. newTexture.hasAlpha = this.hasAlpha;
  64350. newTexture.level = this.level;
  64351. // Refraction Texture
  64352. newTexture.refractionPlane = this.refractionPlane.clone();
  64353. if (this.renderList) {
  64354. newTexture.renderList = this.renderList.slice(0);
  64355. }
  64356. newTexture.depth = this.depth;
  64357. return newTexture;
  64358. };
  64359. RefractionTexture.prototype.serialize = function () {
  64360. if (!this.name) {
  64361. return null;
  64362. }
  64363. var serializationObject = _super.prototype.serialize.call(this);
  64364. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64365. serializationObject.depth = this.depth;
  64366. return serializationObject;
  64367. };
  64368. return RefractionTexture;
  64369. }(BABYLON.RenderTargetTexture));
  64370. BABYLON.RefractionTexture = RefractionTexture;
  64371. })(BABYLON || (BABYLON = {}));
  64372. //# sourceMappingURL=babylon.refractionTexture.js.map
  64373. var BABYLON;
  64374. (function (BABYLON) {
  64375. /**
  64376. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64377. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64378. */
  64379. var DynamicTexture = /** @class */ (function (_super) {
  64380. __extends(DynamicTexture, _super);
  64381. /**
  64382. * Creates a {BABYLON.DynamicTexture}
  64383. * @param name defines the name of the texture
  64384. * @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
  64385. * @param scene defines the scene where you want the texture
  64386. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64387. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64388. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64389. */
  64390. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64391. if (scene === void 0) { scene = null; }
  64392. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64393. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64394. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64395. _this.name = name;
  64396. _this._engine = _this.getScene().getEngine();
  64397. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64398. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64399. _this._generateMipMaps = generateMipMaps;
  64400. if (options.getContext) {
  64401. _this._canvas = options;
  64402. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64403. }
  64404. else {
  64405. _this._canvas = document.createElement("canvas");
  64406. if (options.width || options.width === 0) {
  64407. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64408. }
  64409. else {
  64410. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64411. }
  64412. }
  64413. var textureSize = _this.getSize();
  64414. _this._canvas.width = textureSize.width;
  64415. _this._canvas.height = textureSize.height;
  64416. _this._context = _this._canvas.getContext("2d");
  64417. return _this;
  64418. }
  64419. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64420. /**
  64421. * Gets the current state of canRescale
  64422. */
  64423. get: function () {
  64424. return true;
  64425. },
  64426. enumerable: true,
  64427. configurable: true
  64428. });
  64429. DynamicTexture.prototype._recreate = function (textureSize) {
  64430. this._canvas.width = textureSize.width;
  64431. this._canvas.height = textureSize.height;
  64432. this.releaseInternalTexture();
  64433. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64434. };
  64435. /**
  64436. * Scales the texture
  64437. * @param ratio the scale factor to apply to both width and height
  64438. */
  64439. DynamicTexture.prototype.scale = function (ratio) {
  64440. var textureSize = this.getSize();
  64441. textureSize.width *= ratio;
  64442. textureSize.height *= ratio;
  64443. this._recreate(textureSize);
  64444. };
  64445. /**
  64446. * Resizes the texture
  64447. * @param width the new width
  64448. * @param height the new height
  64449. */
  64450. DynamicTexture.prototype.scaleTo = function (width, height) {
  64451. var textureSize = this.getSize();
  64452. textureSize.width = width;
  64453. textureSize.height = height;
  64454. this._recreate(textureSize);
  64455. };
  64456. /**
  64457. * Gets the context of the canvas used by the texture
  64458. * @returns the canvas context of the dynamic texture
  64459. */
  64460. DynamicTexture.prototype.getContext = function () {
  64461. return this._context;
  64462. };
  64463. /**
  64464. * Clears the texture
  64465. */
  64466. DynamicTexture.prototype.clear = function () {
  64467. var size = this.getSize();
  64468. this._context.fillRect(0, 0, size.width, size.height);
  64469. };
  64470. /**
  64471. * Updates the texture
  64472. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64473. */
  64474. DynamicTexture.prototype.update = function (invertY) {
  64475. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, undefined, this._format || undefined);
  64476. };
  64477. /**
  64478. * Draws text onto the texture
  64479. * @param text defines the text to be drawn
  64480. * @param x defines the placement of the text from the left
  64481. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64482. * @param font defines the font to be used with font-style, font-size, font-name
  64483. * @param color defines the color used for the text
  64484. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64485. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64486. * @param update defines whether texture is immediately update (default is true)
  64487. */
  64488. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64489. if (update === void 0) { update = true; }
  64490. var size = this.getSize();
  64491. if (clearColor) {
  64492. this._context.fillStyle = clearColor;
  64493. this._context.fillRect(0, 0, size.width, size.height);
  64494. }
  64495. this._context.font = font;
  64496. if (x === null || x === undefined) {
  64497. var textSize = this._context.measureText(text);
  64498. x = (size.width - textSize.width) / 2;
  64499. }
  64500. if (y === null || y === undefined) {
  64501. var fontSize = parseInt((font.replace(/\D/g, '')));
  64502. y = (size.height / 2) + (fontSize / 3.65);
  64503. }
  64504. this._context.fillStyle = color;
  64505. this._context.fillText(text, x, y);
  64506. if (update) {
  64507. this.update(invertY);
  64508. }
  64509. };
  64510. /**
  64511. * Clones the texture
  64512. * @returns the clone of the texture.
  64513. */
  64514. DynamicTexture.prototype.clone = function () {
  64515. var scene = this.getScene();
  64516. if (!scene) {
  64517. return this;
  64518. }
  64519. var textureSize = this.getSize();
  64520. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64521. // Base texture
  64522. newTexture.hasAlpha = this.hasAlpha;
  64523. newTexture.level = this.level;
  64524. // Dynamic Texture
  64525. newTexture.wrapU = this.wrapU;
  64526. newTexture.wrapV = this.wrapV;
  64527. return newTexture;
  64528. };
  64529. /** @hidden */
  64530. DynamicTexture.prototype._rebuild = function () {
  64531. this.update();
  64532. };
  64533. return DynamicTexture;
  64534. }(BABYLON.Texture));
  64535. BABYLON.DynamicTexture = DynamicTexture;
  64536. })(BABYLON || (BABYLON = {}));
  64537. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64538. var BABYLON;
  64539. (function (BABYLON) {
  64540. var VideoTexture = /** @class */ (function (_super) {
  64541. __extends(VideoTexture, _super);
  64542. /**
  64543. * Creates a video texture.
  64544. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64545. * @param {string | null} name optional name, will detect from video source, if not defined
  64546. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64547. * @param {BABYLON.Scene} scene is obviously the current scene.
  64548. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64549. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64550. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64551. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64552. */
  64553. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64554. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64555. if (invertY === void 0) { invertY = false; }
  64556. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64557. if (settings === void 0) { settings = {
  64558. autoPlay: true,
  64559. loop: true,
  64560. autoUpdateTexture: true,
  64561. }; }
  64562. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64563. _this._stillImageCaptured = false;
  64564. _this._createInternalTexture = function () {
  64565. if (_this._texture != null) {
  64566. return;
  64567. }
  64568. if (!_this._engine.needPOTTextures ||
  64569. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64570. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64571. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64572. }
  64573. else {
  64574. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64575. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64576. _this._generateMipMaps = false;
  64577. }
  64578. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64579. if (!_this.video.autoplay) {
  64580. var oldHandler_1 = _this.video.onplaying;
  64581. _this.video.onplaying = function () {
  64582. _this.video.onplaying = oldHandler_1;
  64583. _this._texture.isReady = true;
  64584. _this._updateInternalTexture();
  64585. _this.video.pause();
  64586. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64587. _this.onLoadObservable.notifyObservers(_this);
  64588. }
  64589. };
  64590. _this.video.play();
  64591. }
  64592. else {
  64593. _this._texture.isReady = true;
  64594. _this._updateInternalTexture();
  64595. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64596. _this.onLoadObservable.notifyObservers(_this);
  64597. }
  64598. }
  64599. };
  64600. _this.reset = function () {
  64601. if (_this._texture == null) {
  64602. return;
  64603. }
  64604. _this._texture.dispose();
  64605. _this._texture = null;
  64606. };
  64607. _this._updateInternalTexture = function (e) {
  64608. if (_this._texture == null || !_this._texture.isReady) {
  64609. return;
  64610. }
  64611. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64612. return;
  64613. }
  64614. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64615. };
  64616. _this._engine = _this.getScene().getEngine();
  64617. _this._generateMipMaps = generateMipMaps;
  64618. _this._samplingMode = samplingMode;
  64619. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64620. _this.name = name || _this._getName(src);
  64621. _this.video = _this._getVideo(src);
  64622. if (settings.autoPlay !== undefined) {
  64623. _this.video.autoplay = settings.autoPlay;
  64624. }
  64625. if (settings.loop !== undefined) {
  64626. _this.video.loop = settings.loop;
  64627. }
  64628. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64629. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64630. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64631. _this.video.addEventListener("emptied", _this.reset);
  64632. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64633. _this._createInternalTexture();
  64634. }
  64635. return _this;
  64636. }
  64637. VideoTexture.prototype._getName = function (src) {
  64638. if (src instanceof HTMLVideoElement) {
  64639. return src.currentSrc;
  64640. }
  64641. if (typeof src === "object") {
  64642. return src.toString();
  64643. }
  64644. return src;
  64645. };
  64646. ;
  64647. VideoTexture.prototype._getVideo = function (src) {
  64648. if (src instanceof HTMLVideoElement) {
  64649. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64650. return src;
  64651. }
  64652. var video = document.createElement("video");
  64653. if (typeof src === "string") {
  64654. BABYLON.Tools.SetCorsBehavior(src, video);
  64655. video.src = src;
  64656. }
  64657. else {
  64658. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64659. src.forEach(function (url) {
  64660. var source = document.createElement("source");
  64661. source.src = url;
  64662. video.appendChild(source);
  64663. });
  64664. }
  64665. return video;
  64666. };
  64667. ;
  64668. /**
  64669. * Internal method to initiate `update`.
  64670. */
  64671. VideoTexture.prototype._rebuild = function () {
  64672. this.update();
  64673. };
  64674. /**
  64675. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  64676. */
  64677. VideoTexture.prototype.update = function () {
  64678. if (!this.autoUpdateTexture) {
  64679. // Expecting user to call `updateTexture` manually
  64680. return;
  64681. }
  64682. this.updateTexture(true);
  64683. };
  64684. /**
  64685. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  64686. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  64687. */
  64688. VideoTexture.prototype.updateTexture = function (isVisible) {
  64689. if (!isVisible) {
  64690. return;
  64691. }
  64692. if (this.video.paused && this._stillImageCaptured) {
  64693. return;
  64694. }
  64695. this._stillImageCaptured = true;
  64696. this._updateInternalTexture();
  64697. };
  64698. /**
  64699. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  64700. * @param url New url.
  64701. */
  64702. VideoTexture.prototype.updateURL = function (url) {
  64703. this.video.src = url;
  64704. };
  64705. VideoTexture.prototype.dispose = function () {
  64706. _super.prototype.dispose.call(this);
  64707. this.video.removeEventListener("canplay", this._createInternalTexture);
  64708. this.video.removeEventListener("paused", this._updateInternalTexture);
  64709. this.video.removeEventListener("seeked", this._updateInternalTexture);
  64710. this.video.removeEventListener("emptied", this.reset);
  64711. this.video.pause();
  64712. };
  64713. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  64714. var video = document.createElement("video");
  64715. var constraintsDeviceId;
  64716. if (constraints && constraints.deviceId) {
  64717. constraintsDeviceId = {
  64718. exact: constraints.deviceId,
  64719. };
  64720. }
  64721. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  64722. if (navigator.mediaDevices) {
  64723. navigator.mediaDevices.getUserMedia({ video: constraints })
  64724. .then(function (stream) {
  64725. if (video.mozSrcObject !== undefined) {
  64726. // hack for Firefox < 19
  64727. video.mozSrcObject = stream;
  64728. }
  64729. else {
  64730. video.srcObject = stream;
  64731. }
  64732. var onPlaying = function () {
  64733. if (onReady) {
  64734. onReady(new VideoTexture("video", video, scene, true, true));
  64735. }
  64736. video.removeEventListener("playing", onPlaying);
  64737. };
  64738. video.addEventListener("playing", onPlaying);
  64739. video.play();
  64740. })
  64741. .catch(function (err) {
  64742. BABYLON.Tools.Error(err.name);
  64743. });
  64744. }
  64745. else {
  64746. navigator.getUserMedia =
  64747. navigator.getUserMedia ||
  64748. navigator.webkitGetUserMedia ||
  64749. navigator.mozGetUserMedia ||
  64750. navigator.msGetUserMedia;
  64751. if (navigator.getUserMedia) {
  64752. navigator.getUserMedia({
  64753. video: {
  64754. deviceId: constraintsDeviceId,
  64755. width: {
  64756. min: (constraints && constraints.minWidth) || 256,
  64757. max: (constraints && constraints.maxWidth) || 640,
  64758. },
  64759. height: {
  64760. min: (constraints && constraints.minHeight) || 256,
  64761. max: (constraints && constraints.maxHeight) || 480,
  64762. },
  64763. },
  64764. }, function (stream) {
  64765. if (video.mozSrcObject !== undefined) {
  64766. // hack for Firefox < 19
  64767. video.mozSrcObject = stream;
  64768. }
  64769. else {
  64770. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  64771. }
  64772. video.play();
  64773. if (onReady) {
  64774. onReady(new VideoTexture("video", video, scene, true, true));
  64775. }
  64776. }, function (e) {
  64777. BABYLON.Tools.Error(e.name);
  64778. });
  64779. }
  64780. }
  64781. };
  64782. return VideoTexture;
  64783. }(BABYLON.Texture));
  64784. BABYLON.VideoTexture = VideoTexture;
  64785. })(BABYLON || (BABYLON = {}));
  64786. //# sourceMappingURL=babylon.videoTexture.js.map
  64787. var BABYLON;
  64788. (function (BABYLON) {
  64789. var RawTexture = /** @class */ (function (_super) {
  64790. __extends(RawTexture, _super);
  64791. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  64792. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64793. if (invertY === void 0) { invertY = false; }
  64794. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64795. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64796. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64797. _this.format = format;
  64798. _this._engine = scene.getEngine();
  64799. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  64800. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64801. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64802. return _this;
  64803. }
  64804. RawTexture.prototype.update = function (data) {
  64805. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  64806. };
  64807. // Statics
  64808. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64809. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64810. if (invertY === void 0) { invertY = false; }
  64811. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64812. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  64813. };
  64814. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64815. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64816. if (invertY === void 0) { invertY = false; }
  64817. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64818. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64819. };
  64820. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  64821. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64822. if (invertY === void 0) { invertY = false; }
  64823. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64824. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  64825. };
  64826. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64827. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64828. if (invertY === void 0) { invertY = false; }
  64829. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64830. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64831. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  64832. };
  64833. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  64834. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64835. if (invertY === void 0) { invertY = false; }
  64836. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64837. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64838. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  64839. };
  64840. return RawTexture;
  64841. }(BABYLON.Texture));
  64842. BABYLON.RawTexture = RawTexture;
  64843. })(BABYLON || (BABYLON = {}));
  64844. //# sourceMappingURL=babylon.rawTexture.js.map
  64845. var BABYLON;
  64846. (function (BABYLON) {
  64847. /**
  64848. * Class used to store 3D textures containing user data
  64849. */
  64850. var RawTexture3D = /** @class */ (function (_super) {
  64851. __extends(RawTexture3D, _super);
  64852. /**
  64853. * Create a new RawTexture3D
  64854. * @param data defines the data of the texture
  64855. * @param width defines the width of the texture
  64856. * @param height defines the height of the texture
  64857. * @param depth defines the depth of the texture
  64858. * @param format defines the texture format to use
  64859. * @param scene defines the hosting scene
  64860. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  64861. * @param invertY defines if texture must be stored with Y axis inverted
  64862. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  64863. */
  64864. function RawTexture3D(data, width, height, depth,
  64865. /** Gets or sets the texture format to use*/
  64866. format, scene, generateMipMaps, invertY, samplingMode) {
  64867. if (generateMipMaps === void 0) { generateMipMaps = true; }
  64868. if (invertY === void 0) { invertY = false; }
  64869. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64870. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64871. _this.format = format;
  64872. _this._engine = scene.getEngine();
  64873. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode);
  64874. _this.is3D = true;
  64875. return _this;
  64876. }
  64877. /**
  64878. * Update the texture with new data
  64879. * @param data defines the data to store in the texture
  64880. */
  64881. RawTexture3D.prototype.update = function (data) {
  64882. if (!this._texture) {
  64883. return;
  64884. }
  64885. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY);
  64886. };
  64887. return RawTexture3D;
  64888. }(BABYLON.Texture));
  64889. BABYLON.RawTexture3D = RawTexture3D;
  64890. })(BABYLON || (BABYLON = {}));
  64891. //# sourceMappingURL=babylon.rawTexture3D.js.map
  64892. var BABYLON;
  64893. (function (BABYLON) {
  64894. /**
  64895. * PostProcess can be used to apply a shader to a texture after it has been rendered
  64896. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  64897. */
  64898. var PostProcess = /** @class */ (function () {
  64899. /**
  64900. * Creates a new instance PostProcess
  64901. * @param name The name of the PostProcess.
  64902. * @param fragmentUrl The url of the fragment shader to be used.
  64903. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  64904. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  64905. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  64906. * @param camera The camera to apply the render pass to.
  64907. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  64908. * @param engine The engine which the post process will be applied. (default: current engine)
  64909. * @param reusable If the post process can be reused on the same frame. (default: false)
  64910. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  64911. * @param textureType Type of textures used when performing the post process. (default: 0)
  64912. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  64913. * @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
  64914. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  64915. */
  64916. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  64917. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  64918. if (defines === void 0) { defines = null; }
  64919. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64920. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  64921. if (blockCompilation === void 0) { blockCompilation = false; }
  64922. this.name = name;
  64923. /**
  64924. * Width of the texture to apply the post process on
  64925. */
  64926. this.width = -1;
  64927. /**
  64928. * Height of the texture to apply the post process on
  64929. */
  64930. this.height = -1;
  64931. /**
  64932. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  64933. */
  64934. this._outputTexture = null;
  64935. /**
  64936. * If the buffer needs to be cleared before applying the post process. (default: true)
  64937. * Should be set to false if shader will overwrite all previous pixels.
  64938. */
  64939. this.autoClear = true;
  64940. /**
  64941. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  64942. */
  64943. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  64944. /**
  64945. * Animations to be used for the post processing
  64946. */
  64947. this.animations = new Array();
  64948. /**
  64949. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  64950. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  64951. */
  64952. this.enablePixelPerfectMode = false;
  64953. /**
  64954. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  64955. */
  64956. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  64957. /**
  64958. * Force textures to be a power of two (default: false)
  64959. */
  64960. this.alwaysForcePOT = false;
  64961. /**
  64962. * Number of sample textures (default: 1)
  64963. */
  64964. this.samples = 1;
  64965. /**
  64966. * Modify the scale of the post process to be the same as the viewport (default: false)
  64967. */
  64968. this.adaptScaleToCurrentViewport = false;
  64969. this._reusable = false;
  64970. /**
  64971. * Smart array of input and output textures for the post process.
  64972. */
  64973. this._textures = new BABYLON.SmartArray(2);
  64974. /**
  64975. * The index in _textures that corresponds to the output texture.
  64976. */
  64977. this._currentRenderTextureInd = 0;
  64978. this._scaleRatio = new BABYLON.Vector2(1, 1);
  64979. this._texelSize = BABYLON.Vector2.Zero();
  64980. // Events
  64981. /**
  64982. * An event triggered when the postprocess is activated.
  64983. */
  64984. this.onActivateObservable = new BABYLON.Observable();
  64985. /**
  64986. * An event triggered when the postprocess changes its size.
  64987. */
  64988. this.onSizeChangedObservable = new BABYLON.Observable();
  64989. /**
  64990. * An event triggered when the postprocess applies its effect.
  64991. */
  64992. this.onApplyObservable = new BABYLON.Observable();
  64993. /**
  64994. * An event triggered before rendering the postprocess
  64995. */
  64996. this.onBeforeRenderObservable = new BABYLON.Observable();
  64997. /**
  64998. * An event triggered after rendering the postprocess
  64999. */
  65000. this.onAfterRenderObservable = new BABYLON.Observable();
  65001. if (camera != null) {
  65002. this._camera = camera;
  65003. this._scene = camera.getScene();
  65004. camera.attachPostProcess(this);
  65005. this._engine = this._scene.getEngine();
  65006. this._scene.postProcesses.push(this);
  65007. }
  65008. else if (engine) {
  65009. this._engine = engine;
  65010. this._engine.postProcesses.push(this);
  65011. }
  65012. this._options = options;
  65013. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65014. this._reusable = reusable || false;
  65015. this._textureType = textureType;
  65016. this._samplers = samplers || [];
  65017. this._samplers.push("textureSampler");
  65018. this._fragmentUrl = fragmentUrl;
  65019. this._vertexUrl = vertexUrl;
  65020. this._parameters = parameters || [];
  65021. this._parameters.push("scale");
  65022. this._indexParameters = indexParameters;
  65023. if (!blockCompilation) {
  65024. this.updateEffect(defines);
  65025. }
  65026. }
  65027. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65028. /**
  65029. * A function that is added to the onActivateObservable
  65030. */
  65031. set: function (callback) {
  65032. if (this._onActivateObserver) {
  65033. this.onActivateObservable.remove(this._onActivateObserver);
  65034. }
  65035. if (callback) {
  65036. this._onActivateObserver = this.onActivateObservable.add(callback);
  65037. }
  65038. },
  65039. enumerable: true,
  65040. configurable: true
  65041. });
  65042. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65043. /**
  65044. * A function that is added to the onSizeChangedObservable
  65045. */
  65046. set: function (callback) {
  65047. if (this._onSizeChangedObserver) {
  65048. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65049. }
  65050. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65051. },
  65052. enumerable: true,
  65053. configurable: true
  65054. });
  65055. Object.defineProperty(PostProcess.prototype, "onApply", {
  65056. /**
  65057. * A function that is added to the onApplyObservable
  65058. */
  65059. set: function (callback) {
  65060. if (this._onApplyObserver) {
  65061. this.onApplyObservable.remove(this._onApplyObserver);
  65062. }
  65063. this._onApplyObserver = this.onApplyObservable.add(callback);
  65064. },
  65065. enumerable: true,
  65066. configurable: true
  65067. });
  65068. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65069. /**
  65070. * A function that is added to the onBeforeRenderObservable
  65071. */
  65072. set: function (callback) {
  65073. if (this._onBeforeRenderObserver) {
  65074. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65075. }
  65076. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65077. },
  65078. enumerable: true,
  65079. configurable: true
  65080. });
  65081. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65082. /**
  65083. * A function that is added to the onAfterRenderObservable
  65084. */
  65085. set: function (callback) {
  65086. if (this._onAfterRenderObserver) {
  65087. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65088. }
  65089. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65090. },
  65091. enumerable: true,
  65092. configurable: true
  65093. });
  65094. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65095. /**
  65096. * 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
  65097. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65098. */
  65099. get: function () {
  65100. return this._textures.data[this._currentRenderTextureInd];
  65101. },
  65102. set: function (value) {
  65103. this._forcedOutputTexture = value;
  65104. },
  65105. enumerable: true,
  65106. configurable: true
  65107. });
  65108. /**
  65109. * Gets the camera which post process is applied to.
  65110. * @returns The camera the post process is applied to.
  65111. */
  65112. PostProcess.prototype.getCamera = function () {
  65113. return this._camera;
  65114. };
  65115. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65116. /**
  65117. * Gets the texel size of the postprocess.
  65118. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65119. */
  65120. get: function () {
  65121. if (this._shareOutputWithPostProcess) {
  65122. return this._shareOutputWithPostProcess.texelSize;
  65123. }
  65124. if (this._forcedOutputTexture) {
  65125. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65126. }
  65127. return this._texelSize;
  65128. },
  65129. enumerable: true,
  65130. configurable: true
  65131. });
  65132. /**
  65133. * Gets the engine which this post process belongs to.
  65134. * @returns The engine the post process was enabled with.
  65135. */
  65136. PostProcess.prototype.getEngine = function () {
  65137. return this._engine;
  65138. };
  65139. /**
  65140. * The effect that is created when initializing the post process.
  65141. * @returns The created effect corrisponding the the postprocess.
  65142. */
  65143. PostProcess.prototype.getEffect = function () {
  65144. return this._effect;
  65145. };
  65146. /**
  65147. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65148. * @param postProcess The post process to share the output with.
  65149. * @returns This post process.
  65150. */
  65151. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65152. this._disposeTextures();
  65153. this._shareOutputWithPostProcess = postProcess;
  65154. return this;
  65155. };
  65156. /**
  65157. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65158. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65159. */
  65160. PostProcess.prototype.useOwnOutput = function () {
  65161. if (this._textures.length == 0) {
  65162. this._textures = new BABYLON.SmartArray(2);
  65163. }
  65164. this._shareOutputWithPostProcess = null;
  65165. };
  65166. /**
  65167. * Updates the effect with the current post process compile time values and recompiles the shader.
  65168. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65169. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65170. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65171. * @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
  65172. * @param onCompiled Called when the shader has been compiled.
  65173. * @param onError Called if there is an error when compiling a shader.
  65174. */
  65175. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65176. if (defines === void 0) { defines = null; }
  65177. if (uniforms === void 0) { uniforms = null; }
  65178. if (samplers === void 0) { samplers = null; }
  65179. 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);
  65180. };
  65181. /**
  65182. * The post process is reusable if it can be used multiple times within one frame.
  65183. * @returns If the post process is reusable
  65184. */
  65185. PostProcess.prototype.isReusable = function () {
  65186. return this._reusable;
  65187. };
  65188. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65189. PostProcess.prototype.markTextureDirty = function () {
  65190. this.width = -1;
  65191. };
  65192. /**
  65193. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65194. * 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.
  65195. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65196. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65197. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65198. * @returns The target texture that was bound to be written to.
  65199. */
  65200. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65201. var _this = this;
  65202. if (sourceTexture === void 0) { sourceTexture = null; }
  65203. camera = camera || this._camera;
  65204. var scene = camera.getScene();
  65205. var engine = scene.getEngine();
  65206. var maxSize = engine.getCaps().maxTextureSize;
  65207. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65208. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65209. // 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
  65210. var webVRCamera = camera.parent;
  65211. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65212. requiredWidth /= 2;
  65213. }
  65214. var desiredWidth = (this._options.width || requiredWidth);
  65215. var desiredHeight = this._options.height || requiredHeight;
  65216. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65217. if (this.adaptScaleToCurrentViewport) {
  65218. var currentViewport = engine.currentViewport;
  65219. if (currentViewport) {
  65220. desiredWidth *= currentViewport.width;
  65221. desiredHeight *= currentViewport.height;
  65222. }
  65223. }
  65224. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65225. if (!this._options.width) {
  65226. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65227. }
  65228. if (!this._options.height) {
  65229. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65230. }
  65231. }
  65232. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65233. if (this._textures.length > 0) {
  65234. for (var i = 0; i < this._textures.length; i++) {
  65235. this._engine._releaseTexture(this._textures.data[i]);
  65236. }
  65237. this._textures.reset();
  65238. }
  65239. this.width = desiredWidth;
  65240. this.height = desiredHeight;
  65241. var textureSize = { width: this.width, height: this.height };
  65242. var textureOptions = {
  65243. generateMipMaps: false,
  65244. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65245. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65246. samplingMode: this.renderTargetSamplingMode,
  65247. type: this._textureType
  65248. };
  65249. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65250. if (this._reusable) {
  65251. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65252. }
  65253. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65254. this.onSizeChangedObservable.notifyObservers(this);
  65255. }
  65256. this._textures.forEach(function (texture) {
  65257. if (texture.samples !== _this.samples) {
  65258. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65259. }
  65260. });
  65261. }
  65262. var target;
  65263. if (this._shareOutputWithPostProcess) {
  65264. target = this._shareOutputWithPostProcess.inputTexture;
  65265. }
  65266. else if (this._forcedOutputTexture) {
  65267. target = this._forcedOutputTexture;
  65268. this.width = this._forcedOutputTexture.width;
  65269. this.height = this._forcedOutputTexture.height;
  65270. }
  65271. else {
  65272. target = this.inputTexture;
  65273. }
  65274. // Bind the input of this post process to be used as the output of the previous post process.
  65275. if (this.enablePixelPerfectMode) {
  65276. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65277. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, true);
  65278. }
  65279. else {
  65280. this._scaleRatio.copyFromFloats(1, 1);
  65281. this._engine.bindFramebuffer(target, 0, undefined, undefined, true);
  65282. }
  65283. this.onActivateObservable.notifyObservers(camera);
  65284. // Clear
  65285. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65286. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65287. }
  65288. if (this._reusable) {
  65289. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65290. }
  65291. return target;
  65292. };
  65293. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65294. /**
  65295. * If the post process is supported.
  65296. */
  65297. get: function () {
  65298. return this._effect.isSupported;
  65299. },
  65300. enumerable: true,
  65301. configurable: true
  65302. });
  65303. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65304. /**
  65305. * The aspect ratio of the output texture.
  65306. */
  65307. get: function () {
  65308. if (this._shareOutputWithPostProcess) {
  65309. return this._shareOutputWithPostProcess.aspectRatio;
  65310. }
  65311. if (this._forcedOutputTexture) {
  65312. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65313. }
  65314. return this.width / this.height;
  65315. },
  65316. enumerable: true,
  65317. configurable: true
  65318. });
  65319. /**
  65320. * Get a value indicating if the post-process is ready to be used
  65321. * @returns true if the post-process is ready (shader is compiled)
  65322. */
  65323. PostProcess.prototype.isReady = function () {
  65324. return this._effect && this._effect.isReady();
  65325. };
  65326. /**
  65327. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65328. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65329. */
  65330. PostProcess.prototype.apply = function () {
  65331. // Check
  65332. if (!this._effect || !this._effect.isReady())
  65333. return null;
  65334. // States
  65335. this._engine.enableEffect(this._effect);
  65336. this._engine.setState(false);
  65337. this._engine.setDepthBuffer(false);
  65338. this._engine.setDepthWrite(false);
  65339. // Alpha
  65340. this._engine.setAlphaMode(this.alphaMode);
  65341. if (this.alphaConstants) {
  65342. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65343. }
  65344. // Bind the output texture of the preivous post process as the input to this post process.
  65345. var source;
  65346. if (this._shareOutputWithPostProcess) {
  65347. source = this._shareOutputWithPostProcess.inputTexture;
  65348. }
  65349. else if (this._forcedOutputTexture) {
  65350. source = this._forcedOutputTexture;
  65351. }
  65352. else {
  65353. source = this.inputTexture;
  65354. }
  65355. this._effect._bindTexture("textureSampler", source);
  65356. // Parameters
  65357. this._effect.setVector2("scale", this._scaleRatio);
  65358. this.onApplyObservable.notifyObservers(this._effect);
  65359. return this._effect;
  65360. };
  65361. PostProcess.prototype._disposeTextures = function () {
  65362. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65363. return;
  65364. }
  65365. if (this._textures.length > 0) {
  65366. for (var i = 0; i < this._textures.length; i++) {
  65367. this._engine._releaseTexture(this._textures.data[i]);
  65368. }
  65369. }
  65370. this._textures.dispose();
  65371. };
  65372. /**
  65373. * Disposes the post process.
  65374. * @param camera The camera to dispose the post process on.
  65375. */
  65376. PostProcess.prototype.dispose = function (camera) {
  65377. camera = camera || this._camera;
  65378. this._disposeTextures();
  65379. if (this._scene) {
  65380. var index_1 = this._scene.postProcesses.indexOf(this);
  65381. if (index_1 !== -1) {
  65382. this._scene.postProcesses.splice(index_1, 1);
  65383. }
  65384. }
  65385. else {
  65386. var index_2 = this._engine.postProcesses.indexOf(this);
  65387. if (index_2 !== -1) {
  65388. this._engine.postProcesses.splice(index_2, 1);
  65389. }
  65390. }
  65391. if (!camera) {
  65392. return;
  65393. }
  65394. camera.detachPostProcess(this);
  65395. var index = camera._postProcesses.indexOf(this);
  65396. if (index === 0 && camera._postProcesses.length > 0) {
  65397. var firstPostProcess = this._camera._getFirstPostProcess();
  65398. if (firstPostProcess) {
  65399. firstPostProcess.markTextureDirty();
  65400. }
  65401. }
  65402. this.onActivateObservable.clear();
  65403. this.onAfterRenderObservable.clear();
  65404. this.onApplyObservable.clear();
  65405. this.onBeforeRenderObservable.clear();
  65406. this.onSizeChangedObservable.clear();
  65407. };
  65408. return PostProcess;
  65409. }());
  65410. BABYLON.PostProcess = PostProcess;
  65411. })(BABYLON || (BABYLON = {}));
  65412. //# sourceMappingURL=babylon.postProcess.js.map
  65413. var BABYLON;
  65414. (function (BABYLON) {
  65415. var PassPostProcess = /** @class */ (function (_super) {
  65416. __extends(PassPostProcess, _super);
  65417. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65418. if (camera === void 0) { camera = null; }
  65419. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65420. if (blockCompilation === void 0) { blockCompilation = false; }
  65421. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65422. }
  65423. return PassPostProcess;
  65424. }(BABYLON.PostProcess));
  65425. BABYLON.PassPostProcess = PassPostProcess;
  65426. })(BABYLON || (BABYLON = {}));
  65427. //# sourceMappingURL=babylon.passPostProcess.js.map
  65428. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65429. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65430. s = arguments[i];
  65431. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65432. t[p] = s[p];
  65433. }
  65434. return t;
  65435. };
  65436. var BABYLON;
  65437. (function (BABYLON) {
  65438. /**
  65439. * Default implementation IShadowGenerator.
  65440. * This is the main object responsible of generating shadows in the framework.
  65441. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65442. */
  65443. var ShadowGenerator = /** @class */ (function () {
  65444. /**
  65445. * Creates a ShadowGenerator object.
  65446. * A ShadowGenerator is the required tool to use the shadows.
  65447. * Each light casting shadows needs to use its own ShadowGenerator.
  65448. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65449. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65450. * @param light The light object generating the shadows.
  65451. * @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.
  65452. */
  65453. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65454. this._bias = 0.00005;
  65455. this._normalBias = 0;
  65456. this._blurBoxOffset = 1;
  65457. this._blurScale = 2;
  65458. this._blurKernel = 1;
  65459. this._useKernelBlur = false;
  65460. this._filter = ShadowGenerator.FILTER_NONE;
  65461. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  65462. this._contactHardeningLightSizeUVRatio = 0.1;
  65463. this._darkness = 0;
  65464. this._transparencyShadow = false;
  65465. /**
  65466. * Controls the extent to which the shadows fade out at the edge of the frustum
  65467. * Used only by directionals and spots
  65468. */
  65469. this.frustumEdgeFalloff = 0;
  65470. /**
  65471. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  65472. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  65473. * It might on the other hand introduce peter panning.
  65474. */
  65475. this.forceBackFacesOnly = false;
  65476. this._lightDirection = BABYLON.Vector3.Zero();
  65477. this._viewMatrix = BABYLON.Matrix.Zero();
  65478. this._projectionMatrix = BABYLON.Matrix.Zero();
  65479. this._transformMatrix = BABYLON.Matrix.Zero();
  65480. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65481. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  65482. this._currentFaceIndex = 0;
  65483. this._currentFaceIndexCache = 0;
  65484. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  65485. this._mapSize = mapSize;
  65486. this._light = light;
  65487. this._scene = light.getScene();
  65488. light._shadowGenerator = this;
  65489. // Texture type fallback from float to int if not supported.
  65490. var caps = this._scene.getEngine().getCaps();
  65491. if (!useFullFloatFirst) {
  65492. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65493. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65494. }
  65495. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65496. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65497. }
  65498. else {
  65499. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65500. }
  65501. }
  65502. else {
  65503. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  65504. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  65505. }
  65506. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  65507. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  65508. }
  65509. else {
  65510. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  65511. }
  65512. }
  65513. this._initializeGenerator();
  65514. this._applyFilterValues();
  65515. }
  65516. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  65517. /**
  65518. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  65519. */
  65520. get: function () {
  65521. return this._bias;
  65522. },
  65523. /**
  65524. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  65525. */
  65526. set: function (bias) {
  65527. this._bias = bias;
  65528. },
  65529. enumerable: true,
  65530. configurable: true
  65531. });
  65532. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  65533. /**
  65534. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65535. */
  65536. get: function () {
  65537. return this._normalBias;
  65538. },
  65539. /**
  65540. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  65541. */
  65542. set: function (normalBias) {
  65543. this._normalBias = normalBias;
  65544. },
  65545. enumerable: true,
  65546. configurable: true
  65547. });
  65548. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  65549. /**
  65550. * Gets the blur box offset: offset applied during the blur pass.
  65551. * Only usefull if useKernelBlur = false
  65552. */
  65553. get: function () {
  65554. return this._blurBoxOffset;
  65555. },
  65556. /**
  65557. * Sets the blur box offset: offset applied during the blur pass.
  65558. * Only usefull if useKernelBlur = false
  65559. */
  65560. set: function (value) {
  65561. if (this._blurBoxOffset === value) {
  65562. return;
  65563. }
  65564. this._blurBoxOffset = value;
  65565. this._disposeBlurPostProcesses();
  65566. },
  65567. enumerable: true,
  65568. configurable: true
  65569. });
  65570. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  65571. /**
  65572. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  65573. * 2 means half of the size.
  65574. */
  65575. get: function () {
  65576. return this._blurScale;
  65577. },
  65578. /**
  65579. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  65580. * 2 means half of the size.
  65581. */
  65582. set: function (value) {
  65583. if (this._blurScale === value) {
  65584. return;
  65585. }
  65586. this._blurScale = value;
  65587. this._disposeBlurPostProcesses();
  65588. },
  65589. enumerable: true,
  65590. configurable: true
  65591. });
  65592. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  65593. /**
  65594. * Gets the blur kernel: kernel size of the blur pass.
  65595. * Only usefull if useKernelBlur = true
  65596. */
  65597. get: function () {
  65598. return this._blurKernel;
  65599. },
  65600. /**
  65601. * Sets the blur kernel: kernel size of the blur pass.
  65602. * Only usefull if useKernelBlur = true
  65603. */
  65604. set: function (value) {
  65605. if (this._blurKernel === value) {
  65606. return;
  65607. }
  65608. this._blurKernel = value;
  65609. this._disposeBlurPostProcesses();
  65610. },
  65611. enumerable: true,
  65612. configurable: true
  65613. });
  65614. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  65615. /**
  65616. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  65617. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65618. */
  65619. get: function () {
  65620. return this._useKernelBlur;
  65621. },
  65622. /**
  65623. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  65624. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  65625. */
  65626. set: function (value) {
  65627. if (this._useKernelBlur === value) {
  65628. return;
  65629. }
  65630. this._useKernelBlur = value;
  65631. this._disposeBlurPostProcesses();
  65632. },
  65633. enumerable: true,
  65634. configurable: true
  65635. });
  65636. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  65637. /**
  65638. * Gets the depth scale used in ESM mode.
  65639. */
  65640. get: function () {
  65641. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  65642. },
  65643. /**
  65644. * Sets the depth scale used in ESM mode.
  65645. * This can override the scale stored on the light.
  65646. */
  65647. set: function (value) {
  65648. this._depthScale = value;
  65649. },
  65650. enumerable: true,
  65651. configurable: true
  65652. });
  65653. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  65654. /**
  65655. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  65656. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65657. */
  65658. get: function () {
  65659. return this._filter;
  65660. },
  65661. /**
  65662. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  65663. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  65664. */
  65665. set: function (value) {
  65666. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  65667. if (this._light.needCube()) {
  65668. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65669. this.useExponentialShadowMap = true;
  65670. return;
  65671. }
  65672. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65673. this.useCloseExponentialShadowMap = true;
  65674. return;
  65675. }
  65676. // PCF on cubemap would also be expensive
  65677. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65678. this.usePoissonSampling = true;
  65679. return;
  65680. }
  65681. }
  65682. // Weblg1 fallback for PCF.
  65683. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  65684. if (this._scene.getEngine().webGLVersion === 1) {
  65685. this.usePoissonSampling = true;
  65686. return;
  65687. }
  65688. }
  65689. if (this._filter === value) {
  65690. return;
  65691. }
  65692. this._filter = value;
  65693. this._disposeBlurPostProcesses();
  65694. this._applyFilterValues();
  65695. this._light._markMeshesAsLightDirty();
  65696. },
  65697. enumerable: true,
  65698. configurable: true
  65699. });
  65700. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  65701. /**
  65702. * Gets if the current filter is set to Poisson Sampling.
  65703. */
  65704. get: function () {
  65705. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  65706. },
  65707. /**
  65708. * Sets the current filter to Poisson Sampling.
  65709. */
  65710. set: function (value) {
  65711. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  65712. return;
  65713. }
  65714. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  65715. },
  65716. enumerable: true,
  65717. configurable: true
  65718. });
  65719. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  65720. /**
  65721. * Gets if the current filter is set to VSM.
  65722. * DEPRECATED. Should use useExponentialShadowMap instead.
  65723. */
  65724. get: function () {
  65725. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65726. return this.useExponentialShadowMap;
  65727. },
  65728. /**
  65729. * Sets the current filter is to VSM.
  65730. * DEPRECATED. Should use useExponentialShadowMap instead.
  65731. */
  65732. set: function (value) {
  65733. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  65734. this.useExponentialShadowMap = value;
  65735. },
  65736. enumerable: true,
  65737. configurable: true
  65738. });
  65739. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  65740. /**
  65741. * Gets if the current filter is set to blurred VSM.
  65742. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65743. */
  65744. get: function () {
  65745. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65746. return this.useBlurExponentialShadowMap;
  65747. },
  65748. /**
  65749. * Sets the current filter is to blurred VSM.
  65750. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  65751. */
  65752. set: function (value) {
  65753. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  65754. this.useBlurExponentialShadowMap = value;
  65755. },
  65756. enumerable: true,
  65757. configurable: true
  65758. });
  65759. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  65760. /**
  65761. * Gets if the current filter is set to ESM.
  65762. */
  65763. get: function () {
  65764. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  65765. },
  65766. /**
  65767. * Sets the current filter is to ESM.
  65768. */
  65769. set: function (value) {
  65770. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  65771. return;
  65772. }
  65773. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65774. },
  65775. enumerable: true,
  65776. configurable: true
  65777. });
  65778. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  65779. /**
  65780. * Gets if the current filter is set to filtered ESM.
  65781. */
  65782. get: function () {
  65783. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  65784. },
  65785. /**
  65786. * Gets if the current filter is set to filtered ESM.
  65787. */
  65788. set: function (value) {
  65789. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  65790. return;
  65791. }
  65792. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65793. },
  65794. enumerable: true,
  65795. configurable: true
  65796. });
  65797. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  65798. /**
  65799. * Gets if the current filter is set to "close ESM" (using the inverse of the
  65800. * exponential to prevent steep falloff artifacts).
  65801. */
  65802. get: function () {
  65803. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  65804. },
  65805. /**
  65806. * Sets the current filter to "close ESM" (using the inverse of the
  65807. * exponential to prevent steep falloff artifacts).
  65808. */
  65809. set: function (value) {
  65810. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  65811. return;
  65812. }
  65813. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65814. },
  65815. enumerable: true,
  65816. configurable: true
  65817. });
  65818. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  65819. /**
  65820. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  65821. * exponential to prevent steep falloff artifacts).
  65822. */
  65823. get: function () {
  65824. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  65825. },
  65826. /**
  65827. * Sets the current filter to filtered "close ESM" (using the inverse of the
  65828. * exponential to prevent steep falloff artifacts).
  65829. */
  65830. set: function (value) {
  65831. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  65832. return;
  65833. }
  65834. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  65835. },
  65836. enumerable: true,
  65837. configurable: true
  65838. });
  65839. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  65840. /**
  65841. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  65842. */
  65843. get: function () {
  65844. return this.filter === ShadowGenerator.FILTER_PCF;
  65845. },
  65846. /**
  65847. * Sets the current filter to "PCF" (percentage closer filtering).
  65848. */
  65849. set: function (value) {
  65850. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  65851. return;
  65852. }
  65853. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  65854. },
  65855. enumerable: true,
  65856. configurable: true
  65857. });
  65858. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  65859. /**
  65860. * Gets the PCF or PCSS Quality.
  65861. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65862. */
  65863. get: function () {
  65864. return this._filteringQuality;
  65865. },
  65866. /**
  65867. * Sets the PCF or PCSS Quality.
  65868. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  65869. */
  65870. set: function (filteringQuality) {
  65871. this._filteringQuality = filteringQuality;
  65872. },
  65873. enumerable: true,
  65874. configurable: true
  65875. });
  65876. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  65877. /**
  65878. * Gets if the current filter is set to "PCSS" (contact hardening).
  65879. */
  65880. get: function () {
  65881. return this.filter === ShadowGenerator.FILTER_PCSS;
  65882. },
  65883. /**
  65884. * Sets the current filter to "PCSS" (contact hardening).
  65885. */
  65886. set: function (value) {
  65887. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  65888. return;
  65889. }
  65890. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  65891. },
  65892. enumerable: true,
  65893. configurable: true
  65894. });
  65895. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  65896. /**
  65897. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65898. * Using a ratio helps keeping shape stability independently of the map size.
  65899. *
  65900. * It does not account for the light projection as it was having too much
  65901. * instability during the light setup or during light position changes.
  65902. *
  65903. * Only valid if useContactHardeningShadow is true.
  65904. */
  65905. get: function () {
  65906. return this._contactHardeningLightSizeUVRatio;
  65907. },
  65908. /**
  65909. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  65910. * Using a ratio helps keeping shape stability independently of the map size.
  65911. *
  65912. * It does not account for the light projection as it was having too much
  65913. * instability during the light setup or during light position changes.
  65914. *
  65915. * Only valid if useContactHardeningShadow is true.
  65916. */
  65917. set: function (contactHardeningLightSizeUVRatio) {
  65918. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  65919. },
  65920. enumerable: true,
  65921. configurable: true
  65922. });
  65923. /**
  65924. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  65925. * 0 means strongest and 1 would means no shadow.
  65926. * @returns the darkness.
  65927. */
  65928. ShadowGenerator.prototype.getDarkness = function () {
  65929. return this._darkness;
  65930. };
  65931. /**
  65932. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  65933. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  65934. * @returns the shadow generator allowing fluent coding.
  65935. */
  65936. ShadowGenerator.prototype.setDarkness = function (darkness) {
  65937. if (darkness >= 1.0)
  65938. this._darkness = 1.0;
  65939. else if (darkness <= 0.0)
  65940. this._darkness = 0.0;
  65941. else
  65942. this._darkness = darkness;
  65943. return this;
  65944. };
  65945. /**
  65946. * Sets the ability to have transparent shadow (boolean).
  65947. * @param transparent True if transparent else False
  65948. * @returns the shadow generator allowing fluent coding
  65949. */
  65950. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  65951. this._transparencyShadow = transparent;
  65952. return this;
  65953. };
  65954. /**
  65955. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  65956. * @returns The render target texture if present otherwise, null
  65957. */
  65958. ShadowGenerator.prototype.getShadowMap = function () {
  65959. return this._shadowMap;
  65960. };
  65961. /**
  65962. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  65963. * @returns The render target texture if the shadow map is present otherwise, null
  65964. */
  65965. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  65966. if (this._shadowMap2) {
  65967. return this._shadowMap2;
  65968. }
  65969. return this._shadowMap;
  65970. };
  65971. /**
  65972. * Helper function to add a mesh and its descendants to the list of shadow casters.
  65973. * @param mesh Mesh to add
  65974. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  65975. * @returns the Shadow Generator itself
  65976. */
  65977. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  65978. if (includeDescendants === void 0) { includeDescendants = true; }
  65979. if (!this._shadowMap) {
  65980. return this;
  65981. }
  65982. if (!this._shadowMap.renderList) {
  65983. this._shadowMap.renderList = [];
  65984. }
  65985. this._shadowMap.renderList.push(mesh);
  65986. if (includeDescendants) {
  65987. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  65988. }
  65989. return this;
  65990. var _a;
  65991. };
  65992. /**
  65993. * Helper function to remove a mesh and its descendants from the list of shadow casters
  65994. * @param mesh Mesh to remove
  65995. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  65996. * @returns the Shadow Generator itself
  65997. */
  65998. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  65999. if (includeDescendants === void 0) { includeDescendants = true; }
  66000. if (!this._shadowMap || !this._shadowMap.renderList) {
  66001. return this;
  66002. }
  66003. var index = this._shadowMap.renderList.indexOf(mesh);
  66004. if (index !== -1) {
  66005. this._shadowMap.renderList.splice(index, 1);
  66006. }
  66007. if (includeDescendants) {
  66008. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66009. var child = _a[_i];
  66010. this.removeShadowCaster(child);
  66011. }
  66012. }
  66013. return this;
  66014. };
  66015. /**
  66016. * Returns the associated light object.
  66017. * @returns the light generating the shadow
  66018. */
  66019. ShadowGenerator.prototype.getLight = function () {
  66020. return this._light;
  66021. };
  66022. ShadowGenerator.prototype._initializeGenerator = function () {
  66023. this._light._markMeshesAsLightDirty();
  66024. this._initializeShadowMap();
  66025. };
  66026. ShadowGenerator.prototype._initializeShadowMap = function () {
  66027. var _this = this;
  66028. // Render target
  66029. var engine = this._scene.getEngine();
  66030. if (engine.webGLVersion > 1) {
  66031. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66032. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66033. }
  66034. else {
  66035. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66036. }
  66037. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66038. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66039. this._shadowMap.anisotropicFilteringLevel = 1;
  66040. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66041. this._shadowMap.renderParticles = false;
  66042. this._shadowMap.ignoreCameraViewport = true;
  66043. // Record Face Index before render.
  66044. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66045. _this._currentFaceIndex = faceIndex;
  66046. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66047. engine.setColorWrite(false);
  66048. }
  66049. });
  66050. // Custom render function.
  66051. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66052. // Blur if required afer render.
  66053. this._shadowMap.onAfterUnbindObservable.add(function () {
  66054. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66055. engine.setColorWrite(true);
  66056. }
  66057. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66058. return;
  66059. }
  66060. var shadowMap = _this.getShadowMapForRendering();
  66061. if (shadowMap) {
  66062. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66063. }
  66064. });
  66065. // Clear according to the chosen filter.
  66066. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66067. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66068. this._shadowMap.onClearObservable.add(function (engine) {
  66069. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66070. engine.clear(clearOne, false, true, false);
  66071. }
  66072. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66073. engine.clear(clearZero, true, true, false);
  66074. }
  66075. else {
  66076. engine.clear(clearOne, true, true, false);
  66077. }
  66078. });
  66079. };
  66080. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66081. var _this = this;
  66082. var engine = this._scene.getEngine();
  66083. var targetSize = this._mapSize / this.blurScale;
  66084. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66085. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66086. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66087. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66088. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66089. }
  66090. if (this.useKernelBlur) {
  66091. 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);
  66092. this._kernelBlurXPostprocess.width = targetSize;
  66093. this._kernelBlurXPostprocess.height = targetSize;
  66094. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66095. effect.setTexture("textureSampler", _this._shadowMap);
  66096. });
  66097. 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);
  66098. this._kernelBlurXPostprocess.autoClear = false;
  66099. this._kernelBlurYPostprocess.autoClear = false;
  66100. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66101. this._kernelBlurXPostprocess.packedFloat = true;
  66102. this._kernelBlurYPostprocess.packedFloat = true;
  66103. }
  66104. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66105. }
  66106. else {
  66107. 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);
  66108. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66109. effect.setFloat2("screenSize", targetSize, targetSize);
  66110. effect.setTexture("textureSampler", _this._shadowMap);
  66111. });
  66112. this._boxBlurPostprocess.autoClear = false;
  66113. this._blurPostProcesses = [this._boxBlurPostprocess];
  66114. }
  66115. };
  66116. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66117. var index;
  66118. var engine = this._scene.getEngine();
  66119. if (depthOnlySubMeshes.length) {
  66120. engine.setColorWrite(false);
  66121. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66122. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66123. }
  66124. engine.setColorWrite(true);
  66125. }
  66126. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66127. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66128. }
  66129. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66130. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66131. }
  66132. if (this._transparencyShadow) {
  66133. for (index = 0; index < transparentSubMeshes.length; index++) {
  66134. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66135. }
  66136. }
  66137. };
  66138. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66139. var _this = this;
  66140. var mesh = subMesh.getRenderingMesh();
  66141. var scene = this._scene;
  66142. var engine = scene.getEngine();
  66143. var material = subMesh.getMaterial();
  66144. if (!material) {
  66145. return;
  66146. }
  66147. // Culling
  66148. engine.setState(material.backFaceCulling);
  66149. // Managing instances
  66150. var batch = mesh._getInstancesRenderList(subMesh._id);
  66151. if (batch.mustReturn) {
  66152. return;
  66153. }
  66154. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66155. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66156. engine.enableEffect(this._effect);
  66157. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66158. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66159. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66160. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66161. this._effect.setVector3("lightData", this._cachedDirection);
  66162. }
  66163. else {
  66164. this._effect.setVector3("lightData", this._cachedPosition);
  66165. }
  66166. if (scene.activeCamera) {
  66167. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66168. }
  66169. // Alpha test
  66170. if (material && material.needAlphaTesting()) {
  66171. var alphaTexture = material.getAlphaTestTexture();
  66172. if (alphaTexture) {
  66173. this._effect.setTexture("diffuseSampler", alphaTexture);
  66174. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66175. }
  66176. }
  66177. // Bones
  66178. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66179. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66180. }
  66181. // Morph targets
  66182. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66183. if (this.forceBackFacesOnly) {
  66184. engine.setState(true, 0, false, true);
  66185. }
  66186. // Draw
  66187. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66188. if (this.forceBackFacesOnly) {
  66189. engine.setState(true, 0, false, false);
  66190. }
  66191. }
  66192. else {
  66193. // Need to reset refresh rate of the shadowMap
  66194. if (this._shadowMap) {
  66195. this._shadowMap.resetRefreshCounter();
  66196. }
  66197. }
  66198. };
  66199. ShadowGenerator.prototype._applyFilterValues = function () {
  66200. if (!this._shadowMap) {
  66201. return;
  66202. }
  66203. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66204. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66205. }
  66206. else {
  66207. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66208. }
  66209. };
  66210. /**
  66211. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66212. * @param onCompiled Callback triggered at the and of the effects compilation
  66213. * @param options Sets of optional options forcing the compilation with different modes
  66214. */
  66215. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66216. var _this = this;
  66217. var localOptions = __assign({ useInstances: false }, options);
  66218. var shadowMap = this.getShadowMap();
  66219. if (!shadowMap) {
  66220. if (onCompiled) {
  66221. onCompiled(this);
  66222. }
  66223. return;
  66224. }
  66225. var renderList = shadowMap.renderList;
  66226. if (!renderList) {
  66227. if (onCompiled) {
  66228. onCompiled(this);
  66229. }
  66230. return;
  66231. }
  66232. var subMeshes = new Array();
  66233. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66234. var mesh = renderList_1[_i];
  66235. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66236. }
  66237. if (subMeshes.length === 0) {
  66238. if (onCompiled) {
  66239. onCompiled(this);
  66240. }
  66241. return;
  66242. }
  66243. var currentIndex = 0;
  66244. var checkReady = function () {
  66245. if (!_this._scene || !_this._scene.getEngine()) {
  66246. return;
  66247. }
  66248. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66249. currentIndex++;
  66250. if (currentIndex >= subMeshes.length) {
  66251. if (onCompiled) {
  66252. onCompiled(_this);
  66253. }
  66254. return;
  66255. }
  66256. }
  66257. setTimeout(checkReady, 16);
  66258. };
  66259. checkReady();
  66260. };
  66261. /**
  66262. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66263. * @param options Sets of optional options forcing the compilation with different modes
  66264. * @returns A promise that resolves when the compilation completes
  66265. */
  66266. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66267. var _this = this;
  66268. return new Promise(function (resolve) {
  66269. _this.forceCompilation(function () {
  66270. resolve();
  66271. }, options);
  66272. });
  66273. };
  66274. /**
  66275. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66276. * @param subMesh The submesh we want to render in the shadow map
  66277. * @param useInstances Defines wether will draw in the map using instances
  66278. * @returns true if ready otherwise, false
  66279. */
  66280. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66281. var defines = [];
  66282. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66283. defines.push("#define FLOAT");
  66284. }
  66285. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66286. defines.push("#define ESM");
  66287. }
  66288. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66289. defines.push("#define DEPTHTEXTURE");
  66290. }
  66291. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66292. var mesh = subMesh.getMesh();
  66293. var material = subMesh.getMaterial();
  66294. // Normal bias.
  66295. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66296. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66297. defines.push("#define NORMAL");
  66298. if (mesh.nonUniformScaling) {
  66299. defines.push("#define NONUNIFORMSCALING");
  66300. }
  66301. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66302. defines.push("#define DIRECTIONINLIGHTDATA");
  66303. }
  66304. }
  66305. // Alpha test
  66306. if (material && material.needAlphaTesting()) {
  66307. var alphaTexture = material.getAlphaTestTexture();
  66308. if (alphaTexture) {
  66309. defines.push("#define ALPHATEST");
  66310. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66311. attribs.push(BABYLON.VertexBuffer.UVKind);
  66312. defines.push("#define UV1");
  66313. }
  66314. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66315. if (alphaTexture.coordinatesIndex === 1) {
  66316. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66317. defines.push("#define UV2");
  66318. }
  66319. }
  66320. }
  66321. }
  66322. // Bones
  66323. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66324. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66325. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66326. if (mesh.numBoneInfluencers > 4) {
  66327. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66328. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66329. }
  66330. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66331. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66332. }
  66333. else {
  66334. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66335. }
  66336. // Morph targets
  66337. var manager = mesh.morphTargetManager;
  66338. var morphInfluencers = 0;
  66339. if (manager) {
  66340. if (manager.numInfluencers > 0) {
  66341. defines.push("#define MORPHTARGETS");
  66342. morphInfluencers = manager.numInfluencers;
  66343. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66344. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66345. }
  66346. }
  66347. // Instances
  66348. if (useInstances) {
  66349. defines.push("#define INSTANCES");
  66350. attribs.push("world0");
  66351. attribs.push("world1");
  66352. attribs.push("world2");
  66353. attribs.push("world3");
  66354. }
  66355. // Get correct effect
  66356. var join = defines.join("\n");
  66357. if (this._cachedDefines !== join) {
  66358. this._cachedDefines = join;
  66359. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66360. }
  66361. if (!this._effect.isReady()) {
  66362. return false;
  66363. }
  66364. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66365. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66366. this._initializeBlurRTTAndPostProcesses();
  66367. }
  66368. }
  66369. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66370. return false;
  66371. }
  66372. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66373. return false;
  66374. }
  66375. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66376. return false;
  66377. }
  66378. return true;
  66379. };
  66380. /**
  66381. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66382. * @param defines Defines of the material we want to update
  66383. * @param lightIndex Index of the light in the enabled light list of the material
  66384. */
  66385. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66386. var scene = this._scene;
  66387. var light = this._light;
  66388. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66389. return;
  66390. }
  66391. defines["SHADOW" + lightIndex] = true;
  66392. if (this.useContactHardeningShadow) {
  66393. defines["SHADOWPCSS" + lightIndex] = true;
  66394. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66395. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66396. }
  66397. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66398. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66399. }
  66400. // else default to high.
  66401. }
  66402. if (this.usePercentageCloserFiltering) {
  66403. defines["SHADOWPCF" + lightIndex] = true;
  66404. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66405. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66406. }
  66407. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66408. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66409. }
  66410. // else default to high.
  66411. }
  66412. else if (this.usePoissonSampling) {
  66413. defines["SHADOWPOISSON" + lightIndex] = true;
  66414. }
  66415. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66416. defines["SHADOWESM" + lightIndex] = true;
  66417. }
  66418. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66419. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66420. }
  66421. if (light.needCube()) {
  66422. defines["SHADOWCUBE" + lightIndex] = true;
  66423. }
  66424. };
  66425. /**
  66426. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66427. * defined in the generator but impacting the effect).
  66428. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66429. * @param effect The effect we are binfing the information for
  66430. */
  66431. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66432. var light = this._light;
  66433. var scene = this._scene;
  66434. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66435. return;
  66436. }
  66437. var camera = scene.activeCamera;
  66438. if (!camera) {
  66439. return;
  66440. }
  66441. var shadowMap = this.getShadowMap();
  66442. if (!shadowMap) {
  66443. return;
  66444. }
  66445. if (!light.needCube()) {
  66446. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66447. }
  66448. // Only PCF uses depth stencil texture.
  66449. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66450. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66451. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66452. }
  66453. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66454. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66455. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66456. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66457. }
  66458. else {
  66459. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66460. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  66461. }
  66462. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  66463. };
  66464. /**
  66465. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  66466. * (eq to shadow prjection matrix * light transform matrix)
  66467. * @returns The transform matrix used to create the shadow map
  66468. */
  66469. ShadowGenerator.prototype.getTransformMatrix = function () {
  66470. var scene = this._scene;
  66471. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  66472. return this._transformMatrix;
  66473. }
  66474. this._currentRenderID = scene.getRenderId();
  66475. this._currentFaceIndexCache = this._currentFaceIndex;
  66476. var lightPosition = this._light.position;
  66477. if (this._light.computeTransformedInformation()) {
  66478. lightPosition = this._light.transformedPosition;
  66479. }
  66480. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  66481. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  66482. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  66483. }
  66484. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  66485. this._cachedPosition.copyFrom(lightPosition);
  66486. this._cachedDirection.copyFrom(this._lightDirection);
  66487. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  66488. var shadowMap = this.getShadowMap();
  66489. if (shadowMap) {
  66490. var renderList = shadowMap.renderList;
  66491. if (renderList) {
  66492. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  66493. }
  66494. }
  66495. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  66496. }
  66497. return this._transformMatrix;
  66498. };
  66499. /**
  66500. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  66501. * Cube and 2D textures for instance.
  66502. */
  66503. ShadowGenerator.prototype.recreateShadowMap = function () {
  66504. var shadowMap = this._shadowMap;
  66505. if (!shadowMap) {
  66506. return;
  66507. }
  66508. // Track render list.
  66509. var renderList = shadowMap.renderList;
  66510. // Clean up existing data.
  66511. this._disposeRTTandPostProcesses();
  66512. // Reinitializes.
  66513. this._initializeGenerator();
  66514. // Reaffect the filter to ensure a correct fallback if necessary.
  66515. this.filter = this.filter;
  66516. // Reaffect the filter.
  66517. this._applyFilterValues();
  66518. // Reaffect Render List.
  66519. this._shadowMap.renderList = renderList;
  66520. };
  66521. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  66522. if (this._shadowMap2) {
  66523. this._shadowMap2.dispose();
  66524. this._shadowMap2 = null;
  66525. }
  66526. if (this._boxBlurPostprocess) {
  66527. this._boxBlurPostprocess.dispose();
  66528. this._boxBlurPostprocess = null;
  66529. }
  66530. if (this._kernelBlurXPostprocess) {
  66531. this._kernelBlurXPostprocess.dispose();
  66532. this._kernelBlurXPostprocess = null;
  66533. }
  66534. if (this._kernelBlurYPostprocess) {
  66535. this._kernelBlurYPostprocess.dispose();
  66536. this._kernelBlurYPostprocess = null;
  66537. }
  66538. this._blurPostProcesses = [];
  66539. };
  66540. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  66541. if (this._shadowMap) {
  66542. this._shadowMap.dispose();
  66543. this._shadowMap = null;
  66544. }
  66545. this._disposeBlurPostProcesses();
  66546. };
  66547. /**
  66548. * Disposes the ShadowGenerator.
  66549. * Returns nothing.
  66550. */
  66551. ShadowGenerator.prototype.dispose = function () {
  66552. this._disposeRTTandPostProcesses();
  66553. if (this._light) {
  66554. this._light._shadowGenerator = null;
  66555. this._light._markMeshesAsLightDirty();
  66556. }
  66557. };
  66558. /**
  66559. * Serializes the shadow generator setup to a json object.
  66560. * @returns The serialized JSON object
  66561. */
  66562. ShadowGenerator.prototype.serialize = function () {
  66563. var serializationObject = {};
  66564. var shadowMap = this.getShadowMap();
  66565. if (!shadowMap) {
  66566. return serializationObject;
  66567. }
  66568. serializationObject.lightId = this._light.id;
  66569. serializationObject.mapSize = shadowMap.getRenderSize();
  66570. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  66571. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  66572. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66573. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  66574. serializationObject.usePoissonSampling = this.usePoissonSampling;
  66575. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  66576. serializationObject.depthScale = this.depthScale;
  66577. serializationObject.darkness = this.getDarkness();
  66578. serializationObject.blurBoxOffset = this.blurBoxOffset;
  66579. serializationObject.blurKernel = this.blurKernel;
  66580. serializationObject.blurScale = this.blurScale;
  66581. serializationObject.useKernelBlur = this.useKernelBlur;
  66582. serializationObject.transparencyShadow = this._transparencyShadow;
  66583. serializationObject.bias = this.bias;
  66584. serializationObject.normalBias = this.normalBias;
  66585. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  66586. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  66587. serializationObject.filteringQuality = this.filteringQuality;
  66588. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  66589. serializationObject.renderList = [];
  66590. if (shadowMap.renderList) {
  66591. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  66592. var mesh = shadowMap.renderList[meshIndex];
  66593. serializationObject.renderList.push(mesh.id);
  66594. }
  66595. }
  66596. return serializationObject;
  66597. };
  66598. /**
  66599. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  66600. * @param parsedShadowGenerator The JSON object to parse
  66601. * @param scene The scene to create the shadow map for
  66602. * @returns The parsed shadow generator
  66603. */
  66604. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  66605. //casting to point light, as light is missing the position attr and typescript complains.
  66606. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  66607. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  66608. var shadowMap = shadowGenerator.getShadowMap();
  66609. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  66610. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  66611. meshes.forEach(function (mesh) {
  66612. if (!shadowMap) {
  66613. return;
  66614. }
  66615. if (!shadowMap.renderList) {
  66616. shadowMap.renderList = [];
  66617. }
  66618. shadowMap.renderList.push(mesh);
  66619. });
  66620. }
  66621. if (parsedShadowGenerator.usePoissonSampling) {
  66622. shadowGenerator.usePoissonSampling = true;
  66623. }
  66624. else if (parsedShadowGenerator.useExponentialShadowMap) {
  66625. shadowGenerator.useExponentialShadowMap = true;
  66626. }
  66627. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  66628. shadowGenerator.useBlurExponentialShadowMap = true;
  66629. }
  66630. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  66631. shadowGenerator.useCloseExponentialShadowMap = true;
  66632. }
  66633. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  66634. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  66635. }
  66636. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  66637. shadowGenerator.usePercentageCloserFiltering = true;
  66638. }
  66639. else if (parsedShadowGenerator.useContactHardeningShadow) {
  66640. shadowGenerator.useContactHardeningShadow = true;
  66641. }
  66642. if (parsedShadowGenerator.filteringQuality) {
  66643. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  66644. }
  66645. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  66646. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  66647. }
  66648. // Backward compat
  66649. else if (parsedShadowGenerator.useVarianceShadowMap) {
  66650. shadowGenerator.useExponentialShadowMap = true;
  66651. }
  66652. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  66653. shadowGenerator.useBlurExponentialShadowMap = true;
  66654. }
  66655. if (parsedShadowGenerator.depthScale) {
  66656. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  66657. }
  66658. if (parsedShadowGenerator.blurScale) {
  66659. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  66660. }
  66661. if (parsedShadowGenerator.blurBoxOffset) {
  66662. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  66663. }
  66664. if (parsedShadowGenerator.useKernelBlur) {
  66665. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  66666. }
  66667. if (parsedShadowGenerator.blurKernel) {
  66668. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  66669. }
  66670. if (parsedShadowGenerator.bias !== undefined) {
  66671. shadowGenerator.bias = parsedShadowGenerator.bias;
  66672. }
  66673. if (parsedShadowGenerator.normalBias !== undefined) {
  66674. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  66675. }
  66676. if (parsedShadowGenerator.darkness) {
  66677. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  66678. }
  66679. if (parsedShadowGenerator.transparencyShadow) {
  66680. shadowGenerator.setTransparencyShadow(true);
  66681. }
  66682. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  66683. return shadowGenerator;
  66684. };
  66685. /**
  66686. * Shadow generator mode None: no filtering applied.
  66687. */
  66688. ShadowGenerator.FILTER_NONE = 0;
  66689. /**
  66690. * Shadow generator mode ESM: Exponential Shadow Mapping.
  66691. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66692. */
  66693. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  66694. /**
  66695. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  66696. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  66697. */
  66698. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  66699. /**
  66700. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  66701. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66702. */
  66703. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  66704. /**
  66705. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  66706. * edge artifacts on steep falloff.
  66707. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66708. */
  66709. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  66710. /**
  66711. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  66712. * edge artifacts on steep falloff.
  66713. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  66714. */
  66715. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  66716. /**
  66717. * Shadow generator mode PCF: Percentage Closer Filtering
  66718. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66719. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  66720. */
  66721. ShadowGenerator.FILTER_PCF = 6;
  66722. /**
  66723. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  66724. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  66725. * Contact Hardening
  66726. */
  66727. ShadowGenerator.FILTER_PCSS = 7;
  66728. /**
  66729. * Reserved for PCF and PCSS
  66730. * Highest Quality.
  66731. *
  66732. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  66733. *
  66734. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  66735. */
  66736. ShadowGenerator.QUALITY_HIGH = 0;
  66737. /**
  66738. * Reserved for PCF and PCSS
  66739. * Good tradeoff for quality/perf cross devices
  66740. *
  66741. * Execute PCF on a 3*3 kernel.
  66742. *
  66743. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  66744. */
  66745. ShadowGenerator.QUALITY_MEDIUM = 1;
  66746. /**
  66747. * Reserved for PCF and PCSS
  66748. * The lowest quality but the fastest.
  66749. *
  66750. * Execute PCF on a 1*1 kernel.
  66751. *
  66752. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  66753. */
  66754. ShadowGenerator.QUALITY_LOW = 2;
  66755. return ShadowGenerator;
  66756. }());
  66757. BABYLON.ShadowGenerator = ShadowGenerator;
  66758. })(BABYLON || (BABYLON = {}));
  66759. //# sourceMappingURL=babylon.shadowGenerator.js.map
  66760. var BABYLON;
  66761. (function (BABYLON) {
  66762. var DefaultLoadingScreen = /** @class */ (function () {
  66763. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  66764. if (_loadingText === void 0) { _loadingText = ""; }
  66765. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  66766. var _this = this;
  66767. this._renderingCanvas = _renderingCanvas;
  66768. this._loadingText = _loadingText;
  66769. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  66770. // Resize
  66771. this._resizeLoadingUI = function () {
  66772. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  66773. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  66774. if (!_this._loadingDiv) {
  66775. return;
  66776. }
  66777. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  66778. _this._loadingDiv.style.left = canvasRect.left + "px";
  66779. _this._loadingDiv.style.top = canvasRect.top + "px";
  66780. _this._loadingDiv.style.width = canvasRect.width + "px";
  66781. _this._loadingDiv.style.height = canvasRect.height + "px";
  66782. };
  66783. }
  66784. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  66785. if (this._loadingDiv) {
  66786. // Do not add a loading screen if there is already one
  66787. return;
  66788. }
  66789. this._loadingDiv = document.createElement("div");
  66790. this._loadingDiv.id = "babylonjsLoadingDiv";
  66791. this._loadingDiv.style.opacity = "0";
  66792. this._loadingDiv.style.transition = "opacity 1.5s ease";
  66793. this._loadingDiv.style.pointerEvents = "none";
  66794. // Loading text
  66795. this._loadingTextDiv = document.createElement("div");
  66796. this._loadingTextDiv.style.position = "absolute";
  66797. this._loadingTextDiv.style.left = "0";
  66798. this._loadingTextDiv.style.top = "50%";
  66799. this._loadingTextDiv.style.marginTop = "80px";
  66800. this._loadingTextDiv.style.width = "100%";
  66801. this._loadingTextDiv.style.height = "20px";
  66802. this._loadingTextDiv.style.fontFamily = "Arial";
  66803. this._loadingTextDiv.style.fontSize = "14px";
  66804. this._loadingTextDiv.style.color = "white";
  66805. this._loadingTextDiv.style.textAlign = "center";
  66806. this._loadingTextDiv.innerHTML = "Loading";
  66807. this._loadingDiv.appendChild(this._loadingTextDiv);
  66808. //set the predefined text
  66809. this._loadingTextDiv.innerHTML = this._loadingText;
  66810. // Generating keyframes
  66811. var style = document.createElement('style');
  66812. style.type = 'text/css';
  66813. 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 }";
  66814. style.innerHTML = keyFrames;
  66815. document.getElementsByTagName('head')[0].appendChild(style);
  66816. // Loading img
  66817. var imgBack = new Image();
  66818. 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";
  66819. imgBack.style.position = "absolute";
  66820. imgBack.style.left = "50%";
  66821. imgBack.style.top = "50%";
  66822. imgBack.style.marginLeft = "-60px";
  66823. imgBack.style.marginTop = "-60px";
  66824. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  66825. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  66826. imgBack.style.transformOrigin = "50% 50%";
  66827. imgBack.style.webkitTransformOrigin = "50% 50%";
  66828. this._loadingDiv.appendChild(imgBack);
  66829. this._resizeLoadingUI();
  66830. window.addEventListener("resize", this._resizeLoadingUI);
  66831. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66832. document.body.appendChild(this._loadingDiv);
  66833. this._loadingDiv.style.opacity = "1";
  66834. };
  66835. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  66836. var _this = this;
  66837. if (!this._loadingDiv) {
  66838. return;
  66839. }
  66840. var onTransitionEnd = function () {
  66841. if (!_this._loadingDiv) {
  66842. return;
  66843. }
  66844. document.body.removeChild(_this._loadingDiv);
  66845. window.removeEventListener("resize", _this._resizeLoadingUI);
  66846. _this._loadingDiv = null;
  66847. };
  66848. this._loadingDiv.style.opacity = "0";
  66849. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  66850. };
  66851. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  66852. set: function (text) {
  66853. this._loadingText = text;
  66854. if (this._loadingTextDiv) {
  66855. this._loadingTextDiv.innerHTML = this._loadingText;
  66856. }
  66857. },
  66858. enumerable: true,
  66859. configurable: true
  66860. });
  66861. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  66862. get: function () {
  66863. return this._loadingDivBackgroundColor;
  66864. },
  66865. set: function (color) {
  66866. this._loadingDivBackgroundColor = color;
  66867. if (!this._loadingDiv) {
  66868. return;
  66869. }
  66870. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  66871. },
  66872. enumerable: true,
  66873. configurable: true
  66874. });
  66875. return DefaultLoadingScreen;
  66876. }());
  66877. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  66878. })(BABYLON || (BABYLON = {}));
  66879. //# sourceMappingURL=babylon.loadingScreen.js.map
  66880. var BABYLON;
  66881. (function (BABYLON) {
  66882. var SceneLoaderProgressEvent = /** @class */ (function () {
  66883. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  66884. this.lengthComputable = lengthComputable;
  66885. this.loaded = loaded;
  66886. this.total = total;
  66887. }
  66888. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  66889. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  66890. };
  66891. return SceneLoaderProgressEvent;
  66892. }());
  66893. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  66894. var SceneLoader = /** @class */ (function () {
  66895. function SceneLoader() {
  66896. }
  66897. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  66898. get: function () {
  66899. return 0;
  66900. },
  66901. enumerable: true,
  66902. configurable: true
  66903. });
  66904. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  66905. get: function () {
  66906. return 1;
  66907. },
  66908. enumerable: true,
  66909. configurable: true
  66910. });
  66911. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  66912. get: function () {
  66913. return 2;
  66914. },
  66915. enumerable: true,
  66916. configurable: true
  66917. });
  66918. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  66919. get: function () {
  66920. return 3;
  66921. },
  66922. enumerable: true,
  66923. configurable: true
  66924. });
  66925. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  66926. get: function () {
  66927. return SceneLoader._ForceFullSceneLoadingForIncremental;
  66928. },
  66929. set: function (value) {
  66930. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  66931. },
  66932. enumerable: true,
  66933. configurable: true
  66934. });
  66935. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  66936. get: function () {
  66937. return SceneLoader._ShowLoadingScreen;
  66938. },
  66939. set: function (value) {
  66940. SceneLoader._ShowLoadingScreen = value;
  66941. },
  66942. enumerable: true,
  66943. configurable: true
  66944. });
  66945. Object.defineProperty(SceneLoader, "loggingLevel", {
  66946. get: function () {
  66947. return SceneLoader._loggingLevel;
  66948. },
  66949. set: function (value) {
  66950. SceneLoader._loggingLevel = value;
  66951. },
  66952. enumerable: true,
  66953. configurable: true
  66954. });
  66955. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  66956. get: function () {
  66957. return SceneLoader._CleanBoneMatrixWeights;
  66958. },
  66959. set: function (value) {
  66960. SceneLoader._CleanBoneMatrixWeights = value;
  66961. },
  66962. enumerable: true,
  66963. configurable: true
  66964. });
  66965. SceneLoader._getDefaultPlugin = function () {
  66966. return SceneLoader._registeredPlugins[".babylon"];
  66967. };
  66968. SceneLoader._getPluginForExtension = function (extension) {
  66969. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  66970. if (registeredPlugin) {
  66971. return registeredPlugin;
  66972. }
  66973. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin.");
  66974. return SceneLoader._getDefaultPlugin();
  66975. };
  66976. SceneLoader._getPluginForDirectLoad = function (data) {
  66977. for (var extension in SceneLoader._registeredPlugins) {
  66978. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  66979. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  66980. return SceneLoader._registeredPlugins[extension];
  66981. }
  66982. }
  66983. return SceneLoader._getDefaultPlugin();
  66984. };
  66985. SceneLoader._getPluginForFilename = function (sceneFilename) {
  66986. if (sceneFilename.name) {
  66987. sceneFilename = sceneFilename.name;
  66988. }
  66989. var queryStringPosition = sceneFilename.indexOf("?");
  66990. if (queryStringPosition !== -1) {
  66991. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  66992. }
  66993. var dotPosition = sceneFilename.lastIndexOf(".");
  66994. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  66995. return SceneLoader._getPluginForExtension(extension);
  66996. };
  66997. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  66998. SceneLoader._getDirectLoad = function (sceneFilename) {
  66999. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67000. return sceneFilename.substr(5);
  67001. }
  67002. return null;
  67003. };
  67004. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67005. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67006. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67007. var plugin;
  67008. if (registeredPlugin.plugin.createPlugin) {
  67009. plugin = registeredPlugin.plugin.createPlugin();
  67010. }
  67011. else {
  67012. plugin = registeredPlugin.plugin;
  67013. }
  67014. var useArrayBuffer = registeredPlugin.isBinary;
  67015. var database;
  67016. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67017. var dataCallback = function (data, responseURL) {
  67018. if (scene.isDisposed) {
  67019. onError("Scene has been disposed");
  67020. return;
  67021. }
  67022. scene.database = database;
  67023. onSuccess(plugin, data, responseURL);
  67024. };
  67025. var request = null;
  67026. var pluginDisposed = false;
  67027. var onDisposeObservable = plugin.onDisposeObservable;
  67028. if (onDisposeObservable) {
  67029. onDisposeObservable.add(function () {
  67030. pluginDisposed = true;
  67031. if (request) {
  67032. request.abort();
  67033. request = null;
  67034. }
  67035. onDispose();
  67036. });
  67037. }
  67038. var manifestChecked = function () {
  67039. if (pluginDisposed) {
  67040. return;
  67041. }
  67042. var url = rootUrl + sceneFilename;
  67043. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67044. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67045. } : undefined, database, useArrayBuffer, function (request, exception) {
  67046. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67047. });
  67048. };
  67049. if (directLoad) {
  67050. dataCallback(directLoad);
  67051. return plugin;
  67052. }
  67053. if (rootUrl.indexOf("file:") === -1) {
  67054. var engine = scene.getEngine();
  67055. var canUseOfflineSupport = engine.enableOfflineSupport;
  67056. if (canUseOfflineSupport) {
  67057. // Also check for exceptions
  67058. var exceptionFound = false;
  67059. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67060. var regex = _a[_i];
  67061. if (regex.test(rootUrl + sceneFilename)) {
  67062. exceptionFound = true;
  67063. break;
  67064. }
  67065. }
  67066. canUseOfflineSupport = !exceptionFound;
  67067. }
  67068. if (canUseOfflineSupport) {
  67069. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67070. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67071. }
  67072. else {
  67073. manifestChecked();
  67074. }
  67075. }
  67076. // Loading file from disk via input file or drag'n'drop
  67077. else {
  67078. var fileOrString = sceneFilename;
  67079. if (fileOrString.name) { // File
  67080. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67081. }
  67082. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67083. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67084. }
  67085. else {
  67086. onError("Unable to find file named " + sceneFilename);
  67087. }
  67088. }
  67089. return plugin;
  67090. };
  67091. // Public functions
  67092. SceneLoader.GetPluginForExtension = function (extension) {
  67093. return SceneLoader._getPluginForExtension(extension).plugin;
  67094. };
  67095. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67096. return !!SceneLoader._registeredPlugins[extension];
  67097. };
  67098. SceneLoader.RegisterPlugin = function (plugin) {
  67099. if (typeof plugin.extensions === "string") {
  67100. var extension = plugin.extensions;
  67101. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67102. plugin: plugin,
  67103. isBinary: false
  67104. };
  67105. }
  67106. else {
  67107. var extensions = plugin.extensions;
  67108. Object.keys(extensions).forEach(function (extension) {
  67109. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67110. plugin: plugin,
  67111. isBinary: extensions[extension].isBinary
  67112. };
  67113. });
  67114. }
  67115. };
  67116. /**
  67117. * Import meshes into a scene
  67118. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67119. * @param rootUrl a string that defines the root url for scene and resources
  67120. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67121. * @param scene the instance of BABYLON.Scene to append to
  67122. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67123. * @param onProgress a callback with a progress event for each file being loaded
  67124. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67125. * @param pluginExtension the extension used to determine the plugin
  67126. * @returns The loaded plugin
  67127. */
  67128. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67129. if (onSuccess === void 0) { onSuccess = null; }
  67130. if (onProgress === void 0) { onProgress = null; }
  67131. if (onError === void 0) { onError = null; }
  67132. if (pluginExtension === void 0) { pluginExtension = null; }
  67133. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67134. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67135. return null;
  67136. }
  67137. var loadingToken = {};
  67138. scene._addPendingData(loadingToken);
  67139. var disposeHandler = function () {
  67140. scene._removePendingData(loadingToken);
  67141. };
  67142. var errorHandler = function (message, exception) {
  67143. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67144. if (onError) {
  67145. onError(scene, errorMessage, exception);
  67146. }
  67147. else {
  67148. BABYLON.Tools.Error(errorMessage);
  67149. // should the exception be thrown?
  67150. }
  67151. disposeHandler();
  67152. };
  67153. var progressHandler = onProgress ? function (event) {
  67154. try {
  67155. onProgress(event);
  67156. }
  67157. catch (e) {
  67158. errorHandler("Error in onProgress callback", e);
  67159. }
  67160. } : undefined;
  67161. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67162. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67163. if (onSuccess) {
  67164. try {
  67165. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67166. }
  67167. catch (e) {
  67168. errorHandler("Error in onSuccess callback", e);
  67169. }
  67170. }
  67171. scene._removePendingData(loadingToken);
  67172. };
  67173. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67174. if (plugin.rewriteRootURL) {
  67175. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67176. }
  67177. if (sceneFilename === "") {
  67178. if (sceneFilename === "") {
  67179. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67180. }
  67181. }
  67182. if (plugin.importMesh) {
  67183. var syncedPlugin = plugin;
  67184. var meshes = new Array();
  67185. var particleSystems = new Array();
  67186. var skeletons = new Array();
  67187. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67188. return;
  67189. }
  67190. scene.loadingPluginName = plugin.name;
  67191. successHandler(meshes, particleSystems, skeletons, []);
  67192. }
  67193. else {
  67194. var asyncedPlugin = plugin;
  67195. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67196. scene.loadingPluginName = plugin.name;
  67197. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67198. }).catch(function (error) {
  67199. errorHandler(error.message, error);
  67200. });
  67201. }
  67202. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67203. };
  67204. /**
  67205. * Import meshes into a scene
  67206. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67207. * @param rootUrl a string that defines the root url for scene and resources
  67208. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67209. * @param scene the instance of BABYLON.Scene to append to
  67210. * @param onProgress a callback with a progress event for each file being loaded
  67211. * @param pluginExtension the extension used to determine the plugin
  67212. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67213. */
  67214. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67215. if (onProgress === void 0) { onProgress = null; }
  67216. if (pluginExtension === void 0) { pluginExtension = null; }
  67217. return new Promise(function (resolve, reject) {
  67218. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67219. resolve({
  67220. meshes: meshes,
  67221. particleSystems: particleSystems,
  67222. skeletons: skeletons,
  67223. animationGroups: animationGroups
  67224. });
  67225. }, onProgress, function (scene, message, exception) {
  67226. reject(exception || new Error(message));
  67227. }, pluginExtension);
  67228. });
  67229. };
  67230. /**
  67231. * Load a scene
  67232. * @param rootUrl a string that defines the root url for scene and resources
  67233. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67234. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67235. * @param onSuccess a callback with the scene when import succeeds
  67236. * @param onProgress a callback with a progress event for each file being loaded
  67237. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67238. * @param pluginExtension the extension used to determine the plugin
  67239. * @returns The loaded plugin
  67240. */
  67241. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67242. if (onSuccess === void 0) { onSuccess = null; }
  67243. if (onProgress === void 0) { onProgress = null; }
  67244. if (onError === void 0) { onError = null; }
  67245. if (pluginExtension === void 0) { pluginExtension = null; }
  67246. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67247. };
  67248. /**
  67249. * Load a scene
  67250. * @param rootUrl a string that defines the root url for scene and resources
  67251. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67252. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67253. * @param onProgress a callback with a progress event for each file being loaded
  67254. * @param pluginExtension the extension used to determine the plugin
  67255. * @returns The loaded scene
  67256. */
  67257. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67258. if (onProgress === void 0) { onProgress = null; }
  67259. if (pluginExtension === void 0) { pluginExtension = null; }
  67260. return new Promise(function (resolve, reject) {
  67261. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67262. resolve(scene);
  67263. }, onProgress, function (scene, message, exception) {
  67264. reject(exception || new Error(message));
  67265. }, pluginExtension);
  67266. });
  67267. };
  67268. /**
  67269. * Append a scene
  67270. * @param rootUrl a string that defines the root url for scene and resources
  67271. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67272. * @param scene is the instance of BABYLON.Scene to append to
  67273. * @param onSuccess a callback with the scene when import succeeds
  67274. * @param onProgress a callback with a progress event for each file being loaded
  67275. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67276. * @param pluginExtension the extension used to determine the plugin
  67277. * @returns The loaded plugin
  67278. */
  67279. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67280. if (onSuccess === void 0) { onSuccess = null; }
  67281. if (onProgress === void 0) { onProgress = null; }
  67282. if (onError === void 0) { onError = null; }
  67283. if (pluginExtension === void 0) { pluginExtension = null; }
  67284. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67285. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67286. return null;
  67287. }
  67288. if (SceneLoader.ShowLoadingScreen) {
  67289. scene.getEngine().displayLoadingUI();
  67290. }
  67291. var loadingToken = {};
  67292. scene._addPendingData(loadingToken);
  67293. var disposeHandler = function () {
  67294. scene._removePendingData(loadingToken);
  67295. scene.getEngine().hideLoadingUI();
  67296. };
  67297. var errorHandler = function (message, exception) {
  67298. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67299. if (onError) {
  67300. onError(scene, errorMessage, exception);
  67301. }
  67302. else {
  67303. BABYLON.Tools.Error(errorMessage);
  67304. // should the exception be thrown?
  67305. }
  67306. disposeHandler();
  67307. };
  67308. var progressHandler = onProgress ? function (event) {
  67309. try {
  67310. onProgress(event);
  67311. }
  67312. catch (e) {
  67313. errorHandler("Error in onProgress callback", e);
  67314. }
  67315. } : undefined;
  67316. var successHandler = function () {
  67317. if (onSuccess) {
  67318. try {
  67319. onSuccess(scene);
  67320. }
  67321. catch (e) {
  67322. errorHandler("Error in onSuccess callback", e);
  67323. }
  67324. }
  67325. scene._removePendingData(loadingToken);
  67326. };
  67327. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67328. if (sceneFilename === "") {
  67329. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67330. }
  67331. if (plugin.load) {
  67332. var syncedPlugin = plugin;
  67333. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67334. return;
  67335. }
  67336. scene.loadingPluginName = plugin.name;
  67337. successHandler();
  67338. }
  67339. else {
  67340. var asyncedPlugin = plugin;
  67341. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67342. scene.loadingPluginName = plugin.name;
  67343. successHandler();
  67344. }).catch(function (error) {
  67345. errorHandler(error.message, error);
  67346. });
  67347. }
  67348. if (SceneLoader.ShowLoadingScreen) {
  67349. scene.executeWhenReady(function () {
  67350. scene.getEngine().hideLoadingUI();
  67351. });
  67352. }
  67353. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67354. };
  67355. /**
  67356. * Append a scene
  67357. * @param rootUrl a string that defines the root url for scene and resources
  67358. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67359. * @param scene is the instance of BABYLON.Scene to append to
  67360. * @param onProgress a callback with a progress event for each file being loaded
  67361. * @param pluginExtension the extension used to determine the plugin
  67362. * @returns The given scene
  67363. */
  67364. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67365. if (onProgress === void 0) { onProgress = null; }
  67366. if (pluginExtension === void 0) { pluginExtension = null; }
  67367. return new Promise(function (resolve, reject) {
  67368. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67369. resolve(scene);
  67370. }, onProgress, function (scene, message, exception) {
  67371. reject(exception || new Error(message));
  67372. }, pluginExtension);
  67373. });
  67374. };
  67375. /**
  67376. * Load a scene into an asset container
  67377. * @param rootUrl a string that defines the root url for scene and resources
  67378. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67379. * @param scene is the instance of BABYLON.Scene to append to
  67380. * @param onSuccess a callback with the scene when import succeeds
  67381. * @param onProgress a callback with a progress event for each file being loaded
  67382. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67383. * @param pluginExtension the extension used to determine the plugin
  67384. * @returns The loaded plugin
  67385. */
  67386. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67387. if (onSuccess === void 0) { onSuccess = null; }
  67388. if (onProgress === void 0) { onProgress = null; }
  67389. if (onError === void 0) { onError = null; }
  67390. if (pluginExtension === void 0) { pluginExtension = null; }
  67391. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67392. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67393. return null;
  67394. }
  67395. var loadingToken = {};
  67396. scene._addPendingData(loadingToken);
  67397. var disposeHandler = function () {
  67398. scene._removePendingData(loadingToken);
  67399. };
  67400. var errorHandler = function (message, exception) {
  67401. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67402. if (onError) {
  67403. onError(scene, errorMessage, exception);
  67404. }
  67405. else {
  67406. BABYLON.Tools.Error(errorMessage);
  67407. // should the exception be thrown?
  67408. }
  67409. disposeHandler();
  67410. };
  67411. var progressHandler = onProgress ? function (event) {
  67412. try {
  67413. onProgress(event);
  67414. }
  67415. catch (e) {
  67416. errorHandler("Error in onProgress callback", e);
  67417. }
  67418. } : undefined;
  67419. var successHandler = function (assets) {
  67420. if (onSuccess) {
  67421. try {
  67422. onSuccess(assets);
  67423. }
  67424. catch (e) {
  67425. errorHandler("Error in onSuccess callback", e);
  67426. }
  67427. }
  67428. scene._removePendingData(loadingToken);
  67429. };
  67430. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67431. if (plugin.loadAssetContainer) {
  67432. var syncedPlugin = plugin;
  67433. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  67434. if (!assetContainer) {
  67435. return;
  67436. }
  67437. scene.loadingPluginName = plugin.name;
  67438. successHandler(assetContainer);
  67439. }
  67440. else if (plugin.loadAssetContainerAsync) {
  67441. var asyncedPlugin = plugin;
  67442. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  67443. scene.loadingPluginName = plugin.name;
  67444. successHandler(assetContainer);
  67445. }).catch(function (error) {
  67446. errorHandler(error.message, error);
  67447. });
  67448. }
  67449. else {
  67450. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  67451. }
  67452. if (SceneLoader.ShowLoadingScreen) {
  67453. scene.executeWhenReady(function () {
  67454. scene.getEngine().hideLoadingUI();
  67455. });
  67456. }
  67457. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67458. };
  67459. /**
  67460. * Load a scene into an asset container
  67461. * @param rootUrl a string that defines the root url for scene and resources
  67462. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene
  67463. * @param scene is the instance of BABYLON.Scene to append to
  67464. * @param onProgress a callback with a progress event for each file being loaded
  67465. * @param pluginExtension the extension used to determine the plugin
  67466. * @returns The loaded asset container
  67467. */
  67468. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67469. if (onProgress === void 0) { onProgress = null; }
  67470. if (pluginExtension === void 0) { pluginExtension = null; }
  67471. return new Promise(function (resolve, reject) {
  67472. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  67473. resolve(assetContainer);
  67474. }, onProgress, function (scene, message, exception) {
  67475. reject(exception || new Error(message));
  67476. }, pluginExtension);
  67477. });
  67478. };
  67479. // Flags
  67480. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  67481. SceneLoader._ShowLoadingScreen = true;
  67482. SceneLoader._CleanBoneMatrixWeights = false;
  67483. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  67484. // Members
  67485. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  67486. SceneLoader._registeredPlugins = {};
  67487. return SceneLoader;
  67488. }());
  67489. BABYLON.SceneLoader = SceneLoader;
  67490. ;
  67491. })(BABYLON || (BABYLON = {}));
  67492. //# sourceMappingURL=babylon.sceneLoader.js.map
  67493. var BABYLON;
  67494. (function (BABYLON) {
  67495. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  67496. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67497. var parsedMaterial = parsedData.materials[index];
  67498. if (parsedMaterial.id === id) {
  67499. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67500. }
  67501. }
  67502. return null;
  67503. };
  67504. var isDescendantOf = function (mesh, names, hierarchyIds) {
  67505. for (var i in names) {
  67506. if (mesh.name === names[i]) {
  67507. hierarchyIds.push(mesh.id);
  67508. return true;
  67509. }
  67510. }
  67511. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  67512. hierarchyIds.push(mesh.id);
  67513. return true;
  67514. }
  67515. return false;
  67516. };
  67517. var logOperation = function (operation, producer) {
  67518. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  67519. };
  67520. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  67521. if (addToScene === void 0) { addToScene = false; }
  67522. var container = new BABYLON.AssetContainer(scene);
  67523. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67524. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67525. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67526. // and avoid problems with multiple concurrent .babylon loads.
  67527. var log = "importScene has failed JSON parse";
  67528. try {
  67529. var parsedData = JSON.parse(data);
  67530. log = "";
  67531. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67532. var index;
  67533. var cache;
  67534. // Lights
  67535. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  67536. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  67537. var parsedLight = parsedData.lights[index];
  67538. var light = BABYLON.Light.Parse(parsedLight, scene);
  67539. if (light) {
  67540. container.lights.push(light);
  67541. log += (index === 0 ? "\n\tLights:" : "");
  67542. log += "\n\t\t" + light.toString(fullDetails);
  67543. }
  67544. }
  67545. }
  67546. // Animations
  67547. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  67548. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  67549. var parsedAnimation = parsedData.animations[index];
  67550. var animation = BABYLON.Animation.Parse(parsedAnimation);
  67551. scene.animations.push(animation);
  67552. container.animations.push(animation);
  67553. log += (index === 0 ? "\n\tAnimations:" : "");
  67554. log += "\n\t\t" + animation.toString(fullDetails);
  67555. }
  67556. }
  67557. // Materials
  67558. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  67559. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  67560. var parsedMaterial = parsedData.materials[index];
  67561. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  67562. container.materials.push(mat);
  67563. log += (index === 0 ? "\n\tMaterials:" : "");
  67564. log += "\n\t\t" + mat.toString(fullDetails);
  67565. }
  67566. }
  67567. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67568. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  67569. var parsedMultiMaterial = parsedData.multiMaterials[index];
  67570. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67571. container.multiMaterials.push(mmat);
  67572. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  67573. log += "\n\t\t" + mmat.toString(fullDetails);
  67574. }
  67575. }
  67576. // Morph targets
  67577. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67578. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67579. var managerData = _a[_i];
  67580. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  67581. }
  67582. }
  67583. // Skeletons
  67584. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67585. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  67586. var parsedSkeleton = parsedData.skeletons[index];
  67587. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67588. container.skeletons.push(skeleton);
  67589. log += (index === 0 ? "\n\tSkeletons:" : "");
  67590. log += "\n\t\t" + skeleton.toString(fullDetails);
  67591. }
  67592. }
  67593. // Geometries
  67594. var geometries = parsedData.geometries;
  67595. if (geometries !== undefined && geometries !== null) {
  67596. var addedGeometry = new Array();
  67597. // Boxes
  67598. var boxes = geometries.boxes;
  67599. if (boxes !== undefined && boxes !== null) {
  67600. for (index = 0, cache = boxes.length; index < cache; index++) {
  67601. var parsedBox = boxes[index];
  67602. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  67603. }
  67604. }
  67605. // Spheres
  67606. var spheres = geometries.spheres;
  67607. if (spheres !== undefined && spheres !== null) {
  67608. for (index = 0, cache = spheres.length; index < cache; index++) {
  67609. var parsedSphere = spheres[index];
  67610. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  67611. }
  67612. }
  67613. // Cylinders
  67614. var cylinders = geometries.cylinders;
  67615. if (cylinders !== undefined && cylinders !== null) {
  67616. for (index = 0, cache = cylinders.length; index < cache; index++) {
  67617. var parsedCylinder = cylinders[index];
  67618. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  67619. }
  67620. }
  67621. // Toruses
  67622. var toruses = geometries.toruses;
  67623. if (toruses !== undefined && toruses !== null) {
  67624. for (index = 0, cache = toruses.length; index < cache; index++) {
  67625. var parsedTorus = toruses[index];
  67626. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  67627. }
  67628. }
  67629. // Grounds
  67630. var grounds = geometries.grounds;
  67631. if (grounds !== undefined && grounds !== null) {
  67632. for (index = 0, cache = grounds.length; index < cache; index++) {
  67633. var parsedGround = grounds[index];
  67634. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  67635. }
  67636. }
  67637. // Planes
  67638. var planes = geometries.planes;
  67639. if (planes !== undefined && planes !== null) {
  67640. for (index = 0, cache = planes.length; index < cache; index++) {
  67641. var parsedPlane = planes[index];
  67642. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  67643. }
  67644. }
  67645. // TorusKnots
  67646. var torusKnots = geometries.torusKnots;
  67647. if (torusKnots !== undefined && torusKnots !== null) {
  67648. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  67649. var parsedTorusKnot = torusKnots[index];
  67650. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  67651. }
  67652. }
  67653. // VertexData
  67654. var vertexData = geometries.vertexData;
  67655. if (vertexData !== undefined && vertexData !== null) {
  67656. for (index = 0, cache = vertexData.length; index < cache; index++) {
  67657. var parsedVertexData = vertexData[index];
  67658. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  67659. }
  67660. }
  67661. addedGeometry.forEach(function (g) {
  67662. if (g) {
  67663. container.geometries.push(g);
  67664. }
  67665. });
  67666. }
  67667. // Transform nodes
  67668. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  67669. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  67670. var parsedTransformNode = parsedData.transformNodes[index];
  67671. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  67672. container.transformNodes.push(node);
  67673. }
  67674. }
  67675. // Meshes
  67676. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67677. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67678. var parsedMesh = parsedData.meshes[index];
  67679. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67680. container.meshes.push(mesh);
  67681. log += (index === 0 ? "\n\tMeshes:" : "");
  67682. log += "\n\t\t" + mesh.toString(fullDetails);
  67683. }
  67684. }
  67685. // Cameras
  67686. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  67687. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  67688. var parsedCamera = parsedData.cameras[index];
  67689. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  67690. container.cameras.push(camera);
  67691. log += (index === 0 ? "\n\tCameras:" : "");
  67692. log += "\n\t\t" + camera.toString(fullDetails);
  67693. }
  67694. }
  67695. // Browsing all the graph to connect the dots
  67696. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  67697. var camera = scene.cameras[index];
  67698. if (camera._waitingParentId) {
  67699. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  67700. camera._waitingParentId = null;
  67701. }
  67702. }
  67703. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67704. var light_1 = scene.lights[index];
  67705. if (light_1 && light_1._waitingParentId) {
  67706. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  67707. light_1._waitingParentId = null;
  67708. }
  67709. }
  67710. // Sounds
  67711. // TODO: add sound
  67712. var loadedSounds = [];
  67713. var loadedSound;
  67714. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  67715. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  67716. var parsedSound = parsedData.sounds[index];
  67717. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  67718. if (!parsedSound.url)
  67719. parsedSound.url = parsedSound.name;
  67720. if (!loadedSounds[parsedSound.url]) {
  67721. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  67722. loadedSounds[parsedSound.url] = loadedSound;
  67723. container.sounds.push(loadedSound);
  67724. }
  67725. else {
  67726. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  67727. }
  67728. }
  67729. else {
  67730. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  67731. }
  67732. }
  67733. }
  67734. loadedSounds = [];
  67735. // Connect parents & children and parse actions
  67736. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  67737. var transformNode = scene.transformNodes[index];
  67738. if (transformNode._waitingParentId) {
  67739. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  67740. transformNode._waitingParentId = null;
  67741. }
  67742. }
  67743. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67744. var mesh = scene.meshes[index];
  67745. if (mesh._waitingParentId) {
  67746. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  67747. mesh._waitingParentId = null;
  67748. }
  67749. if (mesh._waitingActions) {
  67750. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  67751. mesh._waitingActions = null;
  67752. }
  67753. }
  67754. // freeze world matrix application
  67755. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  67756. var currentMesh = scene.meshes[index];
  67757. if (currentMesh._waitingFreezeWorldMatrix) {
  67758. currentMesh.freezeWorldMatrix();
  67759. currentMesh._waitingFreezeWorldMatrix = null;
  67760. }
  67761. else {
  67762. currentMesh.computeWorldMatrix(true);
  67763. }
  67764. }
  67765. // Particles Systems
  67766. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  67767. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  67768. var parsedParticleSystem = parsedData.particleSystems[index];
  67769. if (parsedParticleSystem.activeParticleCount) {
  67770. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67771. container.particleSystems.push(ps);
  67772. }
  67773. else {
  67774. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  67775. container.particleSystems.push(ps);
  67776. }
  67777. }
  67778. }
  67779. // Lens flares
  67780. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  67781. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  67782. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  67783. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  67784. container.lensFlareSystems.push(lf);
  67785. }
  67786. }
  67787. // Shadows
  67788. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  67789. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  67790. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  67791. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  67792. container.shadowGenerators.push(sg);
  67793. }
  67794. }
  67795. // Lights exclusions / inclusions
  67796. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  67797. var light_2 = scene.lights[index];
  67798. // Excluded check
  67799. if (light_2._excludedMeshesIds.length > 0) {
  67800. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  67801. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  67802. if (excludedMesh) {
  67803. light_2.excludedMeshes.push(excludedMesh);
  67804. }
  67805. }
  67806. light_2._excludedMeshesIds = [];
  67807. }
  67808. // Included check
  67809. if (light_2._includedOnlyMeshesIds.length > 0) {
  67810. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  67811. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  67812. if (includedOnlyMesh) {
  67813. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  67814. }
  67815. }
  67816. light_2._includedOnlyMeshesIds = [];
  67817. }
  67818. }
  67819. // Effect layers
  67820. if (parsedData.effectLayers) {
  67821. for (index = 0; index < parsedData.effectLayers.length; index++) {
  67822. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  67823. container.effectLayers.push(effectLayer);
  67824. }
  67825. }
  67826. // Actions (scene)
  67827. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  67828. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  67829. }
  67830. if (!addToScene) {
  67831. container.removeAllFromScene();
  67832. }
  67833. }
  67834. catch (err) {
  67835. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  67836. if (onError) {
  67837. onError(msg, err);
  67838. }
  67839. else {
  67840. BABYLON.Tools.Log(msg);
  67841. throw err;
  67842. }
  67843. }
  67844. finally {
  67845. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  67846. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  67847. }
  67848. }
  67849. return container;
  67850. };
  67851. BABYLON.SceneLoader.RegisterPlugin({
  67852. name: "babylon.js",
  67853. extensions: ".babylon",
  67854. canDirectLoad: function (data) {
  67855. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  67856. return true;
  67857. }
  67858. return false;
  67859. },
  67860. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  67861. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  67862. // when SceneLoader.debugLogging = true (default), or exception encountered.
  67863. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  67864. // and avoid problems with multiple concurrent .babylon loads.
  67865. var log = "importMesh has failed JSON parse";
  67866. try {
  67867. var parsedData = JSON.parse(data);
  67868. log = "";
  67869. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  67870. if (!meshesNames) {
  67871. meshesNames = null;
  67872. }
  67873. else if (!Array.isArray(meshesNames)) {
  67874. meshesNames = [meshesNames];
  67875. }
  67876. var hierarchyIds = new Array();
  67877. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  67878. var loadedSkeletonsIds = [];
  67879. var loadedMaterialsIds = [];
  67880. var index;
  67881. var cache;
  67882. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  67883. var parsedMesh = parsedData.meshes[index];
  67884. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  67885. if (meshesNames !== null) {
  67886. // Remove found mesh name from list.
  67887. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  67888. }
  67889. //Geometry?
  67890. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  67891. //does the file contain geometries?
  67892. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  67893. //find the correct geometry and add it to the scene
  67894. var found = false;
  67895. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  67896. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  67897. return;
  67898. }
  67899. else {
  67900. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  67901. if (parsedGeometryData.id === parsedMesh.geometryId) {
  67902. switch (geometryType) {
  67903. case "boxes":
  67904. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  67905. break;
  67906. case "spheres":
  67907. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  67908. break;
  67909. case "cylinders":
  67910. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  67911. break;
  67912. case "toruses":
  67913. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  67914. break;
  67915. case "grounds":
  67916. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  67917. break;
  67918. case "planes":
  67919. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  67920. break;
  67921. case "torusKnots":
  67922. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  67923. break;
  67924. case "vertexData":
  67925. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  67926. break;
  67927. }
  67928. found = true;
  67929. }
  67930. });
  67931. }
  67932. });
  67933. if (found === false) {
  67934. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  67935. }
  67936. }
  67937. }
  67938. // Material ?
  67939. if (parsedMesh.materialId) {
  67940. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  67941. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  67942. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  67943. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  67944. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  67945. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  67946. var subMatId = parsedMultiMaterial.materials[matIndex];
  67947. loadedMaterialsIds.push(subMatId);
  67948. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  67949. if (mat) {
  67950. log += "\n\tMaterial " + mat.toString(fullDetails);
  67951. }
  67952. }
  67953. loadedMaterialsIds.push(parsedMultiMaterial.id);
  67954. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  67955. if (mmat) {
  67956. materialFound = true;
  67957. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  67958. }
  67959. break;
  67960. }
  67961. }
  67962. }
  67963. if (materialFound === false) {
  67964. loadedMaterialsIds.push(parsedMesh.materialId);
  67965. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  67966. if (!mat) {
  67967. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  67968. }
  67969. else {
  67970. log += "\n\tMaterial " + mat.toString(fullDetails);
  67971. }
  67972. }
  67973. }
  67974. // Skeleton ?
  67975. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  67976. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  67977. if (skeletonAlreadyLoaded === false) {
  67978. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  67979. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  67980. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  67981. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  67982. skeletons.push(skeleton);
  67983. loadedSkeletonsIds.push(parsedSkeleton.id);
  67984. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  67985. }
  67986. }
  67987. }
  67988. }
  67989. // Morph targets ?
  67990. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  67991. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  67992. var managerData = _a[_i];
  67993. BABYLON.MorphTargetManager.Parse(managerData, scene);
  67994. }
  67995. }
  67996. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  67997. meshes.push(mesh);
  67998. log += "\n\tMesh " + mesh.toString(fullDetails);
  67999. }
  68000. }
  68001. // Connecting parents
  68002. var currentMesh;
  68003. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68004. currentMesh = scene.meshes[index];
  68005. if (currentMesh._waitingParentId) {
  68006. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68007. currentMesh._waitingParentId = null;
  68008. }
  68009. }
  68010. // freeze and compute world matrix application
  68011. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68012. currentMesh = scene.meshes[index];
  68013. if (currentMesh._waitingFreezeWorldMatrix) {
  68014. currentMesh.freezeWorldMatrix();
  68015. currentMesh._waitingFreezeWorldMatrix = null;
  68016. }
  68017. else {
  68018. currentMesh.computeWorldMatrix(true);
  68019. }
  68020. }
  68021. }
  68022. // Particles
  68023. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68024. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68025. var parsedParticleSystem = parsedData.particleSystems[index];
  68026. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68027. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68028. }
  68029. }
  68030. }
  68031. return true;
  68032. }
  68033. catch (err) {
  68034. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68035. if (onError) {
  68036. onError(msg, err);
  68037. }
  68038. else {
  68039. BABYLON.Tools.Log(msg);
  68040. throw err;
  68041. }
  68042. }
  68043. finally {
  68044. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68045. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68046. }
  68047. }
  68048. return false;
  68049. },
  68050. load: function (scene, data, rootUrl, onError) {
  68051. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68052. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68053. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68054. // and avoid problems with multiple concurrent .babylon loads.
  68055. var log = "importScene has failed JSON parse";
  68056. try {
  68057. var parsedData = JSON.parse(data);
  68058. log = "";
  68059. // Scene
  68060. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68061. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68062. }
  68063. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68064. scene.autoClear = parsedData.autoClear;
  68065. }
  68066. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68067. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68068. }
  68069. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68070. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68071. }
  68072. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68073. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68074. }
  68075. // Fog
  68076. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68077. scene.fogMode = parsedData.fogMode;
  68078. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68079. scene.fogStart = parsedData.fogStart;
  68080. scene.fogEnd = parsedData.fogEnd;
  68081. scene.fogDensity = parsedData.fogDensity;
  68082. log += "\tFog mode for scene: ";
  68083. switch (scene.fogMode) {
  68084. // getters not compiling, so using hardcoded
  68085. case 1:
  68086. log += "exp\n";
  68087. break;
  68088. case 2:
  68089. log += "exp2\n";
  68090. break;
  68091. case 3:
  68092. log += "linear\n";
  68093. break;
  68094. }
  68095. }
  68096. //Physics
  68097. if (parsedData.physicsEnabled) {
  68098. var physicsPlugin;
  68099. if (parsedData.physicsEngine === "cannon") {
  68100. physicsPlugin = new BABYLON.CannonJSPlugin();
  68101. }
  68102. else if (parsedData.physicsEngine === "oimo") {
  68103. physicsPlugin = new BABYLON.OimoJSPlugin();
  68104. }
  68105. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68106. //else - default engine, which is currently oimo
  68107. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68108. scene.enablePhysics(physicsGravity, physicsPlugin);
  68109. }
  68110. // Metadata
  68111. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68112. scene.metadata = parsedData.metadata;
  68113. }
  68114. //collisions, if defined. otherwise, default is true
  68115. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68116. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68117. }
  68118. scene.workerCollisions = !!parsedData.workerCollisions;
  68119. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68120. if (!container) {
  68121. return false;
  68122. }
  68123. if (parsedData.autoAnimate) {
  68124. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68125. }
  68126. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68127. scene.setActiveCameraByID(parsedData.activeCameraID);
  68128. }
  68129. // Environment texture
  68130. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68131. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68132. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68133. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68134. if (parsedData.environmentTextureRotationY) {
  68135. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68136. }
  68137. scene.environmentTexture = hdrTexture;
  68138. }
  68139. else {
  68140. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68141. if (parsedData.environmentTextureRotationY) {
  68142. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68143. }
  68144. scene.environmentTexture = cubeTexture;
  68145. }
  68146. if (parsedData.createDefaultSkybox === true) {
  68147. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68148. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68149. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68150. }
  68151. }
  68152. // Finish
  68153. return true;
  68154. }
  68155. catch (err) {
  68156. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68157. if (onError) {
  68158. onError(msg, err);
  68159. }
  68160. else {
  68161. BABYLON.Tools.Log(msg);
  68162. throw err;
  68163. }
  68164. }
  68165. finally {
  68166. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68167. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68168. }
  68169. }
  68170. return false;
  68171. },
  68172. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68173. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68174. return container;
  68175. }
  68176. });
  68177. })(BABYLON || (BABYLON = {}));
  68178. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68179. var BABYLON;
  68180. (function (BABYLON) {
  68181. var FilesInput = /** @class */ (function () {
  68182. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68183. this.onProcessFileCallback = function () { return true; };
  68184. this._engine = engine;
  68185. this._currentScene = scene;
  68186. this._sceneLoadedCallback = sceneLoadedCallback;
  68187. this._progressCallback = progressCallback;
  68188. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68189. this._textureLoadingCallback = textureLoadingCallback;
  68190. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68191. this._onReloadCallback = onReloadCallback;
  68192. this._errorCallback = errorCallback;
  68193. }
  68194. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68195. var _this = this;
  68196. if (elementToMonitor) {
  68197. this._elementToMonitor = elementToMonitor;
  68198. this._dragEnterHandler = function (e) { _this.drag(e); };
  68199. this._dragOverHandler = function (e) { _this.drag(e); };
  68200. this._dropHandler = function (e) { _this.drop(e); };
  68201. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68202. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68203. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68204. }
  68205. };
  68206. FilesInput.prototype.dispose = function () {
  68207. if (!this._elementToMonitor) {
  68208. return;
  68209. }
  68210. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68211. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68212. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68213. };
  68214. FilesInput.prototype.renderFunction = function () {
  68215. if (this._additionalRenderLoopLogicCallback) {
  68216. this._additionalRenderLoopLogicCallback();
  68217. }
  68218. if (this._currentScene) {
  68219. if (this._textureLoadingCallback) {
  68220. var remaining = this._currentScene.getWaitingItemsCount();
  68221. if (remaining > 0) {
  68222. this._textureLoadingCallback(remaining);
  68223. }
  68224. }
  68225. this._currentScene.render();
  68226. }
  68227. };
  68228. FilesInput.prototype.drag = function (e) {
  68229. e.stopPropagation();
  68230. e.preventDefault();
  68231. };
  68232. FilesInput.prototype.drop = function (eventDrop) {
  68233. eventDrop.stopPropagation();
  68234. eventDrop.preventDefault();
  68235. this.loadFiles(eventDrop);
  68236. };
  68237. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68238. var _this = this;
  68239. var reader = folder.createReader();
  68240. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68241. reader.readEntries(function (entries) {
  68242. remaining.count += entries.length;
  68243. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68244. var entry = entries_1[_i];
  68245. if (entry.isFile) {
  68246. entry.file(function (file) {
  68247. file.correctName = relativePath + file.name;
  68248. files.push(file);
  68249. if (--remaining.count === 0) {
  68250. callback();
  68251. }
  68252. });
  68253. }
  68254. else if (entry.isDirectory) {
  68255. _this._traverseFolder(entry, files, remaining, callback);
  68256. }
  68257. }
  68258. if (--remaining.count) {
  68259. callback();
  68260. }
  68261. });
  68262. };
  68263. FilesInput.prototype._processFiles = function (files) {
  68264. for (var i = 0; i < files.length; i++) {
  68265. var name = files[i].correctName.toLowerCase();
  68266. var extension = name.split('.').pop();
  68267. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68268. continue;
  68269. }
  68270. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68271. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68272. this._sceneFileToLoad = files[i];
  68273. }
  68274. else {
  68275. FilesInput.FilesToLoad[name] = files[i];
  68276. }
  68277. }
  68278. };
  68279. FilesInput.prototype.loadFiles = function (event) {
  68280. var _this = this;
  68281. if (this._startingProcessingFilesCallback)
  68282. this._startingProcessingFilesCallback();
  68283. // Handling data transfer via drag'n'drop
  68284. if (event && event.dataTransfer && event.dataTransfer.files) {
  68285. this._filesToLoad = event.dataTransfer.files;
  68286. }
  68287. // Handling files from input files
  68288. if (event && event.target && event.target.files) {
  68289. this._filesToLoad = event.target.files;
  68290. }
  68291. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68292. var files_1 = new Array();
  68293. var folders = [];
  68294. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68295. for (var i = 0; i < this._filesToLoad.length; i++) {
  68296. var fileToLoad = this._filesToLoad[i];
  68297. var name_1 = fileToLoad.name.toLowerCase();
  68298. var entry = void 0;
  68299. fileToLoad.correctName = name_1;
  68300. if (items) {
  68301. var item = items[i];
  68302. if (item.getAsEntry) {
  68303. entry = item.getAsEntry();
  68304. }
  68305. else if (item.webkitGetAsEntry) {
  68306. entry = item.webkitGetAsEntry();
  68307. }
  68308. }
  68309. if (!entry) {
  68310. files_1.push(fileToLoad);
  68311. }
  68312. else {
  68313. if (entry.isDirectory) {
  68314. folders.push(entry);
  68315. }
  68316. else {
  68317. files_1.push(fileToLoad);
  68318. }
  68319. }
  68320. }
  68321. if (folders.length === 0) {
  68322. this._processFiles(files_1);
  68323. this._processReload();
  68324. }
  68325. else {
  68326. var remaining = { count: folders.length };
  68327. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68328. var folder = folders_1[_i];
  68329. this._traverseFolder(folder, files_1, remaining, function () {
  68330. _this._processFiles(files_1);
  68331. if (remaining.count === 0) {
  68332. _this._processReload();
  68333. }
  68334. });
  68335. }
  68336. }
  68337. }
  68338. };
  68339. FilesInput.prototype._processReload = function () {
  68340. if (this._onReloadCallback) {
  68341. this._onReloadCallback(this._sceneFileToLoad);
  68342. }
  68343. else {
  68344. this.reload();
  68345. }
  68346. };
  68347. FilesInput.prototype.reload = function () {
  68348. var _this = this;
  68349. // If a scene file has been provided
  68350. if (this._sceneFileToLoad) {
  68351. if (this._currentScene) {
  68352. if (BABYLON.Tools.errorsCount > 0) {
  68353. BABYLON.Tools.ClearLogCache();
  68354. }
  68355. this._engine.stopRenderLoop();
  68356. this._currentScene.dispose();
  68357. }
  68358. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68359. if (_this._progressCallback) {
  68360. _this._progressCallback(progress);
  68361. }
  68362. }).then(function (scene) {
  68363. _this._currentScene = scene;
  68364. if (_this._sceneLoadedCallback) {
  68365. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68366. }
  68367. // Wait for textures and shaders to be ready
  68368. _this._currentScene.executeWhenReady(function () {
  68369. _this._engine.runRenderLoop(function () {
  68370. _this.renderFunction();
  68371. });
  68372. });
  68373. }).catch(function (error) {
  68374. if (_this._errorCallback) {
  68375. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68376. }
  68377. });
  68378. }
  68379. else {
  68380. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68381. }
  68382. };
  68383. FilesInput.FilesToLoad = {};
  68384. return FilesInput;
  68385. }());
  68386. BABYLON.FilesInput = FilesInput;
  68387. })(BABYLON || (BABYLON = {}));
  68388. //# sourceMappingURL=babylon.filesInput.js.map
  68389. var BABYLON;
  68390. (function (BABYLON) {
  68391. /**
  68392. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68393. * The underlying implementation relies on an associative array to ensure the best performances.
  68394. * The value can be anything including 'null' but except 'undefined'
  68395. */
  68396. var StringDictionary = /** @class */ (function () {
  68397. function StringDictionary() {
  68398. this._count = 0;
  68399. this._data = {};
  68400. }
  68401. /**
  68402. * This will clear this dictionary and copy the content from the 'source' one.
  68403. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68404. * @param source the dictionary to take the content from and copy to this dictionary
  68405. */
  68406. StringDictionary.prototype.copyFrom = function (source) {
  68407. var _this = this;
  68408. this.clear();
  68409. source.forEach(function (t, v) { return _this.add(t, v); });
  68410. };
  68411. /**
  68412. * Get a value based from its key
  68413. * @param key the given key to get the matching value from
  68414. * @return the value if found, otherwise undefined is returned
  68415. */
  68416. StringDictionary.prototype.get = function (key) {
  68417. var val = this._data[key];
  68418. if (val !== undefined) {
  68419. return val;
  68420. }
  68421. return undefined;
  68422. };
  68423. /**
  68424. * Get a value from its key or add it if it doesn't exist.
  68425. * This method will ensure you that a given key/data will be present in the dictionary.
  68426. * @param key the given key to get the matching value from
  68427. * @param factory the factory that will create the value if the key is not present in the dictionary.
  68428. * The factory will only be invoked if there's no data for the given key.
  68429. * @return the value corresponding to the key.
  68430. */
  68431. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  68432. var val = this.get(key);
  68433. if (val !== undefined) {
  68434. return val;
  68435. }
  68436. val = factory(key);
  68437. if (val) {
  68438. this.add(key, val);
  68439. }
  68440. return val;
  68441. };
  68442. /**
  68443. * Get a value from its key if present in the dictionary otherwise add it
  68444. * @param key the key to get the value from
  68445. * @param val if there's no such key/value pair in the dictionary add it with this value
  68446. * @return the value corresponding to the key
  68447. */
  68448. StringDictionary.prototype.getOrAdd = function (key, val) {
  68449. var curVal = this.get(key);
  68450. if (curVal !== undefined) {
  68451. return curVal;
  68452. }
  68453. this.add(key, val);
  68454. return val;
  68455. };
  68456. /**
  68457. * Check if there's a given key in the dictionary
  68458. * @param key the key to check for
  68459. * @return true if the key is present, false otherwise
  68460. */
  68461. StringDictionary.prototype.contains = function (key) {
  68462. return this._data[key] !== undefined;
  68463. };
  68464. /**
  68465. * Add a new key and its corresponding value
  68466. * @param key the key to add
  68467. * @param value the value corresponding to the key
  68468. * @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
  68469. */
  68470. StringDictionary.prototype.add = function (key, value) {
  68471. if (this._data[key] !== undefined) {
  68472. return false;
  68473. }
  68474. this._data[key] = value;
  68475. ++this._count;
  68476. return true;
  68477. };
  68478. StringDictionary.prototype.set = function (key, value) {
  68479. if (this._data[key] === undefined) {
  68480. return false;
  68481. }
  68482. this._data[key] = value;
  68483. return true;
  68484. };
  68485. /**
  68486. * Get the element of the given key and remove it from the dictionary
  68487. * @param key
  68488. */
  68489. StringDictionary.prototype.getAndRemove = function (key) {
  68490. var val = this.get(key);
  68491. if (val !== undefined) {
  68492. delete this._data[key];
  68493. --this._count;
  68494. return val;
  68495. }
  68496. return null;
  68497. };
  68498. /**
  68499. * Remove a key/value from the dictionary.
  68500. * @param key the key to remove
  68501. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  68502. */
  68503. StringDictionary.prototype.remove = function (key) {
  68504. if (this.contains(key)) {
  68505. delete this._data[key];
  68506. --this._count;
  68507. return true;
  68508. }
  68509. return false;
  68510. };
  68511. /**
  68512. * Clear the whole content of the dictionary
  68513. */
  68514. StringDictionary.prototype.clear = function () {
  68515. this._data = {};
  68516. this._count = 0;
  68517. };
  68518. Object.defineProperty(StringDictionary.prototype, "count", {
  68519. get: function () {
  68520. return this._count;
  68521. },
  68522. enumerable: true,
  68523. configurable: true
  68524. });
  68525. /**
  68526. * Execute a callback on each key/val of the dictionary.
  68527. * Note that you can remove any element in this dictionary in the callback implementation
  68528. * @param callback the callback to execute on a given key/value pair
  68529. */
  68530. StringDictionary.prototype.forEach = function (callback) {
  68531. for (var cur in this._data) {
  68532. var val = this._data[cur];
  68533. callback(cur, val);
  68534. }
  68535. };
  68536. /**
  68537. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  68538. * If the callback returns null or undefined the method will iterate to the next key/value pair
  68539. * Note that you can remove any element in this dictionary in the callback implementation
  68540. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  68541. */
  68542. StringDictionary.prototype.first = function (callback) {
  68543. for (var cur in this._data) {
  68544. var val = this._data[cur];
  68545. var res = callback(cur, val);
  68546. if (res) {
  68547. return res;
  68548. }
  68549. }
  68550. return null;
  68551. };
  68552. return StringDictionary;
  68553. }());
  68554. BABYLON.StringDictionary = StringDictionary;
  68555. })(BABYLON || (BABYLON = {}));
  68556. //# sourceMappingURL=babylon.stringDictionary.js.map
  68557. var BABYLON;
  68558. (function (BABYLON) {
  68559. var Tags = /** @class */ (function () {
  68560. function Tags() {
  68561. }
  68562. Tags.EnableFor = function (obj) {
  68563. obj._tags = obj._tags || {};
  68564. obj.hasTags = function () {
  68565. return Tags.HasTags(obj);
  68566. };
  68567. obj.addTags = function (tagsString) {
  68568. return Tags.AddTagsTo(obj, tagsString);
  68569. };
  68570. obj.removeTags = function (tagsString) {
  68571. return Tags.RemoveTagsFrom(obj, tagsString);
  68572. };
  68573. obj.matchesTagsQuery = function (tagsQuery) {
  68574. return Tags.MatchesQuery(obj, tagsQuery);
  68575. };
  68576. };
  68577. Tags.DisableFor = function (obj) {
  68578. delete obj._tags;
  68579. delete obj.hasTags;
  68580. delete obj.addTags;
  68581. delete obj.removeTags;
  68582. delete obj.matchesTagsQuery;
  68583. };
  68584. Tags.HasTags = function (obj) {
  68585. if (!obj._tags) {
  68586. return false;
  68587. }
  68588. return !BABYLON.Tools.IsEmpty(obj._tags);
  68589. };
  68590. Tags.GetTags = function (obj, asString) {
  68591. if (asString === void 0) { asString = true; }
  68592. if (!obj._tags) {
  68593. return null;
  68594. }
  68595. if (asString) {
  68596. var tagsArray = [];
  68597. for (var tag in obj._tags) {
  68598. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  68599. tagsArray.push(tag);
  68600. }
  68601. }
  68602. return tagsArray.join(" ");
  68603. }
  68604. else {
  68605. return obj._tags;
  68606. }
  68607. };
  68608. // the tags 'true' and 'false' are reserved and cannot be used as tags
  68609. // a tag cannot start with '||', '&&', and '!'
  68610. // it cannot contain whitespaces
  68611. Tags.AddTagsTo = function (obj, tagsString) {
  68612. if (!tagsString) {
  68613. return;
  68614. }
  68615. if (typeof tagsString !== "string") {
  68616. return;
  68617. }
  68618. var tags = tagsString.split(" ");
  68619. tags.forEach(function (tag, index, array) {
  68620. Tags._AddTagTo(obj, tag);
  68621. });
  68622. };
  68623. Tags._AddTagTo = function (obj, tag) {
  68624. tag = tag.trim();
  68625. if (tag === "" || tag === "true" || tag === "false") {
  68626. return;
  68627. }
  68628. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  68629. return;
  68630. }
  68631. Tags.EnableFor(obj);
  68632. obj._tags[tag] = true;
  68633. };
  68634. Tags.RemoveTagsFrom = function (obj, tagsString) {
  68635. if (!Tags.HasTags(obj)) {
  68636. return;
  68637. }
  68638. var tags = tagsString.split(" ");
  68639. for (var t in tags) {
  68640. Tags._RemoveTagFrom(obj, tags[t]);
  68641. }
  68642. };
  68643. Tags._RemoveTagFrom = function (obj, tag) {
  68644. delete obj._tags[tag];
  68645. };
  68646. Tags.MatchesQuery = function (obj, tagsQuery) {
  68647. if (tagsQuery === undefined) {
  68648. return true;
  68649. }
  68650. if (tagsQuery === "") {
  68651. return Tags.HasTags(obj);
  68652. }
  68653. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  68654. };
  68655. return Tags;
  68656. }());
  68657. BABYLON.Tags = Tags;
  68658. })(BABYLON || (BABYLON = {}));
  68659. //# sourceMappingURL=babylon.tags.js.map
  68660. var BABYLON;
  68661. (function (BABYLON) {
  68662. /**
  68663. * Class used to evalaute queries containing `and` and `or` operators
  68664. */
  68665. var AndOrNotEvaluator = /** @class */ (function () {
  68666. function AndOrNotEvaluator() {
  68667. }
  68668. /**
  68669. * Evaluate a query
  68670. * @param query defines the query to evaluate
  68671. * @param evaluateCallback defines the callback used to filter result
  68672. * @returns true if the query matches
  68673. */
  68674. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  68675. if (!query.match(/\([^\(\)]*\)/g)) {
  68676. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  68677. }
  68678. else {
  68679. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  68680. // remove parenthesis
  68681. r = r.slice(1, r.length - 1);
  68682. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  68683. });
  68684. }
  68685. if (query === "true") {
  68686. return true;
  68687. }
  68688. if (query === "false") {
  68689. return false;
  68690. }
  68691. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  68692. };
  68693. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  68694. evaluateCallback = evaluateCallback || (function (r) {
  68695. return r === "true" ? true : false;
  68696. });
  68697. var result;
  68698. var or = parenthesisContent.split("||");
  68699. for (var i in or) {
  68700. if (or.hasOwnProperty(i)) {
  68701. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  68702. var and = ori.split("&&");
  68703. if (and.length > 1) {
  68704. for (var j = 0; j < and.length; ++j) {
  68705. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  68706. if (andj !== "true" && andj !== "false") {
  68707. if (andj[0] === "!") {
  68708. result = !evaluateCallback(andj.substring(1));
  68709. }
  68710. else {
  68711. result = evaluateCallback(andj);
  68712. }
  68713. }
  68714. else {
  68715. result = andj === "true" ? true : false;
  68716. }
  68717. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  68718. ori = "false";
  68719. break;
  68720. }
  68721. }
  68722. }
  68723. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  68724. result = true;
  68725. break;
  68726. }
  68727. // result equals false (or undefined)
  68728. if (ori !== "true" && ori !== "false") {
  68729. if (ori[0] === "!") {
  68730. result = !evaluateCallback(ori.substring(1));
  68731. }
  68732. else {
  68733. result = evaluateCallback(ori);
  68734. }
  68735. }
  68736. else {
  68737. result = ori === "true" ? true : false;
  68738. }
  68739. }
  68740. }
  68741. // the whole parenthesis scope is replaced by 'true' or 'false'
  68742. return result ? "true" : "false";
  68743. };
  68744. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  68745. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  68746. // remove whitespaces
  68747. r = r.replace(/[\s]/g, function () { return ""; });
  68748. return r.length % 2 ? "!" : "";
  68749. });
  68750. booleanString = booleanString.trim();
  68751. if (booleanString === "!true") {
  68752. booleanString = "false";
  68753. }
  68754. else if (booleanString === "!false") {
  68755. booleanString = "true";
  68756. }
  68757. return booleanString;
  68758. };
  68759. return AndOrNotEvaluator;
  68760. }());
  68761. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  68762. })(BABYLON || (BABYLON = {}));
  68763. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  68764. var BABYLON;
  68765. (function (BABYLON) {
  68766. /**
  68767. * Class used to enable access to IndexedDB
  68768. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  68769. */
  68770. var Database = /** @class */ (function () {
  68771. /**
  68772. * Creates a new Database
  68773. * @param urlToScene defines the url to load the scene
  68774. * @param callbackManifestChecked defines the callback to use when manifest is checked
  68775. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  68776. */
  68777. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  68778. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  68779. var _this = this;
  68780. // Handling various flavors of prefixed version of IndexedDB
  68781. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  68782. this.callbackManifestChecked = callbackManifestChecked;
  68783. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  68784. this.db = null;
  68785. this._enableSceneOffline = false;
  68786. this._enableTexturesOffline = false;
  68787. this.manifestVersionFound = 0;
  68788. this.mustUpdateRessources = false;
  68789. this.hasReachedQuota = false;
  68790. if (!Database.IDBStorageEnabled) {
  68791. this.callbackManifestChecked(true);
  68792. }
  68793. else {
  68794. if (disableManifestCheck) {
  68795. this._enableSceneOffline = true;
  68796. this._enableTexturesOffline = true;
  68797. this.manifestVersionFound = 1;
  68798. BABYLON.Tools.SetImmediate(function () {
  68799. _this.callbackManifestChecked(true);
  68800. });
  68801. }
  68802. else {
  68803. this._checkManifestFile();
  68804. }
  68805. }
  68806. }
  68807. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  68808. /**
  68809. * Gets a boolean indicating if scene must be saved in the database
  68810. */
  68811. get: function () {
  68812. return this._enableSceneOffline;
  68813. },
  68814. enumerable: true,
  68815. configurable: true
  68816. });
  68817. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  68818. /**
  68819. * Gets a boolean indicating if textures must be saved in the database
  68820. */
  68821. get: function () {
  68822. return this._enableTexturesOffline;
  68823. },
  68824. enumerable: true,
  68825. configurable: true
  68826. });
  68827. Database.prototype._checkManifestFile = function () {
  68828. var _this = this;
  68829. var noManifestFile = function () {
  68830. _this._enableSceneOffline = false;
  68831. _this._enableTexturesOffline = false;
  68832. _this.callbackManifestChecked(false);
  68833. };
  68834. var timeStampUsed = false;
  68835. var manifestURL = this.currentSceneUrl + ".manifest";
  68836. var xhr = new XMLHttpRequest();
  68837. if (navigator.onLine) {
  68838. // Adding a timestamp to by-pass browsers' cache
  68839. timeStampUsed = true;
  68840. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  68841. }
  68842. xhr.open("GET", manifestURL, true);
  68843. xhr.addEventListener("load", function () {
  68844. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  68845. try {
  68846. var manifestFile = JSON.parse(xhr.response);
  68847. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  68848. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  68849. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  68850. _this.manifestVersionFound = manifestFile.version;
  68851. }
  68852. if (_this.callbackManifestChecked) {
  68853. _this.callbackManifestChecked(true);
  68854. }
  68855. }
  68856. catch (ex) {
  68857. noManifestFile();
  68858. }
  68859. }
  68860. else {
  68861. noManifestFile();
  68862. }
  68863. }, false);
  68864. xhr.addEventListener("error", function (event) {
  68865. if (timeStampUsed) {
  68866. timeStampUsed = false;
  68867. // Let's retry without the timeStamp
  68868. // It could fail when coupled with HTML5 Offline API
  68869. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  68870. xhr.open("GET", retryManifestURL, true);
  68871. xhr.send();
  68872. }
  68873. else {
  68874. noManifestFile();
  68875. }
  68876. }, false);
  68877. try {
  68878. xhr.send();
  68879. }
  68880. catch (ex) {
  68881. BABYLON.Tools.Error("Error on XHR send request.");
  68882. this.callbackManifestChecked(false);
  68883. }
  68884. };
  68885. /**
  68886. * Open the database and make it available
  68887. * @param successCallback defines the callback to call on success
  68888. * @param errorCallback defines the callback to call on error
  68889. */
  68890. Database.prototype.openAsync = function (successCallback, errorCallback) {
  68891. var _this = this;
  68892. var handleError = function () {
  68893. _this.isSupported = false;
  68894. if (errorCallback)
  68895. errorCallback();
  68896. };
  68897. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  68898. // Your browser doesn't support IndexedDB
  68899. this.isSupported = false;
  68900. if (errorCallback)
  68901. errorCallback();
  68902. }
  68903. else {
  68904. // If the DB hasn't been opened or created yet
  68905. if (!this.db) {
  68906. this.hasReachedQuota = false;
  68907. this.isSupported = true;
  68908. var request = this.idbFactory.open("babylonjs", 1);
  68909. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  68910. request.onerror = function (event) {
  68911. handleError();
  68912. };
  68913. // executes when a version change transaction cannot complete due to other active transactions
  68914. request.onblocked = function (event) {
  68915. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  68916. handleError();
  68917. };
  68918. // DB has been opened successfully
  68919. request.onsuccess = function (event) {
  68920. _this.db = request.result;
  68921. successCallback();
  68922. };
  68923. // Initialization of the DB. Creating Scenes & Textures stores
  68924. request.onupgradeneeded = function (event) {
  68925. _this.db = (event.target).result;
  68926. if (_this.db) {
  68927. try {
  68928. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  68929. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  68930. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  68931. }
  68932. catch (ex) {
  68933. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  68934. handleError();
  68935. }
  68936. }
  68937. };
  68938. }
  68939. // DB has already been created and opened
  68940. else {
  68941. if (successCallback)
  68942. successCallback();
  68943. }
  68944. }
  68945. };
  68946. /**
  68947. * Loads an image from the database
  68948. * @param url defines the url to load from
  68949. * @param image defines the target DOM image
  68950. */
  68951. Database.prototype.loadImageFromDB = function (url, image) {
  68952. var _this = this;
  68953. var completeURL = Database._ReturnFullUrlLocation(url);
  68954. var saveAndLoadImage = function () {
  68955. if (!_this.hasReachedQuota && _this.db !== null) {
  68956. // the texture is not yet in the DB, let's try to save it
  68957. _this._saveImageIntoDBAsync(completeURL, image);
  68958. }
  68959. // If the texture is not in the DB and we've reached the DB quota limit
  68960. // let's load it directly from the web
  68961. else {
  68962. image.src = url;
  68963. }
  68964. };
  68965. if (!this.mustUpdateRessources) {
  68966. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  68967. }
  68968. // First time we're download the images or update requested in the manifest file by a version change
  68969. else {
  68970. saveAndLoadImage();
  68971. }
  68972. };
  68973. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  68974. if (this.isSupported && this.db !== null) {
  68975. var texture;
  68976. var transaction = this.db.transaction(["textures"]);
  68977. transaction.onabort = function (event) {
  68978. image.src = url;
  68979. };
  68980. transaction.oncomplete = function (event) {
  68981. var blobTextureURL;
  68982. if (texture) {
  68983. var URL = window.URL || window.webkitURL;
  68984. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  68985. image.onerror = function () {
  68986. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  68987. image.src = url;
  68988. };
  68989. image.src = blobTextureURL;
  68990. }
  68991. else {
  68992. notInDBCallback();
  68993. }
  68994. };
  68995. var getRequest = transaction.objectStore("textures").get(url);
  68996. getRequest.onsuccess = function (event) {
  68997. texture = (event.target).result;
  68998. };
  68999. getRequest.onerror = function (event) {
  69000. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69001. image.src = url;
  69002. };
  69003. }
  69004. else {
  69005. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69006. image.src = url;
  69007. }
  69008. };
  69009. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69010. var _this = this;
  69011. if (this.isSupported) {
  69012. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69013. var generateBlobUrl = function () {
  69014. var blobTextureURL;
  69015. if (blob) {
  69016. var URL = window.URL || window.webkitURL;
  69017. try {
  69018. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69019. }
  69020. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69021. catch (ex) {
  69022. blobTextureURL = URL.createObjectURL(blob);
  69023. }
  69024. }
  69025. if (blobTextureURL) {
  69026. image.src = blobTextureURL;
  69027. }
  69028. };
  69029. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69030. var xhr = new XMLHttpRequest(), blob;
  69031. xhr.open("GET", url, true);
  69032. xhr.responseType = "blob";
  69033. xhr.addEventListener("load", function () {
  69034. if (xhr.status === 200 && _this.db) {
  69035. // Blob as response (XHR2)
  69036. blob = xhr.response;
  69037. var transaction = _this.db.transaction(["textures"], "readwrite");
  69038. // the transaction could abort because of a QuotaExceededError error
  69039. transaction.onabort = function (event) {
  69040. try {
  69041. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69042. var srcElement = (event.srcElement || event.target);
  69043. var error = srcElement.error;
  69044. if (error && error.name === "QuotaExceededError") {
  69045. _this.hasReachedQuota = true;
  69046. }
  69047. }
  69048. catch (ex) { }
  69049. generateBlobUrl();
  69050. };
  69051. transaction.oncomplete = function (event) {
  69052. generateBlobUrl();
  69053. };
  69054. var newTexture = { textureUrl: url, data: blob };
  69055. try {
  69056. // Put the blob into the dabase
  69057. var addRequest = transaction.objectStore("textures").put(newTexture);
  69058. addRequest.onsuccess = function (event) {
  69059. };
  69060. addRequest.onerror = function (event) {
  69061. generateBlobUrl();
  69062. };
  69063. }
  69064. catch (ex) {
  69065. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69066. if (ex.code === 25) {
  69067. Database.IsUASupportingBlobStorage = false;
  69068. }
  69069. image.src = url;
  69070. }
  69071. }
  69072. else {
  69073. image.src = url;
  69074. }
  69075. }, false);
  69076. xhr.addEventListener("error", function (event) {
  69077. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69078. image.src = url;
  69079. }, false);
  69080. xhr.send();
  69081. }
  69082. else {
  69083. image.src = url;
  69084. }
  69085. }
  69086. else {
  69087. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69088. image.src = url;
  69089. }
  69090. };
  69091. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69092. var _this = this;
  69093. var updateVersion = function () {
  69094. // the version is not yet in the DB or we need to update it
  69095. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69096. };
  69097. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69098. };
  69099. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69100. var _this = this;
  69101. if (this.isSupported && this.db) {
  69102. var version;
  69103. try {
  69104. var transaction = this.db.transaction(["versions"]);
  69105. transaction.oncomplete = function (event) {
  69106. if (version) {
  69107. // If the version in the JSON file is different from the version in DB
  69108. if (_this.manifestVersionFound !== version.data) {
  69109. _this.mustUpdateRessources = true;
  69110. updateInDBCallback();
  69111. }
  69112. else {
  69113. callback(version.data);
  69114. }
  69115. }
  69116. // version was not found in DB
  69117. else {
  69118. _this.mustUpdateRessources = true;
  69119. updateInDBCallback();
  69120. }
  69121. };
  69122. transaction.onabort = function (event) {
  69123. callback(-1);
  69124. };
  69125. var getRequest = transaction.objectStore("versions").get(url);
  69126. getRequest.onsuccess = function (event) {
  69127. version = (event.target).result;
  69128. };
  69129. getRequest.onerror = function (event) {
  69130. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69131. callback(-1);
  69132. };
  69133. }
  69134. catch (ex) {
  69135. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69136. callback(-1);
  69137. }
  69138. }
  69139. else {
  69140. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69141. callback(-1);
  69142. }
  69143. };
  69144. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69145. var _this = this;
  69146. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69147. try {
  69148. // Open a transaction to the database
  69149. var transaction = this.db.transaction(["versions"], "readwrite");
  69150. // the transaction could abort because of a QuotaExceededError error
  69151. transaction.onabort = function (event) {
  69152. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69153. var error = event.srcElement['error'];
  69154. if (error && error.name === "QuotaExceededError") {
  69155. _this.hasReachedQuota = true;
  69156. }
  69157. }
  69158. catch (ex) { }
  69159. callback(-1);
  69160. };
  69161. transaction.oncomplete = function (event) {
  69162. callback(_this.manifestVersionFound);
  69163. };
  69164. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69165. // Put the scene into the database
  69166. var addRequest = transaction.objectStore("versions").put(newVersion);
  69167. addRequest.onsuccess = function (event) {
  69168. };
  69169. addRequest.onerror = function (event) {
  69170. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69171. };
  69172. }
  69173. catch (ex) {
  69174. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69175. callback(-1);
  69176. }
  69177. }
  69178. else {
  69179. callback(-1);
  69180. }
  69181. };
  69182. /**
  69183. * Loads a file from database
  69184. * @param url defines the URL to load from
  69185. * @param sceneLoaded defines a callback to call on success
  69186. * @param progressCallBack defines a callback to call when progress changed
  69187. * @param errorCallback defines a callback to call on error
  69188. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69189. */
  69190. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69191. var _this = this;
  69192. var completeUrl = Database._ReturnFullUrlLocation(url);
  69193. var saveAndLoadFile = function () {
  69194. // the scene is not yet in the DB, let's try to save it
  69195. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69196. };
  69197. this._checkVersionFromDB(completeUrl, function (version) {
  69198. if (version !== -1) {
  69199. if (!_this.mustUpdateRessources) {
  69200. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69201. }
  69202. else {
  69203. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69204. }
  69205. }
  69206. else {
  69207. if (errorCallback) {
  69208. errorCallback();
  69209. }
  69210. }
  69211. });
  69212. };
  69213. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69214. if (this.isSupported && this.db) {
  69215. var targetStore;
  69216. if (url.indexOf(".babylon") !== -1) {
  69217. targetStore = "scenes";
  69218. }
  69219. else {
  69220. targetStore = "textures";
  69221. }
  69222. var file;
  69223. var transaction = this.db.transaction([targetStore]);
  69224. transaction.oncomplete = function (event) {
  69225. if (file) {
  69226. callback(file.data);
  69227. }
  69228. // file was not found in DB
  69229. else {
  69230. notInDBCallback();
  69231. }
  69232. };
  69233. transaction.onabort = function (event) {
  69234. notInDBCallback();
  69235. };
  69236. var getRequest = transaction.objectStore(targetStore).get(url);
  69237. getRequest.onsuccess = function (event) {
  69238. file = (event.target).result;
  69239. };
  69240. getRequest.onerror = function (event) {
  69241. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69242. notInDBCallback();
  69243. };
  69244. }
  69245. else {
  69246. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69247. callback();
  69248. }
  69249. };
  69250. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69251. var _this = this;
  69252. if (this.isSupported) {
  69253. var targetStore;
  69254. if (url.indexOf(".babylon") !== -1) {
  69255. targetStore = "scenes";
  69256. }
  69257. else {
  69258. targetStore = "textures";
  69259. }
  69260. // Create XHR
  69261. var xhr = new XMLHttpRequest();
  69262. var fileData;
  69263. xhr.open("GET", url, true);
  69264. if (useArrayBuffer) {
  69265. xhr.responseType = "arraybuffer";
  69266. }
  69267. if (progressCallback) {
  69268. xhr.onprogress = progressCallback;
  69269. }
  69270. xhr.addEventListener("load", function () {
  69271. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69272. // Blob as response (XHR2)
  69273. //fileData = xhr.responseText;
  69274. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69275. if (!_this.hasReachedQuota && _this.db) {
  69276. // Open a transaction to the database
  69277. var transaction = _this.db.transaction([targetStore], "readwrite");
  69278. // the transaction could abort because of a QuotaExceededError error
  69279. transaction.onabort = function (event) {
  69280. try {
  69281. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69282. var error = event.srcElement['error'];
  69283. if (error && error.name === "QuotaExceededError") {
  69284. _this.hasReachedQuota = true;
  69285. }
  69286. }
  69287. catch (ex) { }
  69288. callback(fileData);
  69289. };
  69290. transaction.oncomplete = function (event) {
  69291. callback(fileData);
  69292. };
  69293. var newFile;
  69294. if (targetStore === "scenes") {
  69295. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69296. }
  69297. else {
  69298. newFile = { textureUrl: url, data: fileData };
  69299. }
  69300. try {
  69301. // Put the scene into the database
  69302. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69303. addRequest.onsuccess = function (event) {
  69304. };
  69305. addRequest.onerror = function (event) {
  69306. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69307. };
  69308. }
  69309. catch (ex) {
  69310. callback(fileData);
  69311. }
  69312. }
  69313. else {
  69314. callback(fileData);
  69315. }
  69316. }
  69317. else {
  69318. callback();
  69319. }
  69320. }, false);
  69321. xhr.addEventListener("error", function (event) {
  69322. BABYLON.Tools.Error("error on XHR request.");
  69323. callback();
  69324. }, false);
  69325. xhr.send();
  69326. }
  69327. else {
  69328. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69329. callback();
  69330. }
  69331. };
  69332. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69333. Database.IsUASupportingBlobStorage = true;
  69334. /** Gets a boolean indicating if Database storate is enabled */
  69335. Database.IDBStorageEnabled = true;
  69336. Database._ParseURL = function (url) {
  69337. var a = document.createElement('a');
  69338. a.href = url;
  69339. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69340. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69341. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69342. return absLocation;
  69343. };
  69344. Database._ReturnFullUrlLocation = function (url) {
  69345. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69346. return (Database._ParseURL(window.location.href) + url);
  69347. }
  69348. else {
  69349. return url;
  69350. }
  69351. };
  69352. return Database;
  69353. }());
  69354. BABYLON.Database = Database;
  69355. })(BABYLON || (BABYLON = {}));
  69356. //# sourceMappingURL=babylon.database.js.map
  69357. var BABYLON;
  69358. (function (BABYLON) {
  69359. var FresnelParameters = /** @class */ (function () {
  69360. function FresnelParameters() {
  69361. this._isEnabled = true;
  69362. this.leftColor = BABYLON.Color3.White();
  69363. this.rightColor = BABYLON.Color3.Black();
  69364. this.bias = 0;
  69365. this.power = 1;
  69366. }
  69367. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69368. get: function () {
  69369. return this._isEnabled;
  69370. },
  69371. set: function (value) {
  69372. if (this._isEnabled === value) {
  69373. return;
  69374. }
  69375. this._isEnabled = value;
  69376. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69377. },
  69378. enumerable: true,
  69379. configurable: true
  69380. });
  69381. FresnelParameters.prototype.clone = function () {
  69382. var newFresnelParameters = new FresnelParameters();
  69383. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69384. return newFresnelParameters;
  69385. };
  69386. FresnelParameters.prototype.serialize = function () {
  69387. var serializationObject = {};
  69388. serializationObject.isEnabled = this.isEnabled;
  69389. serializationObject.leftColor = this.leftColor.asArray();
  69390. serializationObject.rightColor = this.rightColor.asArray();
  69391. serializationObject.bias = this.bias;
  69392. serializationObject.power = this.power;
  69393. return serializationObject;
  69394. };
  69395. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69396. var fresnelParameters = new FresnelParameters();
  69397. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69398. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69399. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69400. fresnelParameters.bias = parsedFresnelParameters.bias;
  69401. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69402. return fresnelParameters;
  69403. };
  69404. return FresnelParameters;
  69405. }());
  69406. BABYLON.FresnelParameters = FresnelParameters;
  69407. })(BABYLON || (BABYLON = {}));
  69408. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69409. var BABYLON;
  69410. (function (BABYLON) {
  69411. var MultiMaterial = /** @class */ (function (_super) {
  69412. __extends(MultiMaterial, _super);
  69413. function MultiMaterial(name, scene) {
  69414. var _this = _super.call(this, name, scene, true) || this;
  69415. scene.multiMaterials.push(_this);
  69416. _this.subMaterials = new Array();
  69417. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  69418. return _this;
  69419. }
  69420. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  69421. get: function () {
  69422. return this._subMaterials;
  69423. },
  69424. set: function (value) {
  69425. this._subMaterials = value;
  69426. this._hookArray(value);
  69427. },
  69428. enumerable: true,
  69429. configurable: true
  69430. });
  69431. MultiMaterial.prototype._hookArray = function (array) {
  69432. var _this = this;
  69433. var oldPush = array.push;
  69434. array.push = function () {
  69435. var items = [];
  69436. for (var _i = 0; _i < arguments.length; _i++) {
  69437. items[_i] = arguments[_i];
  69438. }
  69439. var result = oldPush.apply(array, items);
  69440. _this._markAllSubMeshesAsTexturesDirty();
  69441. return result;
  69442. };
  69443. var oldSplice = array.splice;
  69444. array.splice = function (index, deleteCount) {
  69445. var deleted = oldSplice.apply(array, [index, deleteCount]);
  69446. _this._markAllSubMeshesAsTexturesDirty();
  69447. return deleted;
  69448. };
  69449. };
  69450. // Properties
  69451. MultiMaterial.prototype.getSubMaterial = function (index) {
  69452. if (index < 0 || index >= this.subMaterials.length) {
  69453. return this.getScene().defaultMaterial;
  69454. }
  69455. return this.subMaterials[index];
  69456. };
  69457. MultiMaterial.prototype.getActiveTextures = function () {
  69458. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  69459. if (subMaterial) {
  69460. return subMaterial.getActiveTextures();
  69461. }
  69462. else {
  69463. return [];
  69464. }
  69465. }));
  69466. var _a;
  69467. };
  69468. // Methods
  69469. MultiMaterial.prototype.getClassName = function () {
  69470. return "MultiMaterial";
  69471. };
  69472. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  69473. for (var index = 0; index < this.subMaterials.length; index++) {
  69474. var subMaterial = this.subMaterials[index];
  69475. if (subMaterial) {
  69476. if (subMaterial.storeEffectOnSubMeshes) {
  69477. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  69478. return false;
  69479. }
  69480. continue;
  69481. }
  69482. if (!subMaterial.isReady(mesh)) {
  69483. return false;
  69484. }
  69485. }
  69486. }
  69487. return true;
  69488. };
  69489. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  69490. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  69491. for (var index = 0; index < this.subMaterials.length; index++) {
  69492. var subMaterial = null;
  69493. var current = this.subMaterials[index];
  69494. if (cloneChildren && current) {
  69495. subMaterial = current.clone(name + "-" + current.name);
  69496. }
  69497. else {
  69498. subMaterial = this.subMaterials[index];
  69499. }
  69500. newMultiMaterial.subMaterials.push(subMaterial);
  69501. }
  69502. return newMultiMaterial;
  69503. };
  69504. MultiMaterial.prototype.serialize = function () {
  69505. var serializationObject = {};
  69506. serializationObject.name = this.name;
  69507. serializationObject.id = this.id;
  69508. if (BABYLON.Tags) {
  69509. serializationObject.tags = BABYLON.Tags.GetTags(this);
  69510. }
  69511. serializationObject.materials = [];
  69512. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  69513. var subMat = this.subMaterials[matIndex];
  69514. if (subMat) {
  69515. serializationObject.materials.push(subMat.id);
  69516. }
  69517. else {
  69518. serializationObject.materials.push(null);
  69519. }
  69520. }
  69521. return serializationObject;
  69522. };
  69523. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  69524. var scene = this.getScene();
  69525. if (!scene) {
  69526. return;
  69527. }
  69528. var index = scene.multiMaterials.indexOf(this);
  69529. if (index >= 0) {
  69530. scene.multiMaterials.splice(index, 1);
  69531. }
  69532. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  69533. };
  69534. return MultiMaterial;
  69535. }(BABYLON.Material));
  69536. BABYLON.MultiMaterial = MultiMaterial;
  69537. })(BABYLON || (BABYLON = {}));
  69538. //# sourceMappingURL=babylon.multiMaterial.js.map
  69539. var BABYLON;
  69540. (function (BABYLON) {
  69541. var FreeCameraTouchInput = /** @class */ (function () {
  69542. function FreeCameraTouchInput() {
  69543. this._offsetX = null;
  69544. this._offsetY = null;
  69545. this._pointerPressed = new Array();
  69546. this.touchAngularSensibility = 200000.0;
  69547. this.touchMoveSensibility = 250.0;
  69548. }
  69549. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  69550. var _this = this;
  69551. var previousPosition = null;
  69552. if (this._pointerInput === undefined) {
  69553. this._onLostFocus = function (evt) {
  69554. _this._offsetX = null;
  69555. _this._offsetY = null;
  69556. };
  69557. this._pointerInput = function (p, s) {
  69558. var evt = p.event;
  69559. if (evt.pointerType === "mouse") {
  69560. return;
  69561. }
  69562. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  69563. if (!noPreventDefault) {
  69564. evt.preventDefault();
  69565. }
  69566. _this._pointerPressed.push(evt.pointerId);
  69567. if (_this._pointerPressed.length !== 1) {
  69568. return;
  69569. }
  69570. previousPosition = {
  69571. x: evt.clientX,
  69572. y: evt.clientY
  69573. };
  69574. }
  69575. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  69576. if (!noPreventDefault) {
  69577. evt.preventDefault();
  69578. }
  69579. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69580. if (index === -1) {
  69581. return;
  69582. }
  69583. _this._pointerPressed.splice(index, 1);
  69584. if (index != 0) {
  69585. return;
  69586. }
  69587. previousPosition = null;
  69588. _this._offsetX = null;
  69589. _this._offsetY = null;
  69590. }
  69591. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  69592. if (!noPreventDefault) {
  69593. evt.preventDefault();
  69594. }
  69595. if (!previousPosition) {
  69596. return;
  69597. }
  69598. var index = _this._pointerPressed.indexOf(evt.pointerId);
  69599. if (index != 0) {
  69600. return;
  69601. }
  69602. _this._offsetX = evt.clientX - previousPosition.x;
  69603. _this._offsetY = -(evt.clientY - previousPosition.y);
  69604. }
  69605. };
  69606. }
  69607. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  69608. if (this._onLostFocus) {
  69609. element.addEventListener("blur", this._onLostFocus);
  69610. }
  69611. };
  69612. FreeCameraTouchInput.prototype.detachControl = function (element) {
  69613. if (this._pointerInput && element) {
  69614. if (this._observer) {
  69615. this.camera.getScene().onPointerObservable.remove(this._observer);
  69616. this._observer = null;
  69617. }
  69618. if (this._onLostFocus) {
  69619. element.removeEventListener("blur", this._onLostFocus);
  69620. this._onLostFocus = null;
  69621. }
  69622. this._pointerPressed = [];
  69623. this._offsetX = null;
  69624. this._offsetY = null;
  69625. }
  69626. };
  69627. FreeCameraTouchInput.prototype.checkInputs = function () {
  69628. if (this._offsetX && this._offsetY) {
  69629. var camera = this.camera;
  69630. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  69631. if (this._pointerPressed.length > 1) {
  69632. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  69633. }
  69634. else {
  69635. var speed = camera._computeLocalCameraSpeed();
  69636. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  69637. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  69638. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  69639. }
  69640. }
  69641. };
  69642. FreeCameraTouchInput.prototype.getClassName = function () {
  69643. return "FreeCameraTouchInput";
  69644. };
  69645. FreeCameraTouchInput.prototype.getSimpleName = function () {
  69646. return "touch";
  69647. };
  69648. __decorate([
  69649. BABYLON.serialize()
  69650. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  69651. __decorate([
  69652. BABYLON.serialize()
  69653. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  69654. return FreeCameraTouchInput;
  69655. }());
  69656. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  69657. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  69658. })(BABYLON || (BABYLON = {}));
  69659. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  69660. var BABYLON;
  69661. (function (BABYLON) {
  69662. // We're mainly based on the logic defined into the FreeCamera code
  69663. var TouchCamera = /** @class */ (function (_super) {
  69664. __extends(TouchCamera, _super);
  69665. //-- end properties for backward compatibility for inputs
  69666. function TouchCamera(name, position, scene) {
  69667. var _this = _super.call(this, name, position, scene) || this;
  69668. _this.inputs.addTouch();
  69669. _this._setupInputs();
  69670. return _this;
  69671. }
  69672. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  69673. //-- Begin properties for backward compatibility for inputs
  69674. get: function () {
  69675. var touch = this.inputs.attached["touch"];
  69676. if (touch)
  69677. return touch.touchAngularSensibility;
  69678. return 0;
  69679. },
  69680. set: function (value) {
  69681. var touch = this.inputs.attached["touch"];
  69682. if (touch)
  69683. touch.touchAngularSensibility = value;
  69684. },
  69685. enumerable: true,
  69686. configurable: true
  69687. });
  69688. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  69689. get: function () {
  69690. var touch = this.inputs.attached["touch"];
  69691. if (touch)
  69692. return touch.touchMoveSensibility;
  69693. return 0;
  69694. },
  69695. set: function (value) {
  69696. var touch = this.inputs.attached["touch"];
  69697. if (touch)
  69698. touch.touchMoveSensibility = value;
  69699. },
  69700. enumerable: true,
  69701. configurable: true
  69702. });
  69703. TouchCamera.prototype.getClassName = function () {
  69704. return "TouchCamera";
  69705. };
  69706. TouchCamera.prototype._setupInputs = function () {
  69707. var mouse = this.inputs.attached["mouse"];
  69708. if (mouse) {
  69709. mouse.touchEnabled = false;
  69710. }
  69711. };
  69712. return TouchCamera;
  69713. }(BABYLON.FreeCamera));
  69714. BABYLON.TouchCamera = TouchCamera;
  69715. })(BABYLON || (BABYLON = {}));
  69716. //# sourceMappingURL=babylon.touchCamera.js.map
  69717. var BABYLON;
  69718. (function (BABYLON) {
  69719. var ProceduralTexture = /** @class */ (function (_super) {
  69720. __extends(ProceduralTexture, _super);
  69721. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  69722. if (fallbackTexture === void 0) { fallbackTexture = null; }
  69723. if (generateMipMaps === void 0) { generateMipMaps = true; }
  69724. if (isCube === void 0) { isCube = false; }
  69725. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  69726. _this.isCube = isCube;
  69727. _this.isEnabled = true;
  69728. _this._currentRefreshId = -1;
  69729. _this._refreshRate = 1;
  69730. _this._vertexBuffers = {};
  69731. _this._uniforms = new Array();
  69732. _this._samplers = new Array();
  69733. _this._textures = {};
  69734. _this._floats = {};
  69735. _this._floatsArrays = {};
  69736. _this._colors3 = {};
  69737. _this._colors4 = {};
  69738. _this._vectors2 = {};
  69739. _this._vectors3 = {};
  69740. _this._matrices = {};
  69741. _this._fallbackTextureUsed = false;
  69742. scene.proceduralTextures.push(_this);
  69743. _this._engine = scene.getEngine();
  69744. _this.name = name;
  69745. _this.isRenderTarget = true;
  69746. _this._size = size;
  69747. _this._generateMipMaps = generateMipMaps;
  69748. _this.setFragment(fragment);
  69749. _this._fallbackTexture = fallbackTexture;
  69750. if (isCube) {
  69751. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  69752. _this.setFloat("face", 0);
  69753. }
  69754. else {
  69755. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  69756. }
  69757. // VBO
  69758. var vertices = [];
  69759. vertices.push(1, 1);
  69760. vertices.push(-1, 1);
  69761. vertices.push(-1, -1);
  69762. vertices.push(1, -1);
  69763. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  69764. _this._createIndexBuffer();
  69765. return _this;
  69766. }
  69767. ProceduralTexture.prototype._createIndexBuffer = function () {
  69768. var engine = this._engine;
  69769. // Indices
  69770. var indices = [];
  69771. indices.push(0);
  69772. indices.push(1);
  69773. indices.push(2);
  69774. indices.push(0);
  69775. indices.push(2);
  69776. indices.push(3);
  69777. this._indexBuffer = engine.createIndexBuffer(indices);
  69778. };
  69779. ProceduralTexture.prototype._rebuild = function () {
  69780. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  69781. if (vb) {
  69782. vb._rebuild();
  69783. }
  69784. this._createIndexBuffer();
  69785. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  69786. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  69787. }
  69788. };
  69789. ProceduralTexture.prototype.reset = function () {
  69790. if (this._effect === undefined) {
  69791. return;
  69792. }
  69793. var engine = this._engine;
  69794. engine._releaseEffect(this._effect);
  69795. };
  69796. ProceduralTexture.prototype.isReady = function () {
  69797. var _this = this;
  69798. var engine = this._engine;
  69799. var shaders;
  69800. if (!this._fragment) {
  69801. return false;
  69802. }
  69803. if (this._fallbackTextureUsed) {
  69804. return true;
  69805. }
  69806. if (this._fragment.fragmentElement !== undefined) {
  69807. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  69808. }
  69809. else {
  69810. shaders = { vertex: "procedural", fragment: this._fragment };
  69811. }
  69812. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  69813. _this.releaseInternalTexture();
  69814. if (_this._fallbackTexture) {
  69815. _this._texture = _this._fallbackTexture._texture;
  69816. if (_this._texture) {
  69817. _this._texture.incrementReferences();
  69818. }
  69819. }
  69820. _this._fallbackTextureUsed = true;
  69821. });
  69822. return this._effect.isReady();
  69823. };
  69824. ProceduralTexture.prototype.resetRefreshCounter = function () {
  69825. this._currentRefreshId = -1;
  69826. };
  69827. ProceduralTexture.prototype.setFragment = function (fragment) {
  69828. this._fragment = fragment;
  69829. };
  69830. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  69831. get: function () {
  69832. return this._refreshRate;
  69833. },
  69834. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  69835. set: function (value) {
  69836. this._refreshRate = value;
  69837. this.resetRefreshCounter();
  69838. },
  69839. enumerable: true,
  69840. configurable: true
  69841. });
  69842. ProceduralTexture.prototype._shouldRender = function () {
  69843. if (!this.isEnabled || !this.isReady() || !this._texture) {
  69844. return false;
  69845. }
  69846. if (this._fallbackTextureUsed) {
  69847. return false;
  69848. }
  69849. if (this._currentRefreshId === -1) { // At least render once
  69850. this._currentRefreshId = 1;
  69851. return true;
  69852. }
  69853. if (this.refreshRate === this._currentRefreshId) {
  69854. this._currentRefreshId = 1;
  69855. return true;
  69856. }
  69857. this._currentRefreshId++;
  69858. return false;
  69859. };
  69860. ProceduralTexture.prototype.getRenderSize = function () {
  69861. return this._size;
  69862. };
  69863. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  69864. if (this._fallbackTextureUsed) {
  69865. return;
  69866. }
  69867. this.releaseInternalTexture();
  69868. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  69869. };
  69870. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  69871. if (this._uniforms.indexOf(uniformName) === -1) {
  69872. this._uniforms.push(uniformName);
  69873. }
  69874. };
  69875. ProceduralTexture.prototype.setTexture = function (name, texture) {
  69876. if (this._samplers.indexOf(name) === -1) {
  69877. this._samplers.push(name);
  69878. }
  69879. this._textures[name] = texture;
  69880. return this;
  69881. };
  69882. ProceduralTexture.prototype.setFloat = function (name, value) {
  69883. this._checkUniform(name);
  69884. this._floats[name] = value;
  69885. return this;
  69886. };
  69887. ProceduralTexture.prototype.setFloats = function (name, value) {
  69888. this._checkUniform(name);
  69889. this._floatsArrays[name] = value;
  69890. return this;
  69891. };
  69892. ProceduralTexture.prototype.setColor3 = function (name, value) {
  69893. this._checkUniform(name);
  69894. this._colors3[name] = value;
  69895. return this;
  69896. };
  69897. ProceduralTexture.prototype.setColor4 = function (name, value) {
  69898. this._checkUniform(name);
  69899. this._colors4[name] = value;
  69900. return this;
  69901. };
  69902. ProceduralTexture.prototype.setVector2 = function (name, value) {
  69903. this._checkUniform(name);
  69904. this._vectors2[name] = value;
  69905. return this;
  69906. };
  69907. ProceduralTexture.prototype.setVector3 = function (name, value) {
  69908. this._checkUniform(name);
  69909. this._vectors3[name] = value;
  69910. return this;
  69911. };
  69912. ProceduralTexture.prototype.setMatrix = function (name, value) {
  69913. this._checkUniform(name);
  69914. this._matrices[name] = value;
  69915. return this;
  69916. };
  69917. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  69918. var scene = this.getScene();
  69919. if (!scene) {
  69920. return;
  69921. }
  69922. var engine = this._engine;
  69923. // Render
  69924. engine.enableEffect(this._effect);
  69925. engine.setState(false);
  69926. // Texture
  69927. for (var name in this._textures) {
  69928. this._effect.setTexture(name, this._textures[name]);
  69929. }
  69930. // Float
  69931. for (name in this._floats) {
  69932. this._effect.setFloat(name, this._floats[name]);
  69933. }
  69934. // Floats
  69935. for (name in this._floatsArrays) {
  69936. this._effect.setArray(name, this._floatsArrays[name]);
  69937. }
  69938. // Color3
  69939. for (name in this._colors3) {
  69940. this._effect.setColor3(name, this._colors3[name]);
  69941. }
  69942. // Color4
  69943. for (name in this._colors4) {
  69944. var color = this._colors4[name];
  69945. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  69946. }
  69947. // Vector2
  69948. for (name in this._vectors2) {
  69949. this._effect.setVector2(name, this._vectors2[name]);
  69950. }
  69951. // Vector3
  69952. for (name in this._vectors3) {
  69953. this._effect.setVector3(name, this._vectors3[name]);
  69954. }
  69955. // Matrix
  69956. for (name in this._matrices) {
  69957. this._effect.setMatrix(name, this._matrices[name]);
  69958. }
  69959. if (!this._texture) {
  69960. return;
  69961. }
  69962. if (this.isCube) {
  69963. for (var face = 0; face < 6; face++) {
  69964. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  69965. // VBOs
  69966. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69967. this._effect.setFloat("face", face);
  69968. // Clear
  69969. engine.clear(scene.clearColor, true, true, true);
  69970. // Draw order
  69971. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69972. // Mipmaps
  69973. if (face === 5) {
  69974. engine.generateMipMapsForCubemap(this._texture);
  69975. }
  69976. }
  69977. }
  69978. else {
  69979. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  69980. // VBOs
  69981. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  69982. // Clear
  69983. engine.clear(scene.clearColor, true, true, true);
  69984. // Draw order
  69985. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  69986. }
  69987. // Unbind
  69988. engine.unBindFramebuffer(this._texture, this.isCube);
  69989. if (this.onGenerated) {
  69990. this.onGenerated();
  69991. }
  69992. };
  69993. ProceduralTexture.prototype.clone = function () {
  69994. var textureSize = this.getSize();
  69995. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  69996. // Base texture
  69997. newTexture.hasAlpha = this.hasAlpha;
  69998. newTexture.level = this.level;
  69999. // RenderTarget Texture
  70000. newTexture.coordinatesMode = this.coordinatesMode;
  70001. return newTexture;
  70002. };
  70003. ProceduralTexture.prototype.dispose = function () {
  70004. var scene = this.getScene();
  70005. if (!scene) {
  70006. return;
  70007. }
  70008. var index = scene.proceduralTextures.indexOf(this);
  70009. if (index >= 0) {
  70010. scene.proceduralTextures.splice(index, 1);
  70011. }
  70012. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70013. if (vertexBuffer) {
  70014. vertexBuffer.dispose();
  70015. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70016. }
  70017. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70018. this._indexBuffer = null;
  70019. }
  70020. _super.prototype.dispose.call(this);
  70021. };
  70022. return ProceduralTexture;
  70023. }(BABYLON.Texture));
  70024. BABYLON.ProceduralTexture = ProceduralTexture;
  70025. })(BABYLON || (BABYLON = {}));
  70026. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70027. var BABYLON;
  70028. (function (BABYLON) {
  70029. var CustomProceduralTexture = /** @class */ (function (_super) {
  70030. __extends(CustomProceduralTexture, _super);
  70031. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70032. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70033. _this._animate = true;
  70034. _this._time = 0;
  70035. _this._texturePath = texturePath;
  70036. //Try to load json
  70037. _this.loadJson(texturePath);
  70038. _this.refreshRate = 1;
  70039. return _this;
  70040. }
  70041. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70042. var _this = this;
  70043. var noConfigFile = function () {
  70044. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70045. try {
  70046. _this.setFragment(_this._texturePath);
  70047. }
  70048. catch (ex) {
  70049. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70050. }
  70051. };
  70052. var configFileUrl = jsonUrl + "/config.json";
  70053. var xhr = new XMLHttpRequest();
  70054. xhr.open("GET", configFileUrl, true);
  70055. xhr.addEventListener("load", function () {
  70056. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70057. try {
  70058. _this._config = JSON.parse(xhr.response);
  70059. _this.updateShaderUniforms();
  70060. _this.updateTextures();
  70061. _this.setFragment(_this._texturePath + "/custom");
  70062. _this._animate = _this._config.animate;
  70063. _this.refreshRate = _this._config.refreshrate;
  70064. }
  70065. catch (ex) {
  70066. noConfigFile();
  70067. }
  70068. }
  70069. else {
  70070. noConfigFile();
  70071. }
  70072. }, false);
  70073. xhr.addEventListener("error", function () {
  70074. noConfigFile();
  70075. }, false);
  70076. try {
  70077. xhr.send();
  70078. }
  70079. catch (ex) {
  70080. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70081. }
  70082. };
  70083. CustomProceduralTexture.prototype.isReady = function () {
  70084. if (!_super.prototype.isReady.call(this)) {
  70085. return false;
  70086. }
  70087. for (var name in this._textures) {
  70088. var texture = this._textures[name];
  70089. if (!texture.isReady()) {
  70090. return false;
  70091. }
  70092. }
  70093. return true;
  70094. };
  70095. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70096. var scene = this.getScene();
  70097. if (this._animate && scene) {
  70098. this._time += scene.getAnimationRatio() * 0.03;
  70099. this.updateShaderUniforms();
  70100. }
  70101. _super.prototype.render.call(this, useCameraPostProcess);
  70102. };
  70103. CustomProceduralTexture.prototype.updateTextures = function () {
  70104. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70105. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70106. }
  70107. };
  70108. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70109. if (this._config) {
  70110. for (var j = 0; j < this._config.uniforms.length; j++) {
  70111. var uniform = this._config.uniforms[j];
  70112. switch (uniform.type) {
  70113. case "float":
  70114. this.setFloat(uniform.name, uniform.value);
  70115. break;
  70116. case "color3":
  70117. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70118. break;
  70119. case "color4":
  70120. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70121. break;
  70122. case "vector2":
  70123. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70124. break;
  70125. case "vector3":
  70126. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70127. break;
  70128. }
  70129. }
  70130. }
  70131. this.setFloat("time", this._time);
  70132. };
  70133. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70134. get: function () {
  70135. return this._animate;
  70136. },
  70137. set: function (value) {
  70138. this._animate = value;
  70139. },
  70140. enumerable: true,
  70141. configurable: true
  70142. });
  70143. return CustomProceduralTexture;
  70144. }(BABYLON.ProceduralTexture));
  70145. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70146. })(BABYLON || (BABYLON = {}));
  70147. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70148. var BABYLON;
  70149. (function (BABYLON) {
  70150. var FreeCameraGamepadInput = /** @class */ (function () {
  70151. function FreeCameraGamepadInput() {
  70152. this.gamepadAngularSensibility = 200;
  70153. this.gamepadMoveSensibility = 40;
  70154. // private members
  70155. this._cameraTransform = BABYLON.Matrix.Identity();
  70156. this._deltaTransform = BABYLON.Vector3.Zero();
  70157. this._vector3 = BABYLON.Vector3.Zero();
  70158. this._vector2 = BABYLON.Vector2.Zero();
  70159. }
  70160. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70161. var _this = this;
  70162. var manager = this.camera.getScene().gamepadManager;
  70163. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70164. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70165. // prioritize XBOX gamepads.
  70166. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70167. _this.gamepad = gamepad;
  70168. }
  70169. }
  70170. });
  70171. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70172. if (_this.gamepad === gamepad) {
  70173. _this.gamepad = null;
  70174. }
  70175. });
  70176. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70177. };
  70178. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70179. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70180. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70181. this.gamepad = null;
  70182. };
  70183. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70184. if (this.gamepad && this.gamepad.leftStick) {
  70185. var camera = this.camera;
  70186. var LSValues = this.gamepad.leftStick;
  70187. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70188. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70189. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70190. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70191. var RSValues = this.gamepad.rightStick;
  70192. if (RSValues) {
  70193. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70194. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70195. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70196. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70197. }
  70198. else {
  70199. RSValues = { x: 0, y: 0 };
  70200. }
  70201. if (!camera.rotationQuaternion) {
  70202. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70203. }
  70204. else {
  70205. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70206. }
  70207. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70208. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70209. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70210. camera.cameraDirection.addInPlace(this._deltaTransform);
  70211. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70212. camera.cameraRotation.addInPlace(this._vector2);
  70213. }
  70214. };
  70215. FreeCameraGamepadInput.prototype.getClassName = function () {
  70216. return "FreeCameraGamepadInput";
  70217. };
  70218. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70219. return "gamepad";
  70220. };
  70221. __decorate([
  70222. BABYLON.serialize()
  70223. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70224. __decorate([
  70225. BABYLON.serialize()
  70226. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70227. return FreeCameraGamepadInput;
  70228. }());
  70229. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70230. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70231. })(BABYLON || (BABYLON = {}));
  70232. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70233. var BABYLON;
  70234. (function (BABYLON) {
  70235. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70236. function ArcRotateCameraGamepadInput() {
  70237. this.gamepadRotationSensibility = 80;
  70238. this.gamepadMoveSensibility = 40;
  70239. }
  70240. ArcRotateCameraGamepadInput.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. ArcRotateCameraGamepadInput.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. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70264. if (this.gamepad) {
  70265. var camera = this.camera;
  70266. var RSValues = this.gamepad.rightStick;
  70267. if (RSValues) {
  70268. if (RSValues.x != 0) {
  70269. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70270. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70271. camera.inertialAlphaOffset += normalizedRX;
  70272. }
  70273. }
  70274. if (RSValues.y != 0) {
  70275. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70276. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70277. camera.inertialBetaOffset += normalizedRY;
  70278. }
  70279. }
  70280. }
  70281. var LSValues = this.gamepad.leftStick;
  70282. if (LSValues && LSValues.y != 0) {
  70283. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70284. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70285. this.camera.inertialRadiusOffset -= normalizedLY;
  70286. }
  70287. }
  70288. }
  70289. };
  70290. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70291. return "ArcRotateCameraGamepadInput";
  70292. };
  70293. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70294. return "gamepad";
  70295. };
  70296. __decorate([
  70297. BABYLON.serialize()
  70298. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70299. __decorate([
  70300. BABYLON.serialize()
  70301. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70302. return ArcRotateCameraGamepadInput;
  70303. }());
  70304. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70305. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70306. })(BABYLON || (BABYLON = {}));
  70307. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70308. var BABYLON;
  70309. (function (BABYLON) {
  70310. var GamepadManager = /** @class */ (function () {
  70311. function GamepadManager(_scene) {
  70312. var _this = this;
  70313. this._scene = _scene;
  70314. this._babylonGamepads = [];
  70315. this._oneGamepadConnected = false;
  70316. this._isMonitoring = false;
  70317. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70318. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70319. this._gamepadEventSupported = false;
  70320. }
  70321. else {
  70322. this._gamepadEventSupported = 'GamepadEvent' in window;
  70323. this._gamepadSupport = (navigator.getGamepads ||
  70324. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70325. }
  70326. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70327. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70328. for (var i in _this._babylonGamepads) {
  70329. var gamepad = _this._babylonGamepads[i];
  70330. if (gamepad && gamepad._isConnected) {
  70331. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70332. }
  70333. }
  70334. });
  70335. this._onGamepadConnectedEvent = function (evt) {
  70336. var gamepad = evt.gamepad;
  70337. if (gamepad.index in _this._babylonGamepads) {
  70338. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70339. return;
  70340. }
  70341. }
  70342. var newGamepad;
  70343. if (_this._babylonGamepads[gamepad.index]) {
  70344. newGamepad = _this._babylonGamepads[gamepad.index];
  70345. newGamepad.browserGamepad = gamepad;
  70346. newGamepad._isConnected = true;
  70347. }
  70348. else {
  70349. newGamepad = _this._addNewGamepad(gamepad);
  70350. }
  70351. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70352. _this._startMonitoringGamepads();
  70353. };
  70354. this._onGamepadDisconnectedEvent = function (evt) {
  70355. var gamepad = evt.gamepad;
  70356. // Remove the gamepad from the list of gamepads to monitor.
  70357. for (var i in _this._babylonGamepads) {
  70358. if (_this._babylonGamepads[i].index === gamepad.index) {
  70359. var disconnectedGamepad = _this._babylonGamepads[i];
  70360. disconnectedGamepad._isConnected = false;
  70361. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70362. break;
  70363. }
  70364. }
  70365. };
  70366. if (this._gamepadSupport) {
  70367. //first add already-connected gamepads
  70368. this._updateGamepadObjects();
  70369. if (this._babylonGamepads.length) {
  70370. this._startMonitoringGamepads();
  70371. }
  70372. // Checking if the gamepad connected event is supported (like in Firefox)
  70373. if (this._gamepadEventSupported) {
  70374. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70375. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70376. }
  70377. else {
  70378. this._startMonitoringGamepads();
  70379. }
  70380. }
  70381. }
  70382. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70383. get: function () {
  70384. return this._babylonGamepads;
  70385. },
  70386. enumerable: true,
  70387. configurable: true
  70388. });
  70389. GamepadManager.prototype.getGamepadByType = function (type) {
  70390. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70391. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70392. var gamepad = _a[_i];
  70393. if (gamepad && gamepad.type === type) {
  70394. return gamepad;
  70395. }
  70396. }
  70397. return null;
  70398. };
  70399. GamepadManager.prototype.dispose = function () {
  70400. if (this._gamepadEventSupported) {
  70401. if (this._onGamepadConnectedEvent) {
  70402. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  70403. }
  70404. if (this._onGamepadDisconnectedEvent) {
  70405. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  70406. }
  70407. this._onGamepadConnectedEvent = null;
  70408. this._onGamepadDisconnectedEvent = null;
  70409. }
  70410. this._babylonGamepads.forEach(function (gamepad) {
  70411. gamepad.dispose();
  70412. });
  70413. this.onGamepadConnectedObservable.clear();
  70414. this.onGamepadDisconnectedObservable.clear();
  70415. this._oneGamepadConnected = false;
  70416. this._stopMonitoringGamepads();
  70417. this._babylonGamepads = [];
  70418. };
  70419. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  70420. if (!this._oneGamepadConnected) {
  70421. this._oneGamepadConnected = true;
  70422. }
  70423. var newGamepad;
  70424. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  70425. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  70426. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  70427. }
  70428. // if pose is supported, use the (WebVR) pose enabled controller
  70429. else if (gamepad.pose) {
  70430. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  70431. }
  70432. else {
  70433. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  70434. }
  70435. this._babylonGamepads[newGamepad.index] = newGamepad;
  70436. return newGamepad;
  70437. };
  70438. GamepadManager.prototype._startMonitoringGamepads = function () {
  70439. if (!this._isMonitoring) {
  70440. this._isMonitoring = true;
  70441. //back-comp
  70442. if (!this._scene) {
  70443. this._checkGamepadsStatus();
  70444. }
  70445. }
  70446. };
  70447. GamepadManager.prototype._stopMonitoringGamepads = function () {
  70448. this._isMonitoring = false;
  70449. };
  70450. GamepadManager.prototype._checkGamepadsStatus = function () {
  70451. var _this = this;
  70452. // Hack to be compatible Chrome
  70453. this._updateGamepadObjects();
  70454. for (var i in this._babylonGamepads) {
  70455. var gamepad = this._babylonGamepads[i];
  70456. if (!gamepad || !gamepad.isConnected) {
  70457. continue;
  70458. }
  70459. gamepad.update();
  70460. }
  70461. if (this._isMonitoring && !this._scene) {
  70462. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  70463. }
  70464. };
  70465. // This function is called only on Chrome, which does not properly support
  70466. // connection/disconnection events and forces you to recopy again the gamepad object
  70467. GamepadManager.prototype._updateGamepadObjects = function () {
  70468. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  70469. for (var i = 0; i < gamepads.length; i++) {
  70470. var gamepad = gamepads[i];
  70471. if (gamepad) {
  70472. if (!this._babylonGamepads[gamepad.index]) {
  70473. var newGamepad = this._addNewGamepad(gamepad);
  70474. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70475. }
  70476. else {
  70477. // Forced to copy again this object for Chrome for unknown reason
  70478. this._babylonGamepads[i].browserGamepad = gamepad;
  70479. if (!this._babylonGamepads[i].isConnected) {
  70480. this._babylonGamepads[i]._isConnected = true;
  70481. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  70482. }
  70483. }
  70484. }
  70485. }
  70486. };
  70487. return GamepadManager;
  70488. }());
  70489. BABYLON.GamepadManager = GamepadManager;
  70490. })(BABYLON || (BABYLON = {}));
  70491. //# sourceMappingURL=babylon.gamepadManager.js.map
  70492. var BABYLON;
  70493. (function (BABYLON) {
  70494. var StickValues = /** @class */ (function () {
  70495. function StickValues(x, y) {
  70496. this.x = x;
  70497. this.y = y;
  70498. }
  70499. return StickValues;
  70500. }());
  70501. BABYLON.StickValues = StickValues;
  70502. var Gamepad = /** @class */ (function () {
  70503. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  70504. if (leftStickX === void 0) { leftStickX = 0; }
  70505. if (leftStickY === void 0) { leftStickY = 1; }
  70506. if (rightStickX === void 0) { rightStickX = 2; }
  70507. if (rightStickY === void 0) { rightStickY = 3; }
  70508. this.id = id;
  70509. this.index = index;
  70510. this.browserGamepad = browserGamepad;
  70511. this._isConnected = true;
  70512. this._invertLeftStickY = false;
  70513. this.type = Gamepad.GAMEPAD;
  70514. this._leftStickAxisX = leftStickX;
  70515. this._leftStickAxisY = leftStickY;
  70516. this._rightStickAxisX = rightStickX;
  70517. this._rightStickAxisY = rightStickY;
  70518. if (this.browserGamepad.axes.length >= 2) {
  70519. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70520. }
  70521. if (this.browserGamepad.axes.length >= 4) {
  70522. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70523. }
  70524. }
  70525. Object.defineProperty(Gamepad.prototype, "isConnected", {
  70526. get: function () {
  70527. return this._isConnected;
  70528. },
  70529. enumerable: true,
  70530. configurable: true
  70531. });
  70532. Gamepad.prototype.onleftstickchanged = function (callback) {
  70533. this._onleftstickchanged = callback;
  70534. };
  70535. Gamepad.prototype.onrightstickchanged = function (callback) {
  70536. this._onrightstickchanged = callback;
  70537. };
  70538. Object.defineProperty(Gamepad.prototype, "leftStick", {
  70539. get: function () {
  70540. return this._leftStick;
  70541. },
  70542. set: function (newValues) {
  70543. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  70544. this._onleftstickchanged(newValues);
  70545. }
  70546. this._leftStick = newValues;
  70547. },
  70548. enumerable: true,
  70549. configurable: true
  70550. });
  70551. Object.defineProperty(Gamepad.prototype, "rightStick", {
  70552. get: function () {
  70553. return this._rightStick;
  70554. },
  70555. set: function (newValues) {
  70556. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  70557. this._onrightstickchanged(newValues);
  70558. }
  70559. this._rightStick = newValues;
  70560. },
  70561. enumerable: true,
  70562. configurable: true
  70563. });
  70564. Gamepad.prototype.update = function () {
  70565. if (this._leftStick) {
  70566. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  70567. if (this._invertLeftStickY) {
  70568. this.leftStick.y *= -1;
  70569. }
  70570. }
  70571. if (this._rightStick) {
  70572. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  70573. }
  70574. };
  70575. Gamepad.prototype.dispose = function () {
  70576. };
  70577. Gamepad.GAMEPAD = 0;
  70578. Gamepad.GENERIC = 1;
  70579. Gamepad.XBOX = 2;
  70580. Gamepad.POSE_ENABLED = 3;
  70581. return Gamepad;
  70582. }());
  70583. BABYLON.Gamepad = Gamepad;
  70584. var GenericPad = /** @class */ (function (_super) {
  70585. __extends(GenericPad, _super);
  70586. function GenericPad(id, index, browserGamepad) {
  70587. var _this = _super.call(this, id, index, browserGamepad) || this;
  70588. _this.onButtonDownObservable = new BABYLON.Observable();
  70589. _this.onButtonUpObservable = new BABYLON.Observable();
  70590. _this.type = Gamepad.GENERIC;
  70591. _this._buttons = new Array(browserGamepad.buttons.length);
  70592. return _this;
  70593. }
  70594. GenericPad.prototype.onbuttondown = function (callback) {
  70595. this._onbuttondown = callback;
  70596. };
  70597. GenericPad.prototype.onbuttonup = function (callback) {
  70598. this._onbuttonup = callback;
  70599. };
  70600. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  70601. if (newValue !== currentValue) {
  70602. if (newValue === 1) {
  70603. if (this._onbuttondown) {
  70604. this._onbuttondown(buttonIndex);
  70605. }
  70606. this.onButtonDownObservable.notifyObservers(buttonIndex);
  70607. }
  70608. if (newValue === 0) {
  70609. if (this._onbuttonup) {
  70610. this._onbuttonup(buttonIndex);
  70611. }
  70612. this.onButtonUpObservable.notifyObservers(buttonIndex);
  70613. }
  70614. }
  70615. return newValue;
  70616. };
  70617. GenericPad.prototype.update = function () {
  70618. _super.prototype.update.call(this);
  70619. for (var index = 0; index < this._buttons.length; index++) {
  70620. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  70621. }
  70622. };
  70623. GenericPad.prototype.dispose = function () {
  70624. _super.prototype.dispose.call(this);
  70625. this.onButtonDownObservable.clear();
  70626. this.onButtonUpObservable.clear();
  70627. };
  70628. return GenericPad;
  70629. }(Gamepad));
  70630. BABYLON.GenericPad = GenericPad;
  70631. })(BABYLON || (BABYLON = {}));
  70632. //# sourceMappingURL=babylon.gamepad.js.map
  70633. var BABYLON;
  70634. (function (BABYLON) {
  70635. /**
  70636. * Defines supported buttons for XBox360 compatible gamepads
  70637. */
  70638. var Xbox360Button;
  70639. (function (Xbox360Button) {
  70640. /** A */
  70641. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  70642. /** B */
  70643. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  70644. /** X */
  70645. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  70646. /** Y */
  70647. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  70648. /** Start */
  70649. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  70650. /** Back */
  70651. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  70652. /** Left button */
  70653. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  70654. /** Right button */
  70655. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  70656. /** Left stick */
  70657. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  70658. /** Right stick */
  70659. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  70660. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  70661. /** Defines values for XBox360 DPad */
  70662. var Xbox360Dpad;
  70663. (function (Xbox360Dpad) {
  70664. /** Up */
  70665. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  70666. /** Down */
  70667. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  70668. /** Left */
  70669. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  70670. /** Right */
  70671. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  70672. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  70673. /**
  70674. * Defines a XBox360 gamepad
  70675. */
  70676. var Xbox360Pad = /** @class */ (function (_super) {
  70677. __extends(Xbox360Pad, _super);
  70678. /**
  70679. * Creates a new XBox360 gamepad object
  70680. * @param id defines the id of this gamepad
  70681. * @param index defines its index
  70682. * @param gamepad defines the internal HTML gamepad object
  70683. * @param xboxOne defines if it is a XBox One gamepad
  70684. */
  70685. function Xbox360Pad(id, index, gamepad, xboxOne) {
  70686. if (xboxOne === void 0) { xboxOne = false; }
  70687. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  70688. _this._leftTrigger = 0;
  70689. _this._rightTrigger = 0;
  70690. /** Observable raised when a button is pressed */
  70691. _this.onButtonDownObservable = new BABYLON.Observable();
  70692. /** Observable raised when a button is released */
  70693. _this.onButtonUpObservable = new BABYLON.Observable();
  70694. /** Observable raised when a pad is pressed */
  70695. _this.onPadDownObservable = new BABYLON.Observable();
  70696. /** Observable raised when a pad is released */
  70697. _this.onPadUpObservable = new BABYLON.Observable();
  70698. _this._buttonA = 0;
  70699. _this._buttonB = 0;
  70700. _this._buttonX = 0;
  70701. _this._buttonY = 0;
  70702. _this._buttonBack = 0;
  70703. _this._buttonStart = 0;
  70704. _this._buttonLB = 0;
  70705. _this._buttonRB = 0;
  70706. _this._buttonLeftStick = 0;
  70707. _this._buttonRightStick = 0;
  70708. _this._dPadUp = 0;
  70709. _this._dPadDown = 0;
  70710. _this._dPadLeft = 0;
  70711. _this._dPadRight = 0;
  70712. _this._isXboxOnePad = false;
  70713. _this.type = BABYLON.Gamepad.XBOX;
  70714. _this._isXboxOnePad = xboxOne;
  70715. return _this;
  70716. }
  70717. /**
  70718. * Defines the callback to call when left trigger is pressed
  70719. * @param callback defines the callback to use
  70720. */
  70721. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  70722. this._onlefttriggerchanged = callback;
  70723. };
  70724. /**
  70725. * Defines the callback to call when right trigger is pressed
  70726. * @param callback defines the callback to use
  70727. */
  70728. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  70729. this._onrighttriggerchanged = callback;
  70730. };
  70731. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  70732. /**
  70733. * Gets or sets left trigger value
  70734. */
  70735. get: function () {
  70736. return this._leftTrigger;
  70737. },
  70738. set: function (newValue) {
  70739. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  70740. this._onlefttriggerchanged(newValue);
  70741. }
  70742. this._leftTrigger = newValue;
  70743. },
  70744. enumerable: true,
  70745. configurable: true
  70746. });
  70747. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  70748. /**
  70749. * Gets or sets right trigger value
  70750. */
  70751. get: function () {
  70752. return this._rightTrigger;
  70753. },
  70754. set: function (newValue) {
  70755. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  70756. this._onrighttriggerchanged(newValue);
  70757. }
  70758. this._rightTrigger = newValue;
  70759. },
  70760. enumerable: true,
  70761. configurable: true
  70762. });
  70763. /**
  70764. * Defines the callback to call when a button is pressed
  70765. * @param callback defines the callback to use
  70766. */
  70767. Xbox360Pad.prototype.onbuttondown = function (callback) {
  70768. this._onbuttondown = callback;
  70769. };
  70770. /**
  70771. * Defines the callback to call when a button is released
  70772. * @param callback defines the callback to use
  70773. */
  70774. Xbox360Pad.prototype.onbuttonup = function (callback) {
  70775. this._onbuttonup = callback;
  70776. };
  70777. /**
  70778. * Defines the callback to call when a pad is pressed
  70779. * @param callback defines the callback to use
  70780. */
  70781. Xbox360Pad.prototype.ondpaddown = function (callback) {
  70782. this._ondpaddown = callback;
  70783. };
  70784. /**
  70785. * Defines the callback to call when a pad is released
  70786. * @param callback defines the callback to use
  70787. */
  70788. Xbox360Pad.prototype.ondpadup = function (callback) {
  70789. this._ondpadup = callback;
  70790. };
  70791. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  70792. if (newValue !== currentValue) {
  70793. if (newValue === 1) {
  70794. if (this._onbuttondown) {
  70795. this._onbuttondown(buttonType);
  70796. }
  70797. this.onButtonDownObservable.notifyObservers(buttonType);
  70798. }
  70799. if (newValue === 0) {
  70800. if (this._onbuttonup) {
  70801. this._onbuttonup(buttonType);
  70802. }
  70803. this.onButtonUpObservable.notifyObservers(buttonType);
  70804. }
  70805. }
  70806. return newValue;
  70807. };
  70808. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  70809. if (newValue !== currentValue) {
  70810. if (newValue === 1) {
  70811. if (this._ondpaddown) {
  70812. this._ondpaddown(buttonType);
  70813. }
  70814. this.onPadDownObservable.notifyObservers(buttonType);
  70815. }
  70816. if (newValue === 0) {
  70817. if (this._ondpadup) {
  70818. this._ondpadup(buttonType);
  70819. }
  70820. this.onPadUpObservable.notifyObservers(buttonType);
  70821. }
  70822. }
  70823. return newValue;
  70824. };
  70825. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  70826. /** Gets or sets value of A button */
  70827. get: function () {
  70828. return this._buttonA;
  70829. },
  70830. set: function (value) {
  70831. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  70832. },
  70833. enumerable: true,
  70834. configurable: true
  70835. });
  70836. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  70837. /** Gets or sets value of B button */
  70838. get: function () {
  70839. return this._buttonB;
  70840. },
  70841. set: function (value) {
  70842. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  70843. },
  70844. enumerable: true,
  70845. configurable: true
  70846. });
  70847. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  70848. /** Gets or sets value of X button */
  70849. get: function () {
  70850. return this._buttonX;
  70851. },
  70852. set: function (value) {
  70853. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  70854. },
  70855. enumerable: true,
  70856. configurable: true
  70857. });
  70858. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  70859. /** Gets or sets value of Y button */
  70860. get: function () {
  70861. return this._buttonY;
  70862. },
  70863. set: function (value) {
  70864. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  70865. },
  70866. enumerable: true,
  70867. configurable: true
  70868. });
  70869. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  70870. /** Gets or sets value of Start button */
  70871. get: function () {
  70872. return this._buttonStart;
  70873. },
  70874. set: function (value) {
  70875. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  70876. },
  70877. enumerable: true,
  70878. configurable: true
  70879. });
  70880. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  70881. /** Gets or sets value of Back button */
  70882. get: function () {
  70883. return this._buttonBack;
  70884. },
  70885. set: function (value) {
  70886. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  70887. },
  70888. enumerable: true,
  70889. configurable: true
  70890. });
  70891. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  70892. /** Gets or sets value of Left button */
  70893. get: function () {
  70894. return this._buttonLB;
  70895. },
  70896. set: function (value) {
  70897. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  70898. },
  70899. enumerable: true,
  70900. configurable: true
  70901. });
  70902. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  70903. /** Gets or sets value of Right button */
  70904. get: function () {
  70905. return this._buttonRB;
  70906. },
  70907. set: function (value) {
  70908. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  70909. },
  70910. enumerable: true,
  70911. configurable: true
  70912. });
  70913. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  70914. /** Gets or sets value of left stick */
  70915. get: function () {
  70916. return this._buttonLeftStick;
  70917. },
  70918. set: function (value) {
  70919. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  70920. },
  70921. enumerable: true,
  70922. configurable: true
  70923. });
  70924. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  70925. /** Gets or sets value of right stick */
  70926. get: function () {
  70927. return this._buttonRightStick;
  70928. },
  70929. set: function (value) {
  70930. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  70931. },
  70932. enumerable: true,
  70933. configurable: true
  70934. });
  70935. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  70936. /** Gets or sets value of DPad up */
  70937. get: function () {
  70938. return this._dPadUp;
  70939. },
  70940. set: function (value) {
  70941. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  70942. },
  70943. enumerable: true,
  70944. configurable: true
  70945. });
  70946. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  70947. /** Gets or sets value of DPad down */
  70948. get: function () {
  70949. return this._dPadDown;
  70950. },
  70951. set: function (value) {
  70952. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  70953. },
  70954. enumerable: true,
  70955. configurable: true
  70956. });
  70957. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  70958. /** Gets or sets value of DPad left */
  70959. get: function () {
  70960. return this._dPadLeft;
  70961. },
  70962. set: function (value) {
  70963. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  70964. },
  70965. enumerable: true,
  70966. configurable: true
  70967. });
  70968. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  70969. /** Gets or sets value of DPad right */
  70970. get: function () {
  70971. return this._dPadRight;
  70972. },
  70973. set: function (value) {
  70974. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  70975. },
  70976. enumerable: true,
  70977. configurable: true
  70978. });
  70979. /**
  70980. * Force the gamepad to synchronize with device values
  70981. */
  70982. Xbox360Pad.prototype.update = function () {
  70983. _super.prototype.update.call(this);
  70984. if (this._isXboxOnePad) {
  70985. this.buttonA = this.browserGamepad.buttons[0].value;
  70986. this.buttonB = this.browserGamepad.buttons[1].value;
  70987. this.buttonX = this.browserGamepad.buttons[2].value;
  70988. this.buttonY = this.browserGamepad.buttons[3].value;
  70989. this.buttonLB = this.browserGamepad.buttons[4].value;
  70990. this.buttonRB = this.browserGamepad.buttons[5].value;
  70991. this.leftTrigger = this.browserGamepad.axes[2];
  70992. this.rightTrigger = this.browserGamepad.axes[5];
  70993. this.buttonBack = this.browserGamepad.buttons[9].value;
  70994. this.buttonStart = this.browserGamepad.buttons[8].value;
  70995. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  70996. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  70997. this.dPadUp = this.browserGamepad.buttons[11].value;
  70998. this.dPadDown = this.browserGamepad.buttons[12].value;
  70999. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71000. this.dPadRight = this.browserGamepad.buttons[14].value;
  71001. }
  71002. else {
  71003. this.buttonA = this.browserGamepad.buttons[0].value;
  71004. this.buttonB = this.browserGamepad.buttons[1].value;
  71005. this.buttonX = this.browserGamepad.buttons[2].value;
  71006. this.buttonY = this.browserGamepad.buttons[3].value;
  71007. this.buttonLB = this.browserGamepad.buttons[4].value;
  71008. this.buttonRB = this.browserGamepad.buttons[5].value;
  71009. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71010. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71011. this.buttonBack = this.browserGamepad.buttons[8].value;
  71012. this.buttonStart = this.browserGamepad.buttons[9].value;
  71013. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71014. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71015. this.dPadUp = this.browserGamepad.buttons[12].value;
  71016. this.dPadDown = this.browserGamepad.buttons[13].value;
  71017. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71018. this.dPadRight = this.browserGamepad.buttons[15].value;
  71019. }
  71020. };
  71021. Xbox360Pad.prototype.dispose = function () {
  71022. _super.prototype.dispose.call(this);
  71023. this.onButtonDownObservable.clear();
  71024. this.onButtonUpObservable.clear();
  71025. this.onPadDownObservable.clear();
  71026. this.onPadUpObservable.clear();
  71027. };
  71028. return Xbox360Pad;
  71029. }(BABYLON.Gamepad));
  71030. BABYLON.Xbox360Pad = Xbox360Pad;
  71031. })(BABYLON || (BABYLON = {}));
  71032. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71033. var BABYLON;
  71034. (function (BABYLON) {
  71035. /**
  71036. * Defines the types of pose enabled controllers that are supported
  71037. */
  71038. var PoseEnabledControllerType;
  71039. (function (PoseEnabledControllerType) {
  71040. /**
  71041. * HTC Vive
  71042. */
  71043. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71044. /**
  71045. * Oculus Rift
  71046. */
  71047. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71048. /**
  71049. * Windows mixed reality
  71050. */
  71051. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71052. /**
  71053. * Samsung gear VR
  71054. */
  71055. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71056. /**
  71057. * Google Daydream
  71058. */
  71059. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71060. /**
  71061. * Generic
  71062. */
  71063. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71064. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71065. /**
  71066. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71067. */
  71068. var PoseEnabledControllerHelper = /** @class */ (function () {
  71069. function PoseEnabledControllerHelper() {
  71070. }
  71071. /**
  71072. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71073. * @param vrGamepad the gamepad to initialized
  71074. * @returns a vr controller of the type the gamepad identified as
  71075. */
  71076. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71077. // Oculus Touch
  71078. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71079. return new BABYLON.OculusTouchController(vrGamepad);
  71080. }
  71081. // Windows Mixed Reality controllers
  71082. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71083. return new BABYLON.WindowsMotionController(vrGamepad);
  71084. }
  71085. // HTC Vive
  71086. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71087. return new BABYLON.ViveController(vrGamepad);
  71088. }
  71089. // Samsung/Oculus Gear VR
  71090. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0) {
  71091. return new BABYLON.GearVRController(vrGamepad);
  71092. }
  71093. // Google Daydream
  71094. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71095. return new BABYLON.DaydreamController(vrGamepad);
  71096. }
  71097. // Generic
  71098. else {
  71099. return new BABYLON.GenericController(vrGamepad);
  71100. }
  71101. };
  71102. return PoseEnabledControllerHelper;
  71103. }());
  71104. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71105. /**
  71106. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71107. */
  71108. var PoseEnabledController = /** @class */ (function (_super) {
  71109. __extends(PoseEnabledController, _super);
  71110. /**
  71111. * Creates a new PoseEnabledController from a gamepad
  71112. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71113. */
  71114. function PoseEnabledController(browserGamepad) {
  71115. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71116. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71117. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71118. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71119. /**
  71120. * The device position in babylon space
  71121. */
  71122. _this.devicePosition = BABYLON.Vector3.Zero();
  71123. /**
  71124. * The device rotation in babylon space
  71125. */
  71126. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71127. /**
  71128. * The scale factor of the device in babylon space
  71129. */
  71130. _this.deviceScaleFactor = 1;
  71131. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71132. /**
  71133. * Internal, matrix used to convert room space to babylon space
  71134. */
  71135. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71136. /**
  71137. * Node to be used when casting a ray from the controller
  71138. */
  71139. _this._pointingPoseNode = null;
  71140. _this._workingMatrix = BABYLON.Matrix.Identity();
  71141. /**
  71142. * @hidden
  71143. */
  71144. _this._meshAttachedObservable = new BABYLON.Observable();
  71145. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71146. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71147. _this.position = BABYLON.Vector3.Zero();
  71148. _this.rotationQuaternion = new BABYLON.Quaternion();
  71149. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71150. _this._calculatedRotation = new BABYLON.Quaternion();
  71151. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71152. return _this;
  71153. }
  71154. /**
  71155. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71156. */
  71157. PoseEnabledController.prototype.update = function () {
  71158. _super.prototype.update.call(this);
  71159. var pose = this.browserGamepad.pose;
  71160. this.updateFromDevice(pose);
  71161. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71162. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71163. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71164. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71165. if (this._mesh) {
  71166. this._mesh.position.copyFrom(this.devicePosition);
  71167. if (this._mesh.rotationQuaternion) {
  71168. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71169. }
  71170. }
  71171. };
  71172. /**
  71173. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71174. * @param poseData raw pose fromthe device
  71175. */
  71176. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71177. if (poseData) {
  71178. this.rawPose = poseData;
  71179. if (poseData.position) {
  71180. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71181. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71182. this._deviceRoomPosition.z *= -1;
  71183. }
  71184. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71185. this._calculatedPosition.addInPlace(this.position);
  71186. }
  71187. var pose = this.rawPose;
  71188. if (poseData.orientation && pose.orientation) {
  71189. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71190. if (this._mesh) {
  71191. if (this._mesh.getScene().useRightHandedSystem) {
  71192. this._deviceRoomRotationQuaternion.z *= -1;
  71193. this._deviceRoomRotationQuaternion.w *= -1;
  71194. }
  71195. else {
  71196. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71197. }
  71198. }
  71199. // if the camera is set, rotate to the camera's rotation
  71200. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71201. }
  71202. }
  71203. };
  71204. /**
  71205. * Attaches a mesh to the controller
  71206. * @param mesh the mesh to be attached
  71207. */
  71208. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71209. if (this._mesh) {
  71210. this._mesh.parent = null;
  71211. }
  71212. this._mesh = mesh;
  71213. if (this._poseControlledCamera) {
  71214. this._mesh.parent = this._poseControlledCamera;
  71215. }
  71216. if (!this._mesh.rotationQuaternion) {
  71217. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71218. }
  71219. this._meshAttachedObservable.notifyObservers(mesh);
  71220. };
  71221. /**
  71222. * Attaches the controllers mesh to a camera
  71223. * @param camera the camera the mesh should be attached to
  71224. */
  71225. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71226. this._poseControlledCamera = camera;
  71227. if (this._mesh) {
  71228. this._mesh.parent = this._poseControlledCamera;
  71229. }
  71230. };
  71231. /**
  71232. * Disposes of the controller
  71233. */
  71234. PoseEnabledController.prototype.dispose = function () {
  71235. if (this._mesh) {
  71236. this._mesh.dispose();
  71237. }
  71238. this._mesh = null;
  71239. _super.prototype.dispose.call(this);
  71240. };
  71241. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71242. /**
  71243. * The mesh that is attached to the controller
  71244. */
  71245. get: function () {
  71246. return this._mesh;
  71247. },
  71248. enumerable: true,
  71249. configurable: true
  71250. });
  71251. /**
  71252. * Gets the ray of the controller in the direction the controller is pointing
  71253. * @param length the length the resulting ray should be
  71254. * @returns a ray in the direction the controller is pointing
  71255. */
  71256. PoseEnabledController.prototype.getForwardRay = function (length) {
  71257. if (length === void 0) { length = 100; }
  71258. if (!this.mesh) {
  71259. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71260. }
  71261. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71262. var origin = m.getTranslation();
  71263. var forward = new BABYLON.Vector3(0, 0, -1);
  71264. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71265. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71266. return new BABYLON.Ray(origin, direction, length);
  71267. };
  71268. /**
  71269. * Name of the child mesh that can be used to cast a ray from the controller
  71270. */
  71271. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71272. return PoseEnabledController;
  71273. }(BABYLON.Gamepad));
  71274. BABYLON.PoseEnabledController = PoseEnabledController;
  71275. })(BABYLON || (BABYLON = {}));
  71276. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71277. var BABYLON;
  71278. (function (BABYLON) {
  71279. /**
  71280. * Defines the WebVRController object that represents controllers tracked in 3D space
  71281. */
  71282. var WebVRController = /** @class */ (function (_super) {
  71283. __extends(WebVRController, _super);
  71284. /**
  71285. * Creates a new WebVRController from a gamepad
  71286. * @param vrGamepad the gamepad that the WebVRController should be created from
  71287. */
  71288. function WebVRController(vrGamepad) {
  71289. var _this = _super.call(this, vrGamepad) || this;
  71290. // Observables
  71291. /**
  71292. * Fired when the trigger state has changed
  71293. */
  71294. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71295. /**
  71296. * Fired when the main button state has changed
  71297. */
  71298. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71299. /**
  71300. * Fired when the secondary button state has changed
  71301. */
  71302. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71303. /**
  71304. * Fired when the pad state has changed
  71305. */
  71306. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71307. /**
  71308. * Fired when controllers stick values have changed
  71309. */
  71310. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71311. /**
  71312. * X and Y axis corrisponding to the controllers joystick
  71313. */
  71314. _this.pad = { x: 0, y: 0 };
  71315. // avoid GC, store state in a tmp object
  71316. _this._changes = {
  71317. pressChanged: false,
  71318. touchChanged: false,
  71319. valueChanged: false,
  71320. changed: false
  71321. };
  71322. _this._buttons = new Array(vrGamepad.buttons.length);
  71323. _this.hand = vrGamepad.hand;
  71324. return _this;
  71325. }
  71326. /**
  71327. * Fired when a controller button's state has changed
  71328. * @param callback the callback containing the button that was modified
  71329. */
  71330. WebVRController.prototype.onButtonStateChange = function (callback) {
  71331. this._onButtonStateChange = callback;
  71332. };
  71333. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71334. /**
  71335. * The default controller model for the controller
  71336. */
  71337. get: function () {
  71338. return this._defaultModel;
  71339. },
  71340. enumerable: true,
  71341. configurable: true
  71342. });
  71343. /**
  71344. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71345. */
  71346. WebVRController.prototype.update = function () {
  71347. _super.prototype.update.call(this);
  71348. for (var index = 0; index < this._buttons.length; index++) {
  71349. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71350. }
  71351. ;
  71352. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71353. this.pad.x = this.leftStick.x;
  71354. this.pad.y = this.leftStick.y;
  71355. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71356. }
  71357. };
  71358. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71359. if (!newState) {
  71360. newState = {
  71361. pressed: false,
  71362. touched: false,
  71363. value: 0
  71364. };
  71365. }
  71366. if (!currentState) {
  71367. this._buttons[buttonIndex] = {
  71368. pressed: newState.pressed,
  71369. touched: newState.touched,
  71370. value: newState.value
  71371. };
  71372. return;
  71373. }
  71374. this._checkChanges(newState, currentState);
  71375. if (this._changes.changed) {
  71376. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71377. this._handleButtonChange(buttonIndex, newState, this._changes);
  71378. }
  71379. this._buttons[buttonIndex].pressed = newState.pressed;
  71380. this._buttons[buttonIndex].touched = newState.touched;
  71381. // oculus triggers are never 0, thou not touched.
  71382. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71383. };
  71384. WebVRController.prototype._checkChanges = function (newState, currentState) {
  71385. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  71386. this._changes.touchChanged = newState.touched !== currentState.touched;
  71387. this._changes.valueChanged = newState.value !== currentState.value;
  71388. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  71389. return this._changes;
  71390. };
  71391. /**
  71392. * Disposes of th webVRCOntroller
  71393. */
  71394. WebVRController.prototype.dispose = function () {
  71395. _super.prototype.dispose.call(this);
  71396. this.onTriggerStateChangedObservable.clear();
  71397. this.onMainButtonStateChangedObservable.clear();
  71398. this.onSecondaryButtonStateChangedObservable.clear();
  71399. this.onPadStateChangedObservable.clear();
  71400. this.onPadValuesChangedObservable.clear();
  71401. };
  71402. return WebVRController;
  71403. }(BABYLON.PoseEnabledController));
  71404. BABYLON.WebVRController = WebVRController;
  71405. })(BABYLON || (BABYLON = {}));
  71406. //# sourceMappingURL=babylon.webVRController.js.map
  71407. var BABYLON;
  71408. (function (BABYLON) {
  71409. /**
  71410. * Oculus Touch Controller
  71411. */
  71412. var OculusTouchController = /** @class */ (function (_super) {
  71413. __extends(OculusTouchController, _super);
  71414. /**
  71415. * Creates a new OculusTouchController from a gamepad
  71416. * @param vrGamepad the gamepad that the controller should be created from
  71417. */
  71418. function OculusTouchController(vrGamepad) {
  71419. var _this = _super.call(this, vrGamepad) || this;
  71420. /**
  71421. * Fired when the secondary trigger on this controller is modified
  71422. */
  71423. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  71424. /**
  71425. * Fired when the thumb rest on this controller is modified
  71426. */
  71427. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  71428. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  71429. return _this;
  71430. }
  71431. /**
  71432. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71433. * @param scene scene in which to add meshes
  71434. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71435. */
  71436. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71437. var _this = this;
  71438. var meshName;
  71439. // Hand
  71440. if (this.hand === 'left') {
  71441. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  71442. }
  71443. else { // Right is the default if no hand is specified
  71444. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  71445. }
  71446. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  71447. /*
  71448. Parent Mesh name: oculus_touch_left
  71449. - body
  71450. - trigger
  71451. - thumbstick
  71452. - grip
  71453. - button_y
  71454. - button_x
  71455. - button_enter
  71456. */
  71457. _this._defaultModel = newMeshes[1];
  71458. _this.attachToMesh(_this._defaultModel);
  71459. if (meshLoaded) {
  71460. meshLoaded(_this._defaultModel);
  71461. }
  71462. });
  71463. };
  71464. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  71465. /**
  71466. * Fired when the A button on this controller is modified
  71467. */
  71468. get: function () {
  71469. if (this.hand === 'right') {
  71470. return this.onMainButtonStateChangedObservable;
  71471. }
  71472. else {
  71473. throw new Error('No A button on left hand');
  71474. }
  71475. },
  71476. enumerable: true,
  71477. configurable: true
  71478. });
  71479. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  71480. /**
  71481. * Fired when the B button on this controller is modified
  71482. */
  71483. get: function () {
  71484. if (this.hand === 'right') {
  71485. return this.onSecondaryButtonStateChangedObservable;
  71486. }
  71487. else {
  71488. throw new Error('No B button on left hand');
  71489. }
  71490. },
  71491. enumerable: true,
  71492. configurable: true
  71493. });
  71494. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  71495. /**
  71496. * Fired when the X button on this controller is modified
  71497. */
  71498. get: function () {
  71499. if (this.hand === 'left') {
  71500. return this.onMainButtonStateChangedObservable;
  71501. }
  71502. else {
  71503. throw new Error('No X button on right hand');
  71504. }
  71505. },
  71506. enumerable: true,
  71507. configurable: true
  71508. });
  71509. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  71510. /**
  71511. * Fired when the Y button on this controller is modified
  71512. */
  71513. get: function () {
  71514. if (this.hand === 'left') {
  71515. return this.onSecondaryButtonStateChangedObservable;
  71516. }
  71517. else {
  71518. throw new Error('No Y button on right hand');
  71519. }
  71520. },
  71521. enumerable: true,
  71522. configurable: true
  71523. });
  71524. /**
  71525. * Called once for each button that changed state since the last frame
  71526. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  71527. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  71528. * 2) secondary trigger (same)
  71529. * 3) A (right) X (left), touch, pressed = value
  71530. * 4) B / Y
  71531. * 5) thumb rest
  71532. * @param buttonIdx Which button index changed
  71533. * @param state New state of the button
  71534. * @param changes Which properties on the state changed since last frame
  71535. */
  71536. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71537. var notifyObject = state; //{ state: state, changes: changes };
  71538. var triggerDirection = this.hand === 'right' ? -1 : 1;
  71539. switch (buttonIdx) {
  71540. case 0:
  71541. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71542. return;
  71543. case 1: // index trigger
  71544. if (this._defaultModel) {
  71545. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  71546. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  71547. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  71548. }
  71549. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71550. return;
  71551. case 2: // secondary trigger
  71552. if (this._defaultModel) {
  71553. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  71554. }
  71555. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  71556. return;
  71557. case 3:
  71558. if (this._defaultModel) {
  71559. if (notifyObject.pressed) {
  71560. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  71561. }
  71562. else {
  71563. (this._defaultModel.getChildren()[1]).position.y = 0;
  71564. }
  71565. }
  71566. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71567. return;
  71568. case 4:
  71569. if (this._defaultModel) {
  71570. if (notifyObject.pressed) {
  71571. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71572. }
  71573. else {
  71574. (this._defaultModel.getChildren()[2]).position.y = 0;
  71575. }
  71576. }
  71577. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71578. return;
  71579. case 5:
  71580. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  71581. return;
  71582. }
  71583. };
  71584. /**
  71585. * Base Url for the controller model.
  71586. */
  71587. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  71588. /**
  71589. * File name for the left controller model.
  71590. */
  71591. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  71592. /**
  71593. * File name for the right controller model.
  71594. */
  71595. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  71596. return OculusTouchController;
  71597. }(BABYLON.WebVRController));
  71598. BABYLON.OculusTouchController = OculusTouchController;
  71599. })(BABYLON || (BABYLON = {}));
  71600. //# sourceMappingURL=babylon.oculusTouchController.js.map
  71601. var BABYLON;
  71602. (function (BABYLON) {
  71603. /**
  71604. * Vive Controller
  71605. */
  71606. var ViveController = /** @class */ (function (_super) {
  71607. __extends(ViveController, _super);
  71608. /**
  71609. * Creates a new ViveController from a gamepad
  71610. * @param vrGamepad the gamepad that the controller should be created from
  71611. */
  71612. function ViveController(vrGamepad) {
  71613. var _this = _super.call(this, vrGamepad) || this;
  71614. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  71615. _this._invertLeftStickY = true;
  71616. return _this;
  71617. }
  71618. /**
  71619. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71620. * @param scene scene in which to add meshes
  71621. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71622. */
  71623. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71624. var _this = this;
  71625. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  71626. /*
  71627. Parent Mesh name: ViveWand
  71628. - body
  71629. - r_gripper
  71630. - l_gripper
  71631. - menu_button
  71632. - system_button
  71633. - trackpad
  71634. - trigger
  71635. - LED
  71636. */
  71637. _this._defaultModel = newMeshes[1];
  71638. _this.attachToMesh(_this._defaultModel);
  71639. if (meshLoaded) {
  71640. meshLoaded(_this._defaultModel);
  71641. }
  71642. });
  71643. };
  71644. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  71645. /**
  71646. * Fired when the left button on this controller is modified
  71647. */
  71648. get: function () {
  71649. return this.onMainButtonStateChangedObservable;
  71650. },
  71651. enumerable: true,
  71652. configurable: true
  71653. });
  71654. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  71655. /**
  71656. * Fired when the right button on this controller is modified
  71657. */
  71658. get: function () {
  71659. return this.onMainButtonStateChangedObservable;
  71660. },
  71661. enumerable: true,
  71662. configurable: true
  71663. });
  71664. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  71665. /**
  71666. * Fired when the menu button on this controller is modified
  71667. */
  71668. get: function () {
  71669. return this.onSecondaryButtonStateChangedObservable;
  71670. },
  71671. enumerable: true,
  71672. configurable: true
  71673. });
  71674. /**
  71675. * Called once for each button that changed state since the last frame
  71676. * Vive mapping:
  71677. * 0: touchpad
  71678. * 1: trigger
  71679. * 2: left AND right buttons
  71680. * 3: menu button
  71681. * @param buttonIdx Which button index changed
  71682. * @param state New state of the button
  71683. * @param changes Which properties on the state changed since last frame
  71684. */
  71685. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71686. var notifyObject = state; //{ state: state, changes: changes };
  71687. switch (buttonIdx) {
  71688. case 0:
  71689. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  71690. return;
  71691. case 1: // index trigger
  71692. if (this._defaultModel) {
  71693. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  71694. }
  71695. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  71696. return;
  71697. case 2: // left AND right button
  71698. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  71699. return;
  71700. case 3:
  71701. if (this._defaultModel) {
  71702. if (notifyObject.pressed) {
  71703. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  71704. }
  71705. else {
  71706. (this._defaultModel.getChildren()[2]).position.y = 0;
  71707. }
  71708. }
  71709. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  71710. return;
  71711. }
  71712. };
  71713. /**
  71714. * Base Url for the controller model.
  71715. */
  71716. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  71717. /**
  71718. * File name for the controller model.
  71719. */
  71720. ViveController.MODEL_FILENAME = 'wand.babylon';
  71721. return ViveController;
  71722. }(BABYLON.WebVRController));
  71723. BABYLON.ViveController = ViveController;
  71724. })(BABYLON || (BABYLON = {}));
  71725. //# sourceMappingURL=babylon.viveController.js.map
  71726. var BABYLON;
  71727. (function (BABYLON) {
  71728. /**
  71729. * Generic Controller
  71730. */
  71731. var GenericController = /** @class */ (function (_super) {
  71732. __extends(GenericController, _super);
  71733. /**
  71734. * Creates a new GenericController from a gamepad
  71735. * @param vrGamepad the gamepad that the controller should be created from
  71736. */
  71737. function GenericController(vrGamepad) {
  71738. return _super.call(this, vrGamepad) || this;
  71739. }
  71740. /**
  71741. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71742. * @param scene scene in which to add meshes
  71743. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71744. */
  71745. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  71746. var _this = this;
  71747. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  71748. _this._defaultModel = newMeshes[1];
  71749. _this.attachToMesh(_this._defaultModel);
  71750. if (meshLoaded) {
  71751. meshLoaded(_this._defaultModel);
  71752. }
  71753. });
  71754. };
  71755. /**
  71756. * Called once for each button that changed state since the last frame
  71757. * @param buttonIdx Which button index changed
  71758. * @param state New state of the button
  71759. * @param changes Which properties on the state changed since last frame
  71760. */
  71761. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71762. console.log("Button id: " + buttonIdx + "state: ");
  71763. console.dir(state);
  71764. };
  71765. /**
  71766. * Base Url for the controller model.
  71767. */
  71768. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  71769. /**
  71770. * File name for the controller model.
  71771. */
  71772. GenericController.MODEL_FILENAME = 'generic.babylon';
  71773. return GenericController;
  71774. }(BABYLON.WebVRController));
  71775. BABYLON.GenericController = GenericController;
  71776. })(BABYLON || (BABYLON = {}));
  71777. //# sourceMappingURL=babylon.genericController.js.map
  71778. var BABYLON;
  71779. (function (BABYLON) {
  71780. /**
  71781. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  71782. */
  71783. var LoadedMeshInfo = /** @class */ (function () {
  71784. function LoadedMeshInfo() {
  71785. /**
  71786. * Map of the button meshes contained in the controller
  71787. */
  71788. this.buttonMeshes = {};
  71789. /**
  71790. * Map of the axis meshes contained in the controller
  71791. */
  71792. this.axisMeshes = {};
  71793. }
  71794. return LoadedMeshInfo;
  71795. }());
  71796. /**
  71797. * Defines the WindowsMotionController object that the state of the windows motion controller
  71798. */
  71799. var WindowsMotionController = /** @class */ (function (_super) {
  71800. __extends(WindowsMotionController, _super);
  71801. /**
  71802. * Creates a new WindowsMotionController from a gamepad
  71803. * @param vrGamepad the gamepad that the controller should be created from
  71804. */
  71805. function WindowsMotionController(vrGamepad) {
  71806. var _this = _super.call(this, vrGamepad) || this;
  71807. _this._mapping = {
  71808. // Semantic button names
  71809. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  71810. // A mapping of the button name to glTF model node name
  71811. // that should be transformed by button value.
  71812. buttonMeshNames: {
  71813. 'trigger': 'SELECT',
  71814. 'menu': 'MENU',
  71815. 'grip': 'GRASP',
  71816. 'thumbstick': 'THUMBSTICK_PRESS',
  71817. 'trackpad': 'TOUCHPAD_PRESS'
  71818. },
  71819. // This mapping is used to translate from the Motion Controller to Babylon semantics
  71820. buttonObservableNames: {
  71821. 'trigger': 'onTriggerStateChangedObservable',
  71822. 'menu': 'onSecondaryButtonStateChangedObservable',
  71823. 'grip': 'onMainButtonStateChangedObservable',
  71824. 'thumbstick': 'onPadStateChangedObservable',
  71825. 'trackpad': 'onTrackpadChangedObservable'
  71826. },
  71827. // A mapping of the axis name to glTF model node name
  71828. // that should be transformed by axis value.
  71829. // This array mirrors the browserGamepad.axes array, such that
  71830. // the mesh corresponding to axis 0 is in this array index 0.
  71831. axisMeshNames: [
  71832. 'THUMBSTICK_X',
  71833. 'THUMBSTICK_Y',
  71834. 'TOUCHPAD_TOUCH_X',
  71835. 'TOUCHPAD_TOUCH_Y'
  71836. ],
  71837. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  71838. };
  71839. /**
  71840. * Fired when the trackpad on this controller is clicked
  71841. */
  71842. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  71843. /**
  71844. * Fired when the trackpad on this controller is modified
  71845. */
  71846. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  71847. /**
  71848. * The current x and y values of this controller's trackpad
  71849. */
  71850. _this.trackpad = { x: 0, y: 0 };
  71851. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  71852. _this._loadedMeshInfo = null;
  71853. return _this;
  71854. }
  71855. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  71856. /**
  71857. * Fired when the trigger on this controller is modified
  71858. */
  71859. get: function () {
  71860. return this.onTriggerStateChangedObservable;
  71861. },
  71862. enumerable: true,
  71863. configurable: true
  71864. });
  71865. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  71866. /**
  71867. * Fired when the menu button on this controller is modified
  71868. */
  71869. get: function () {
  71870. return this.onSecondaryButtonStateChangedObservable;
  71871. },
  71872. enumerable: true,
  71873. configurable: true
  71874. });
  71875. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  71876. /**
  71877. * Fired when the grip button on this controller is modified
  71878. */
  71879. get: function () {
  71880. return this.onMainButtonStateChangedObservable;
  71881. },
  71882. enumerable: true,
  71883. configurable: true
  71884. });
  71885. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  71886. /**
  71887. * Fired when the thumbstick button on this controller is modified
  71888. */
  71889. get: function () {
  71890. return this.onPadStateChangedObservable;
  71891. },
  71892. enumerable: true,
  71893. configurable: true
  71894. });
  71895. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  71896. /**
  71897. * Fired when the touchpad button on this controller is modified
  71898. */
  71899. get: function () {
  71900. return this.onTrackpadChangedObservable;
  71901. },
  71902. enumerable: true,
  71903. configurable: true
  71904. });
  71905. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  71906. /**
  71907. * Fired when the touchpad values on this controller are modified
  71908. */
  71909. get: function () {
  71910. return this.onTrackpadValuesChangedObservable;
  71911. },
  71912. enumerable: true,
  71913. configurable: true
  71914. });
  71915. /**
  71916. * Called once per frame by the engine.
  71917. */
  71918. WindowsMotionController.prototype.update = function () {
  71919. _super.prototype.update.call(this);
  71920. if (this.browserGamepad.axes) {
  71921. if (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y) {
  71922. this.trackpad.x = this.browserGamepad["axes"][2];
  71923. this.trackpad.y = this.browserGamepad["axes"][3];
  71924. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  71925. }
  71926. // Only need to animate axes if there is a loaded mesh
  71927. if (this._loadedMeshInfo) {
  71928. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  71929. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  71930. }
  71931. }
  71932. }
  71933. };
  71934. /**
  71935. * Called once for each button that changed state since the last frame
  71936. * @param buttonIdx Which button index changed
  71937. * @param state New state of the button
  71938. * @param changes Which properties on the state changed since last frame
  71939. */
  71940. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  71941. var buttonName = this._mapping.buttons[buttonIdx];
  71942. if (!buttonName) {
  71943. return;
  71944. }
  71945. // Only emit events for buttons that we know how to map from index to name
  71946. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  71947. if (observable) {
  71948. observable.notifyObservers(state);
  71949. }
  71950. this._lerpButtonTransform(buttonName, state.value);
  71951. };
  71952. /**
  71953. * Moves the buttons on the controller mesh based on their current state
  71954. * @param buttonName the name of the button to move
  71955. * @param buttonValue the value of the button which determines the buttons new position
  71956. */
  71957. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  71958. // If there is no loaded mesh, there is nothing to transform.
  71959. if (!this._loadedMeshInfo) {
  71960. return;
  71961. }
  71962. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  71963. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71964. return;
  71965. }
  71966. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  71967. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  71968. };
  71969. /**
  71970. * Moves the axis on the controller mesh based on its current state
  71971. * @param axis the index of the axis
  71972. * @param axisValue the value of the axis which determines the meshes new position
  71973. * @hidden
  71974. */
  71975. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  71976. if (!this._loadedMeshInfo) {
  71977. return;
  71978. }
  71979. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  71980. if (!meshInfo) {
  71981. return;
  71982. }
  71983. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  71984. return;
  71985. }
  71986. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  71987. var lerpValue = axisValue * 0.5 + 0.5;
  71988. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  71989. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  71990. };
  71991. /**
  71992. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  71993. * @param scene scene in which to add meshes
  71994. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  71995. */
  71996. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  71997. var _this = this;
  71998. if (forceDefault === void 0) { forceDefault = false; }
  71999. var path;
  72000. var filename;
  72001. // Checking if GLB loader is present
  72002. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72003. // Determine the device specific folder based on the ID suffix
  72004. var device = 'default';
  72005. if (this.id && !forceDefault) {
  72006. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72007. device = ((match && match[0]) || device);
  72008. }
  72009. // Hand
  72010. if (this.hand === 'left') {
  72011. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72012. }
  72013. else { // Right is the default if no hand is specified
  72014. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72015. }
  72016. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72017. }
  72018. else {
  72019. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72020. path = BABYLON.GenericController.MODEL_BASE_URL;
  72021. filename = BABYLON.GenericController.MODEL_FILENAME;
  72022. }
  72023. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72024. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72025. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72026. if (!_this._loadedMeshInfo) {
  72027. return;
  72028. }
  72029. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72030. _this.attachToMesh(_this._defaultModel);
  72031. if (meshLoaded) {
  72032. meshLoaded(_this._defaultModel);
  72033. }
  72034. }, null, function (scene, message) {
  72035. BABYLON.Tools.Log(message);
  72036. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72037. if (!forceDefault) {
  72038. _this.initControllerMesh(scene, meshLoaded, true);
  72039. }
  72040. });
  72041. };
  72042. /**
  72043. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72044. * can be transformed by button presses and axes values, based on this._mapping.
  72045. *
  72046. * @param scene scene in which the meshes exist
  72047. * @param meshes list of meshes that make up the controller model to process
  72048. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72049. */
  72050. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72051. var loadedMeshInfo = null;
  72052. // Create a new mesh to contain the glTF hierarchy
  72053. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72054. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72055. var childMesh = null;
  72056. for (var i = 0; i < meshes.length; i++) {
  72057. var mesh = meshes[i];
  72058. if (!mesh.parent) {
  72059. // Exclude controller meshes from picking results
  72060. mesh.isPickable = false;
  72061. // Handle root node, attach to the new parentMesh
  72062. childMesh = mesh;
  72063. break;
  72064. }
  72065. }
  72066. if (childMesh) {
  72067. childMesh.setParent(parentMesh);
  72068. // Create our mesh info. Note that this method will always return non-null.
  72069. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72070. }
  72071. else {
  72072. BABYLON.Tools.Warn('Could not find root node in model file.');
  72073. }
  72074. return loadedMeshInfo;
  72075. };
  72076. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72077. var loadedMeshInfo = new LoadedMeshInfo();
  72078. var i;
  72079. loadedMeshInfo.rootNode = rootNode;
  72080. // Reset the caches
  72081. loadedMeshInfo.buttonMeshes = {};
  72082. loadedMeshInfo.axisMeshes = {};
  72083. // Button Meshes
  72084. for (i = 0; i < this._mapping.buttons.length; i++) {
  72085. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72086. if (!buttonMeshName) {
  72087. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72088. continue;
  72089. }
  72090. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72091. if (!buttonMesh) {
  72092. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72093. continue;
  72094. }
  72095. var buttonMeshInfo = {
  72096. index: i,
  72097. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72098. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72099. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72100. };
  72101. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72102. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72103. }
  72104. else {
  72105. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72106. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72107. '(VALUE: ' + !!buttonMeshInfo.value +
  72108. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72109. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72110. ')');
  72111. }
  72112. }
  72113. // Axis Meshes
  72114. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72115. var axisMeshName = this._mapping.axisMeshNames[i];
  72116. if (!axisMeshName) {
  72117. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72118. continue;
  72119. }
  72120. var axisMesh = getChildByName(rootNode, axisMeshName);
  72121. if (!axisMesh) {
  72122. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72123. continue;
  72124. }
  72125. var axisMeshInfo = {
  72126. index: i,
  72127. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72128. min: getImmediateChildByName(axisMesh, 'MIN'),
  72129. max: getImmediateChildByName(axisMesh, 'MAX')
  72130. };
  72131. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72132. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72133. }
  72134. else {
  72135. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72136. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72137. '(VALUE: ' + !!axisMeshInfo.value +
  72138. ', MIN: ' + !!axisMeshInfo.min +
  72139. ', MAX:' + !!axisMeshInfo.max +
  72140. ')');
  72141. }
  72142. }
  72143. // Pointing Ray
  72144. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72145. if (!loadedMeshInfo.pointingPoseNode) {
  72146. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72147. }
  72148. return loadedMeshInfo;
  72149. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72150. function getChildByName(node, name) {
  72151. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72152. }
  72153. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72154. function getImmediateChildByName(node, name) {
  72155. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72156. }
  72157. };
  72158. /**
  72159. * Gets the ray of the controller in the direction the controller is pointing
  72160. * @param length the length the resulting ray should be
  72161. * @returns a ray in the direction the controller is pointing
  72162. */
  72163. WindowsMotionController.prototype.getForwardRay = function (length) {
  72164. if (length === void 0) { length = 100; }
  72165. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72166. return _super.prototype.getForwardRay.call(this, length);
  72167. }
  72168. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72169. var origin = m.getTranslation();
  72170. var forward = new BABYLON.Vector3(0, 0, -1);
  72171. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72172. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72173. return new BABYLON.Ray(origin, direction, length);
  72174. };
  72175. /**
  72176. * Disposes of the controller
  72177. */
  72178. WindowsMotionController.prototype.dispose = function () {
  72179. _super.prototype.dispose.call(this);
  72180. this.onTrackpadChangedObservable.clear();
  72181. };
  72182. /**
  72183. * The base url used to load the left and right controller models
  72184. */
  72185. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72186. /**
  72187. * The name of the left controller model file
  72188. */
  72189. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72190. /**
  72191. * The name of the right controller model file
  72192. */
  72193. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72194. /**
  72195. * The controller name prefix for this controller type
  72196. */
  72197. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72198. /**
  72199. * The controller id pattern for this controller type
  72200. */
  72201. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72202. return WindowsMotionController;
  72203. }(BABYLON.WebVRController));
  72204. BABYLON.WindowsMotionController = WindowsMotionController;
  72205. })(BABYLON || (BABYLON = {}));
  72206. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72207. var BABYLON;
  72208. (function (BABYLON) {
  72209. /**
  72210. * Gear VR Controller
  72211. */
  72212. var GearVRController = /** @class */ (function (_super) {
  72213. __extends(GearVRController, _super);
  72214. /**
  72215. * Creates a new GearVRController from a gamepad
  72216. * @param vrGamepad the gamepad that the controller should be created from
  72217. */
  72218. function GearVRController(vrGamepad) {
  72219. var _this = _super.call(this, vrGamepad) || this;
  72220. _this._buttonIndexToObservableNameMap = [
  72221. 'onTrackpadChangedObservable',
  72222. 'onTriggerStateChangedObservable' // Trigger
  72223. ];
  72224. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72225. return _this;
  72226. }
  72227. /**
  72228. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72229. * @param scene scene in which to add meshes
  72230. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72231. */
  72232. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72233. var _this = this;
  72234. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72235. _this._defaultModel = newMeshes[1];
  72236. _this.attachToMesh(_this._defaultModel);
  72237. if (meshLoaded) {
  72238. meshLoaded(_this._defaultModel);
  72239. }
  72240. });
  72241. };
  72242. /**
  72243. * Called once for each button that changed state since the last frame
  72244. * @param buttonIdx Which button index changed
  72245. * @param state New state of the button
  72246. * @param changes Which properties on the state changed since last frame
  72247. */
  72248. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72249. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72250. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72251. // Only emit events for buttons that we know how to map from index to observable
  72252. var observable = this[observableName];
  72253. if (observable) {
  72254. observable.notifyObservers(state);
  72255. }
  72256. }
  72257. };
  72258. /**
  72259. * Base Url for the controller model.
  72260. */
  72261. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72262. /**
  72263. * File name for the controller model.
  72264. */
  72265. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72266. /**
  72267. * Gamepad Id prefix used to identify this controller.
  72268. */
  72269. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72270. return GearVRController;
  72271. }(BABYLON.WebVRController));
  72272. BABYLON.GearVRController = GearVRController;
  72273. })(BABYLON || (BABYLON = {}));
  72274. //# sourceMappingURL=babylon.gearVRController.js.map
  72275. var BABYLON;
  72276. (function (BABYLON) {
  72277. /**
  72278. * Google Daydream controller
  72279. */
  72280. var DaydreamController = /** @class */ (function (_super) {
  72281. __extends(DaydreamController, _super);
  72282. /**
  72283. * Creates a new DaydreamController from a gamepad
  72284. * @param vrGamepad the gamepad that the controller should be created from
  72285. */
  72286. function DaydreamController(vrGamepad) {
  72287. var _this = _super.call(this, vrGamepad) || this;
  72288. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72289. return _this;
  72290. }
  72291. /**
  72292. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72293. * @param scene scene in which to add meshes
  72294. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72295. */
  72296. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72297. var _this = this;
  72298. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72299. _this._defaultModel = newMeshes[1];
  72300. _this.attachToMesh(_this._defaultModel);
  72301. if (meshLoaded) {
  72302. meshLoaded(_this._defaultModel);
  72303. }
  72304. });
  72305. };
  72306. /**
  72307. * Called once for each button that changed state since the last frame
  72308. * @param buttonIdx Which button index changed
  72309. * @param state New state of the button
  72310. * @param changes Which properties on the state changed since last frame
  72311. */
  72312. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72313. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72314. if (buttonIdx === 0) {
  72315. var observable = this.onTriggerStateChangedObservable;
  72316. if (observable) {
  72317. observable.notifyObservers(state);
  72318. }
  72319. }
  72320. else {
  72321. // If the app or home buttons are ever made available
  72322. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72323. }
  72324. };
  72325. /**
  72326. * Base Url for the controller model.
  72327. */
  72328. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72329. /**
  72330. * File name for the controller model.
  72331. */
  72332. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72333. /**
  72334. * Gamepad Id prefix used to identify Daydream Controller.
  72335. */
  72336. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72337. return DaydreamController;
  72338. }(BABYLON.WebVRController));
  72339. BABYLON.DaydreamController = DaydreamController;
  72340. })(BABYLON || (BABYLON = {}));
  72341. //# sourceMappingURL=babylon.daydreamController.js.map
  72342. var BABYLON;
  72343. (function (BABYLON) {
  72344. var FollowCamera = /** @class */ (function (_super) {
  72345. __extends(FollowCamera, _super);
  72346. function FollowCamera(name, position, scene, lockedTarget) {
  72347. if (lockedTarget === void 0) { lockedTarget = null; }
  72348. var _this = _super.call(this, name, position, scene) || this;
  72349. _this.radius = 12;
  72350. _this.rotationOffset = 0;
  72351. _this.heightOffset = 4;
  72352. _this.cameraAcceleration = 0.05;
  72353. _this.maxCameraSpeed = 20;
  72354. _this.lockedTarget = lockedTarget;
  72355. return _this;
  72356. }
  72357. FollowCamera.prototype.getRadians = function (degrees) {
  72358. return degrees * Math.PI / 180;
  72359. };
  72360. FollowCamera.prototype.follow = function (cameraTarget) {
  72361. if (!cameraTarget)
  72362. return;
  72363. var yRotation;
  72364. if (cameraTarget.rotationQuaternion) {
  72365. var rotMatrix = new BABYLON.Matrix();
  72366. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72367. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72368. }
  72369. else {
  72370. yRotation = cameraTarget.rotation.y;
  72371. }
  72372. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72373. var targetPosition = cameraTarget.getAbsolutePosition();
  72374. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  72375. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  72376. var dx = targetX - this.position.x;
  72377. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  72378. var dz = (targetZ) - this.position.z;
  72379. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  72380. var vy = dy * this.cameraAcceleration;
  72381. var vz = dz * this.cameraAcceleration * 2;
  72382. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  72383. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72384. }
  72385. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  72386. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72387. }
  72388. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  72389. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  72390. }
  72391. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  72392. this.setTarget(targetPosition);
  72393. };
  72394. FollowCamera.prototype._checkInputs = function () {
  72395. _super.prototype._checkInputs.call(this);
  72396. if (this.lockedTarget) {
  72397. this.follow(this.lockedTarget);
  72398. }
  72399. };
  72400. FollowCamera.prototype.getClassName = function () {
  72401. return "FollowCamera";
  72402. };
  72403. __decorate([
  72404. BABYLON.serialize()
  72405. ], FollowCamera.prototype, "radius", void 0);
  72406. __decorate([
  72407. BABYLON.serialize()
  72408. ], FollowCamera.prototype, "rotationOffset", void 0);
  72409. __decorate([
  72410. BABYLON.serialize()
  72411. ], FollowCamera.prototype, "heightOffset", void 0);
  72412. __decorate([
  72413. BABYLON.serialize()
  72414. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  72415. __decorate([
  72416. BABYLON.serialize()
  72417. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  72418. __decorate([
  72419. BABYLON.serializeAsMeshReference("lockedTargetId")
  72420. ], FollowCamera.prototype, "lockedTarget", void 0);
  72421. return FollowCamera;
  72422. }(BABYLON.TargetCamera));
  72423. BABYLON.FollowCamera = FollowCamera;
  72424. var ArcFollowCamera = /** @class */ (function (_super) {
  72425. __extends(ArcFollowCamera, _super);
  72426. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  72427. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  72428. _this.alpha = alpha;
  72429. _this.beta = beta;
  72430. _this.radius = radius;
  72431. _this.target = target;
  72432. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  72433. _this.follow();
  72434. return _this;
  72435. }
  72436. ArcFollowCamera.prototype.follow = function () {
  72437. if (!this.target) {
  72438. return;
  72439. }
  72440. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  72441. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  72442. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  72443. var targetPosition = this.target.getAbsolutePosition();
  72444. this.position = targetPosition.add(this._cartesianCoordinates);
  72445. this.setTarget(targetPosition);
  72446. };
  72447. ArcFollowCamera.prototype._checkInputs = function () {
  72448. _super.prototype._checkInputs.call(this);
  72449. this.follow();
  72450. };
  72451. ArcFollowCamera.prototype.getClassName = function () {
  72452. return "ArcFollowCamera";
  72453. };
  72454. return ArcFollowCamera;
  72455. }(BABYLON.TargetCamera));
  72456. BABYLON.ArcFollowCamera = ArcFollowCamera;
  72457. })(BABYLON || (BABYLON = {}));
  72458. //# sourceMappingURL=babylon.followCamera.js.map
  72459. var BABYLON;
  72460. (function (BABYLON) {
  72461. // We're mainly based on the logic defined into the FreeCamera code
  72462. var UniversalCamera = /** @class */ (function (_super) {
  72463. __extends(UniversalCamera, _super);
  72464. //-- end properties for backward compatibility for inputs
  72465. function UniversalCamera(name, position, scene) {
  72466. var _this = _super.call(this, name, position, scene) || this;
  72467. _this.inputs.addGamepad();
  72468. return _this;
  72469. }
  72470. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  72471. //-- Begin properties for backward compatibility for inputs
  72472. get: function () {
  72473. var gamepad = this.inputs.attached["gamepad"];
  72474. if (gamepad)
  72475. return gamepad.gamepadAngularSensibility;
  72476. return 0;
  72477. },
  72478. set: function (value) {
  72479. var gamepad = this.inputs.attached["gamepad"];
  72480. if (gamepad)
  72481. gamepad.gamepadAngularSensibility = value;
  72482. },
  72483. enumerable: true,
  72484. configurable: true
  72485. });
  72486. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  72487. get: function () {
  72488. var gamepad = this.inputs.attached["gamepad"];
  72489. if (gamepad)
  72490. return gamepad.gamepadMoveSensibility;
  72491. return 0;
  72492. },
  72493. set: function (value) {
  72494. var gamepad = this.inputs.attached["gamepad"];
  72495. if (gamepad)
  72496. gamepad.gamepadMoveSensibility = value;
  72497. },
  72498. enumerable: true,
  72499. configurable: true
  72500. });
  72501. UniversalCamera.prototype.getClassName = function () {
  72502. return "UniversalCamera";
  72503. };
  72504. return UniversalCamera;
  72505. }(BABYLON.TouchCamera));
  72506. BABYLON.UniversalCamera = UniversalCamera;
  72507. })(BABYLON || (BABYLON = {}));
  72508. //# sourceMappingURL=babylon.universalCamera.js.map
  72509. var BABYLON;
  72510. (function (BABYLON) {
  72511. // We're mainly based on the logic defined into the FreeCamera code
  72512. var GamepadCamera = /** @class */ (function (_super) {
  72513. __extends(GamepadCamera, _super);
  72514. //-- end properties for backward compatibility for inputs
  72515. function GamepadCamera(name, position, scene) {
  72516. return _super.call(this, name, position, scene) || this;
  72517. }
  72518. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  72519. //-- Begin properties for backward compatibility for inputs
  72520. get: function () {
  72521. var gamepad = this.inputs.attached["gamepad"];
  72522. if (gamepad)
  72523. return gamepad.gamepadAngularSensibility;
  72524. return 0;
  72525. },
  72526. set: function (value) {
  72527. var gamepad = this.inputs.attached["gamepad"];
  72528. if (gamepad)
  72529. gamepad.gamepadAngularSensibility = value;
  72530. },
  72531. enumerable: true,
  72532. configurable: true
  72533. });
  72534. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  72535. get: function () {
  72536. var gamepad = this.inputs.attached["gamepad"];
  72537. if (gamepad)
  72538. return gamepad.gamepadMoveSensibility;
  72539. return 0;
  72540. },
  72541. set: function (value) {
  72542. var gamepad = this.inputs.attached["gamepad"];
  72543. if (gamepad)
  72544. gamepad.gamepadMoveSensibility = value;
  72545. },
  72546. enumerable: true,
  72547. configurable: true
  72548. });
  72549. GamepadCamera.prototype.getClassName = function () {
  72550. return "GamepadCamera";
  72551. };
  72552. return GamepadCamera;
  72553. }(BABYLON.UniversalCamera));
  72554. BABYLON.GamepadCamera = GamepadCamera;
  72555. })(BABYLON || (BABYLON = {}));
  72556. //# sourceMappingURL=babylon.gamepadCamera.js.map
  72557. var BABYLON;
  72558. (function (BABYLON) {
  72559. var PostProcessRenderPipelineManager = /** @class */ (function () {
  72560. function PostProcessRenderPipelineManager() {
  72561. this._renderPipelines = {};
  72562. }
  72563. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  72564. this._renderPipelines[renderPipeline._name] = renderPipeline;
  72565. };
  72566. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  72567. if (unique === void 0) { unique = false; }
  72568. var renderPipeline = this._renderPipelines[renderPipelineName];
  72569. if (!renderPipeline) {
  72570. return;
  72571. }
  72572. renderPipeline._attachCameras(cameras, unique);
  72573. };
  72574. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  72575. var renderPipeline = this._renderPipelines[renderPipelineName];
  72576. if (!renderPipeline) {
  72577. return;
  72578. }
  72579. renderPipeline._detachCameras(cameras);
  72580. };
  72581. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72582. var renderPipeline = this._renderPipelines[renderPipelineName];
  72583. if (!renderPipeline) {
  72584. return;
  72585. }
  72586. renderPipeline._enableEffect(renderEffectName, cameras);
  72587. };
  72588. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  72589. var renderPipeline = this._renderPipelines[renderPipelineName];
  72590. if (!renderPipeline) {
  72591. return;
  72592. }
  72593. renderPipeline._disableEffect(renderEffectName, cameras);
  72594. };
  72595. PostProcessRenderPipelineManager.prototype.update = function () {
  72596. for (var renderPipelineName in this._renderPipelines) {
  72597. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72598. var pipeline = this._renderPipelines[renderPipelineName];
  72599. if (!pipeline.isSupported) {
  72600. pipeline.dispose();
  72601. delete this._renderPipelines[renderPipelineName];
  72602. }
  72603. else {
  72604. pipeline._update();
  72605. }
  72606. }
  72607. }
  72608. };
  72609. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  72610. for (var renderPipelineName in this._renderPipelines) {
  72611. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72612. var pipeline = this._renderPipelines[renderPipelineName];
  72613. pipeline._rebuild();
  72614. }
  72615. }
  72616. };
  72617. PostProcessRenderPipelineManager.prototype.dispose = function () {
  72618. for (var renderPipelineName in this._renderPipelines) {
  72619. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  72620. var pipeline = this._renderPipelines[renderPipelineName];
  72621. pipeline.dispose();
  72622. }
  72623. }
  72624. };
  72625. return PostProcessRenderPipelineManager;
  72626. }());
  72627. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  72628. })(BABYLON || (BABYLON = {}));
  72629. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  72630. var BABYLON;
  72631. (function (BABYLON) {
  72632. /**
  72633. * This represents a set of one or more post processes in Babylon.
  72634. * A post process can be used to apply a shader to a texture after it is rendered.
  72635. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  72636. */
  72637. var PostProcessRenderEffect = /** @class */ (function () {
  72638. /**
  72639. * Instantiates a post process render effect.
  72640. * A post process can be used to apply a shader to a texture after it is rendered.
  72641. * @param engine The engine the effect is tied to
  72642. * @param name The name of the effect
  72643. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  72644. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  72645. */
  72646. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  72647. this._name = name;
  72648. this._singleInstance = singleInstance || true;
  72649. this._getPostProcesses = getPostProcesses;
  72650. this._cameras = {};
  72651. this._indicesForCamera = {};
  72652. this._postProcesses = {};
  72653. }
  72654. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  72655. /**
  72656. * Checks if all the post processes in the effect are supported.
  72657. */
  72658. get: function () {
  72659. for (var index in this._postProcesses) {
  72660. if (this._postProcesses.hasOwnProperty(index)) {
  72661. var pps = this._postProcesses[index];
  72662. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  72663. if (!pps[ppIndex].isSupported) {
  72664. return false;
  72665. }
  72666. }
  72667. }
  72668. }
  72669. return true;
  72670. },
  72671. enumerable: true,
  72672. configurable: true
  72673. });
  72674. /**
  72675. * Updates the current state of the effect
  72676. */
  72677. PostProcessRenderEffect.prototype._update = function () {
  72678. };
  72679. /**
  72680. * Attaches the effect on cameras
  72681. * @param cameras The camera to attach to.
  72682. */
  72683. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  72684. var _this = this;
  72685. var cameraKey;
  72686. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72687. if (!cams) {
  72688. return;
  72689. }
  72690. for (var i = 0; i < cams.length; i++) {
  72691. var camera = cams[i];
  72692. var cameraName = camera.name;
  72693. if (this._singleInstance) {
  72694. cameraKey = 0;
  72695. }
  72696. else {
  72697. cameraKey = cameraName;
  72698. }
  72699. if (!this._postProcesses[cameraKey]) {
  72700. var postProcess = this._getPostProcesses();
  72701. if (postProcess) {
  72702. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  72703. }
  72704. }
  72705. if (!this._indicesForCamera[cameraName]) {
  72706. this._indicesForCamera[cameraName] = [];
  72707. }
  72708. this._postProcesses[cameraKey].forEach(function (postProcess) {
  72709. var index = camera.attachPostProcess(postProcess);
  72710. _this._indicesForCamera[cameraName].push(index);
  72711. });
  72712. if (!this._cameras[cameraName]) {
  72713. this._cameras[cameraName] = camera;
  72714. }
  72715. }
  72716. };
  72717. /**
  72718. * Detatches the effect on cameras
  72719. * @param cameras The camera to detatch from.
  72720. */
  72721. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  72722. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72723. if (!cams) {
  72724. return;
  72725. }
  72726. for (var i = 0; i < cams.length; i++) {
  72727. var camera = cams[i];
  72728. var cameraName = camera.name;
  72729. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72730. camera.detachPostProcess(postProcess);
  72731. });
  72732. if (this._cameras[cameraName]) {
  72733. //this._indicesForCamera.splice(index, 1);
  72734. this._cameras[cameraName] = null;
  72735. }
  72736. }
  72737. };
  72738. /**
  72739. * Enables the effect on given cameras
  72740. * @param cameras The camera to enable.
  72741. */
  72742. PostProcessRenderEffect.prototype._enable = function (cameras) {
  72743. var _this = this;
  72744. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72745. if (!cams) {
  72746. return;
  72747. }
  72748. for (var i = 0; i < cams.length; i++) {
  72749. var camera = cams[i];
  72750. var cameraName = camera.name;
  72751. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  72752. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  72753. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72754. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  72755. });
  72756. }
  72757. }
  72758. }
  72759. };
  72760. /**
  72761. * Disables the effect on the given cameras
  72762. * @param cameras The camera to disable.
  72763. */
  72764. PostProcessRenderEffect.prototype._disable = function (cameras) {
  72765. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72766. if (!cams) {
  72767. return;
  72768. }
  72769. for (var i = 0; i < cams.length; i++) {
  72770. var camera = cams[i];
  72771. var cameraName = camera.name;
  72772. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  72773. camera.detachPostProcess(postProcess);
  72774. });
  72775. }
  72776. };
  72777. /**
  72778. * Gets a list of the post processes contained in the effect.
  72779. * @param camera The camera to get the post processes on.
  72780. * @returns The list of the post processes in the effect.
  72781. */
  72782. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  72783. if (this._singleInstance) {
  72784. return this._postProcesses[0];
  72785. }
  72786. else {
  72787. if (!camera) {
  72788. return null;
  72789. }
  72790. return this._postProcesses[camera.name];
  72791. }
  72792. };
  72793. return PostProcessRenderEffect;
  72794. }());
  72795. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  72796. })(BABYLON || (BABYLON = {}));
  72797. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  72798. var BABYLON;
  72799. (function (BABYLON) {
  72800. var PostProcessRenderPipeline = /** @class */ (function () {
  72801. function PostProcessRenderPipeline(engine, name) {
  72802. this.engine = engine;
  72803. this._name = name;
  72804. this._renderEffects = {};
  72805. this._renderEffectsForIsolatedPass = new Array();
  72806. this._cameras = [];
  72807. }
  72808. PostProcessRenderPipeline.prototype.getClassName = function () {
  72809. return "PostProcessRenderPipeline";
  72810. };
  72811. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  72812. get: function () {
  72813. for (var renderEffectName in this._renderEffects) {
  72814. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72815. if (!this._renderEffects[renderEffectName].isSupported) {
  72816. return false;
  72817. }
  72818. }
  72819. }
  72820. return true;
  72821. },
  72822. enumerable: true,
  72823. configurable: true
  72824. });
  72825. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  72826. this._renderEffects[renderEffect._name] = renderEffect;
  72827. };
  72828. // private
  72829. PostProcessRenderPipeline.prototype._rebuild = function () {
  72830. };
  72831. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  72832. var renderEffects = this._renderEffects[renderEffectName];
  72833. if (!renderEffects) {
  72834. return;
  72835. }
  72836. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72837. };
  72838. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  72839. var renderEffects = this._renderEffects[renderEffectName];
  72840. if (!renderEffects) {
  72841. return;
  72842. }
  72843. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  72844. };
  72845. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  72846. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72847. if (!cams) {
  72848. return;
  72849. }
  72850. var indicesToDelete = [];
  72851. var i;
  72852. for (i = 0; i < cams.length; i++) {
  72853. var camera = cams[i];
  72854. var cameraName = camera.name;
  72855. if (this._cameras.indexOf(camera) === -1) {
  72856. this._cameras[cameraName] = camera;
  72857. }
  72858. else if (unique) {
  72859. indicesToDelete.push(i);
  72860. }
  72861. }
  72862. for (i = 0; i < indicesToDelete.length; i++) {
  72863. cameras.splice(indicesToDelete[i], 1);
  72864. }
  72865. for (var renderEffectName in this._renderEffects) {
  72866. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72867. this._renderEffects[renderEffectName]._attachCameras(cams);
  72868. }
  72869. }
  72870. };
  72871. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  72872. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  72873. if (!cams) {
  72874. return;
  72875. }
  72876. for (var renderEffectName in this._renderEffects) {
  72877. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72878. this._renderEffects[renderEffectName]._detachCameras(cams);
  72879. }
  72880. }
  72881. for (var i = 0; i < cams.length; i++) {
  72882. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  72883. }
  72884. };
  72885. PostProcessRenderPipeline.prototype._update = function () {
  72886. for (var renderEffectName in this._renderEffects) {
  72887. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  72888. this._renderEffects[renderEffectName]._update();
  72889. }
  72890. }
  72891. for (var i = 0; i < this._cameras.length; i++) {
  72892. var cameraName = this._cameras[i].name;
  72893. if (this._renderEffectsForIsolatedPass[cameraName]) {
  72894. this._renderEffectsForIsolatedPass[cameraName]._update();
  72895. }
  72896. }
  72897. };
  72898. PostProcessRenderPipeline.prototype._reset = function () {
  72899. this._renderEffects = {};
  72900. this._renderEffectsForIsolatedPass = new Array();
  72901. };
  72902. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  72903. // 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)
  72904. var effectKeys = Object.keys(this._renderEffects);
  72905. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  72906. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  72907. if (postProcesses) {
  72908. postProcesses[0].samples = sampleCount;
  72909. return true;
  72910. }
  72911. }
  72912. return false;
  72913. };
  72914. PostProcessRenderPipeline.prototype.dispose = function () {
  72915. // Must be implemented by children
  72916. };
  72917. __decorate([
  72918. BABYLON.serialize()
  72919. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  72920. return PostProcessRenderPipeline;
  72921. }());
  72922. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  72923. })(BABYLON || (BABYLON = {}));
  72924. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  72925. var BABYLON;
  72926. (function (BABYLON) {
  72927. /**
  72928. * This represents a depth renderer in Babylon.
  72929. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  72930. */
  72931. var DepthRenderer = /** @class */ (function () {
  72932. /**
  72933. * Instantiates a depth renderer
  72934. * @param scene The scene the renderer belongs to
  72935. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  72936. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  72937. */
  72938. function DepthRenderer(scene, type, camera) {
  72939. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  72940. if (camera === void 0) { camera = null; }
  72941. var _this = this;
  72942. this._scene = scene;
  72943. this._camera = camera;
  72944. var engine = scene.getEngine();
  72945. // Render target
  72946. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  72947. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72948. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  72949. this._depthMap.refreshRate = 1;
  72950. this._depthMap.renderParticles = false;
  72951. this._depthMap.renderList = null;
  72952. // Camera to get depth map from to support multiple concurrent cameras
  72953. this._depthMap.activeCamera = this._camera;
  72954. this._depthMap.ignoreCameraViewport = true;
  72955. this._depthMap.useCameraPostProcesses = false;
  72956. // set default depth value to 1.0 (far away)
  72957. this._depthMap.onClearObservable.add(function (engine) {
  72958. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  72959. });
  72960. // Custom render function
  72961. var renderSubMesh = function (subMesh) {
  72962. var mesh = subMesh.getRenderingMesh();
  72963. var scene = _this._scene;
  72964. var engine = scene.getEngine();
  72965. var material = subMesh.getMaterial();
  72966. if (!material) {
  72967. return;
  72968. }
  72969. // Culling and reverse (right handed system)
  72970. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  72971. // Managing instances
  72972. var batch = mesh._getInstancesRenderList(subMesh._id);
  72973. if (batch.mustReturn) {
  72974. return;
  72975. }
  72976. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  72977. var camera = _this._camera || scene.activeCamera;
  72978. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  72979. engine.enableEffect(_this._effect);
  72980. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  72981. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  72982. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  72983. // Alpha test
  72984. if (material && material.needAlphaTesting()) {
  72985. var alphaTexture = material.getAlphaTestTexture();
  72986. if (alphaTexture) {
  72987. _this._effect.setTexture("diffuseSampler", alphaTexture);
  72988. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  72989. }
  72990. }
  72991. // Bones
  72992. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  72993. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  72994. }
  72995. // Draw
  72996. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  72997. }
  72998. };
  72999. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73000. var index;
  73001. if (depthOnlySubMeshes.length) {
  73002. engine.setColorWrite(false);
  73003. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73004. renderSubMesh(depthOnlySubMeshes.data[index]);
  73005. }
  73006. engine.setColorWrite(true);
  73007. }
  73008. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73009. renderSubMesh(opaqueSubMeshes.data[index]);
  73010. }
  73011. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73012. renderSubMesh(alphaTestSubMeshes.data[index]);
  73013. }
  73014. };
  73015. }
  73016. /**
  73017. * Creates the depth rendering effect and checks if the effect is ready.
  73018. * @param subMesh The submesh to be used to render the depth map of
  73019. * @param useInstances If multiple world instances should be used
  73020. * @returns if the depth renderer is ready to render the depth map
  73021. */
  73022. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73023. var material = subMesh.getMaterial();
  73024. if (material.disableDepthWrite) {
  73025. return false;
  73026. }
  73027. var defines = [];
  73028. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73029. var mesh = subMesh.getMesh();
  73030. // Alpha test
  73031. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73032. defines.push("#define ALPHATEST");
  73033. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73034. attribs.push(BABYLON.VertexBuffer.UVKind);
  73035. defines.push("#define UV1");
  73036. }
  73037. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73038. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73039. defines.push("#define UV2");
  73040. }
  73041. }
  73042. // Bones
  73043. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73044. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73045. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73046. if (mesh.numBoneInfluencers > 4) {
  73047. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73048. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73049. }
  73050. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73051. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73052. }
  73053. else {
  73054. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73055. }
  73056. // Instances
  73057. if (useInstances) {
  73058. defines.push("#define INSTANCES");
  73059. attribs.push("world0");
  73060. attribs.push("world1");
  73061. attribs.push("world2");
  73062. attribs.push("world3");
  73063. }
  73064. // Get correct effect
  73065. var join = defines.join("\n");
  73066. if (this._cachedDefines !== join) {
  73067. this._cachedDefines = join;
  73068. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73069. }
  73070. return this._effect.isReady();
  73071. };
  73072. /**
  73073. * Gets the texture which the depth map will be written to.
  73074. * @returns The depth map texture
  73075. */
  73076. DepthRenderer.prototype.getDepthMap = function () {
  73077. return this._depthMap;
  73078. };
  73079. /**
  73080. * Disposes of the depth renderer.
  73081. */
  73082. DepthRenderer.prototype.dispose = function () {
  73083. this._depthMap.dispose();
  73084. };
  73085. return DepthRenderer;
  73086. }());
  73087. BABYLON.DepthRenderer = DepthRenderer;
  73088. })(BABYLON || (BABYLON = {}));
  73089. //# sourceMappingURL=babylon.depthRenderer.js.map
  73090. var BABYLON;
  73091. (function (BABYLON) {
  73092. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73093. __extends(SSAORenderingPipeline, _super);
  73094. /**
  73095. * @constructor
  73096. * @param {string} name - The rendering pipeline name
  73097. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73098. * @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 }
  73099. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73100. */
  73101. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73102. var _this = _super.call(this, scene.getEngine(), name) || this;
  73103. // Members
  73104. /**
  73105. * The PassPostProcess id in the pipeline that contains the original scene color
  73106. */
  73107. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73108. /**
  73109. * The SSAO PostProcess id in the pipeline
  73110. */
  73111. _this.SSAORenderEffect = "SSAORenderEffect";
  73112. /**
  73113. * The horizontal blur PostProcess id in the pipeline
  73114. */
  73115. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73116. /**
  73117. * The vertical blur PostProcess id in the pipeline
  73118. */
  73119. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73120. /**
  73121. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73122. */
  73123. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73124. /**
  73125. * The output strength of the SSAO post-process. Default value is 1.0.
  73126. */
  73127. _this.totalStrength = 1.0;
  73128. /**
  73129. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73130. */
  73131. _this.radius = 0.0001;
  73132. /**
  73133. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73134. * Must not be equal to fallOff and superior to fallOff.
  73135. * Default value is 0.975
  73136. */
  73137. _this.area = 0.0075;
  73138. /**
  73139. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73140. * Must not be equal to area and inferior to area.
  73141. * Default value is 0.0
  73142. */
  73143. _this.fallOff = 0.000001;
  73144. /**
  73145. * The base color of the SSAO post-process
  73146. * The final result is "base + ssao" between [0, 1]
  73147. */
  73148. _this.base = 0.5;
  73149. _this._firstUpdate = true;
  73150. _this._scene = scene;
  73151. // Set up assets
  73152. _this._createRandomTexture();
  73153. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73154. var ssaoRatio = ratio.ssaoRatio || ratio;
  73155. var combineRatio = ratio.combineRatio || ratio;
  73156. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73157. _this._createSSAOPostProcess(ssaoRatio);
  73158. _this._createBlurPostProcess(ssaoRatio);
  73159. _this._createSSAOCombinePostProcess(combineRatio);
  73160. // Set up pipeline
  73161. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73162. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73163. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73164. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73165. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73166. // Finish
  73167. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73168. if (cameras)
  73169. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73170. return _this;
  73171. }
  73172. // Public Methods
  73173. /**
  73174. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73175. */
  73176. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73177. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73178. for (var i = 0; i < this._scene.cameras.length; i++) {
  73179. var camera = this._scene.cameras[i];
  73180. this._originalColorPostProcess.dispose(camera);
  73181. this._ssaoPostProcess.dispose(camera);
  73182. this._blurHPostProcess.dispose(camera);
  73183. this._blurVPostProcess.dispose(camera);
  73184. this._ssaoCombinePostProcess.dispose(camera);
  73185. }
  73186. this._randomTexture.dispose();
  73187. if (disableDepthRender)
  73188. this._scene.disableDepthRenderer();
  73189. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73190. _super.prototype.dispose.call(this);
  73191. };
  73192. // Private Methods
  73193. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73194. var _this = this;
  73195. var size = 16;
  73196. 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);
  73197. 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);
  73198. this._blurHPostProcess.onActivateObservable.add(function () {
  73199. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73200. _this._blurHPostProcess.kernel = size * dw;
  73201. });
  73202. this._blurVPostProcess.onActivateObservable.add(function () {
  73203. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73204. _this._blurVPostProcess.kernel = size * dw;
  73205. });
  73206. };
  73207. SSAORenderingPipeline.prototype._rebuild = function () {
  73208. this._firstUpdate = true;
  73209. _super.prototype._rebuild.call(this);
  73210. };
  73211. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73212. var _this = this;
  73213. var numSamples = 16;
  73214. var sampleSphere = [
  73215. 0.5381, 0.1856, -0.4319,
  73216. 0.1379, 0.2486, 0.4430,
  73217. 0.3371, 0.5679, -0.0057,
  73218. -0.6999, -0.0451, -0.0019,
  73219. 0.0689, -0.1598, -0.8547,
  73220. 0.0560, 0.0069, -0.1843,
  73221. -0.0146, 0.1402, 0.0762,
  73222. 0.0100, -0.1924, -0.0344,
  73223. -0.3577, -0.5301, -0.4358,
  73224. -0.3169, 0.1063, 0.0158,
  73225. 0.0103, -0.5869, 0.0046,
  73226. -0.0897, -0.4940, 0.3287,
  73227. 0.7119, -0.0154, -0.0918,
  73228. -0.0533, 0.0596, -0.5411,
  73229. 0.0352, -0.0631, 0.5460,
  73230. -0.4776, 0.2847, -0.0271
  73231. ];
  73232. var samplesFactor = 1.0 / numSamples;
  73233. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73234. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73235. "area", "fallOff", "base", "range", "viewport"
  73236. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73237. this._ssaoPostProcess.onApply = function (effect) {
  73238. if (_this._firstUpdate) {
  73239. effect.setArray3("sampleSphere", sampleSphere);
  73240. effect.setFloat("samplesFactor", samplesFactor);
  73241. effect.setFloat("randTextureTiles", 4.0);
  73242. }
  73243. effect.setFloat("totalStrength", _this.totalStrength);
  73244. effect.setFloat("radius", _this.radius);
  73245. effect.setFloat("area", _this.area);
  73246. effect.setFloat("fallOff", _this.fallOff);
  73247. effect.setFloat("base", _this.base);
  73248. effect.setTexture("textureSampler", _this._depthTexture);
  73249. effect.setTexture("randomSampler", _this._randomTexture);
  73250. };
  73251. };
  73252. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73253. var _this = this;
  73254. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73255. this._ssaoCombinePostProcess.onApply = function (effect) {
  73256. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73257. };
  73258. };
  73259. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73260. var size = 512;
  73261. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73262. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73263. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73264. var context = this._randomTexture.getContext();
  73265. var rand = function (min, max) {
  73266. return Math.random() * (max - min) + min;
  73267. };
  73268. var randVector = BABYLON.Vector3.Zero();
  73269. for (var x = 0; x < size; x++) {
  73270. for (var y = 0; y < size; y++) {
  73271. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73272. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73273. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73274. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73275. context.fillRect(x, y, 1, 1);
  73276. }
  73277. }
  73278. this._randomTexture.update(false);
  73279. };
  73280. __decorate([
  73281. BABYLON.serialize()
  73282. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73283. __decorate([
  73284. BABYLON.serialize()
  73285. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73286. __decorate([
  73287. BABYLON.serialize()
  73288. ], SSAORenderingPipeline.prototype, "area", void 0);
  73289. __decorate([
  73290. BABYLON.serialize()
  73291. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73292. __decorate([
  73293. BABYLON.serialize()
  73294. ], SSAORenderingPipeline.prototype, "base", void 0);
  73295. return SSAORenderingPipeline;
  73296. }(BABYLON.PostProcessRenderPipeline));
  73297. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73298. })(BABYLON || (BABYLON = {}));
  73299. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73300. var BABYLON;
  73301. (function (BABYLON) {
  73302. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73303. __extends(SSAO2RenderingPipeline, _super);
  73304. /**
  73305. * @constructor
  73306. * @param {string} name - The rendering pipeline name
  73307. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73308. * @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 }
  73309. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73310. */
  73311. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73312. var _this = _super.call(this, scene.getEngine(), name) || this;
  73313. // Members
  73314. /**
  73315. * The PassPostProcess id in the pipeline that contains the original scene color
  73316. */
  73317. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73318. /**
  73319. * The SSAO PostProcess id in the pipeline
  73320. */
  73321. _this.SSAORenderEffect = "SSAORenderEffect";
  73322. /**
  73323. * The horizontal blur PostProcess id in the pipeline
  73324. */
  73325. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73326. /**
  73327. * The vertical blur PostProcess id in the pipeline
  73328. */
  73329. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73330. /**
  73331. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73332. */
  73333. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73334. /**
  73335. * The output strength of the SSAO post-process. Default value is 1.0.
  73336. */
  73337. _this.totalStrength = 1.0;
  73338. /**
  73339. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73340. */
  73341. _this.maxZ = 100.0;
  73342. /**
  73343. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73344. */
  73345. _this.minZAspect = 0.2;
  73346. /**
  73347. * Number of samples used for the SSAO calculations. Default value is 8
  73348. */
  73349. _this._samples = 8;
  73350. /**
  73351. * Are we using bilateral blur ?
  73352. */
  73353. _this._expensiveBlur = true;
  73354. /**
  73355. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73356. */
  73357. _this.radius = 2.0;
  73358. /**
  73359. * The base color of the SSAO post-process
  73360. * The final result is "base + ssao" between [0, 1]
  73361. */
  73362. _this.base = 0.1;
  73363. _this._firstUpdate = true;
  73364. _this._scene = scene;
  73365. _this._ratio = ratio;
  73366. if (!_this.isSupported) {
  73367. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73368. return _this;
  73369. }
  73370. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73371. var blurRatio = _this._ratio.blurRatio || ratio;
  73372. // Set up assets
  73373. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  73374. _this._createRandomTexture();
  73375. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  73376. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  73377. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73378. _this._createSSAOPostProcess(1.0);
  73379. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  73380. _this._createSSAOCombinePostProcess(blurRatio);
  73381. // Set up pipeline
  73382. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73383. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73384. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73385. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73386. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73387. // Finish
  73388. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73389. if (cameras)
  73390. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73391. return _this;
  73392. }
  73393. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  73394. get: function () {
  73395. return this._samples;
  73396. },
  73397. set: function (n) {
  73398. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  73399. this._samples = n;
  73400. this._sampleSphere = this._generateHemisphere();
  73401. this._firstUpdate = true;
  73402. },
  73403. enumerable: true,
  73404. configurable: true
  73405. });
  73406. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  73407. get: function () {
  73408. return this._expensiveBlur;
  73409. },
  73410. set: function (b) {
  73411. 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"]);
  73412. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  73413. this._expensiveBlur = b;
  73414. this._firstUpdate = true;
  73415. },
  73416. enumerable: true,
  73417. configurable: true
  73418. });
  73419. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  73420. /**
  73421. * Support test.
  73422. */
  73423. get: function () {
  73424. var engine = BABYLON.Engine.LastCreatedEngine;
  73425. if (!engine) {
  73426. return false;
  73427. }
  73428. return engine.getCaps().drawBuffersExtension;
  73429. },
  73430. enumerable: true,
  73431. configurable: true
  73432. });
  73433. // Public Methods
  73434. /**
  73435. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73436. */
  73437. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  73438. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  73439. for (var i = 0; i < this._scene.cameras.length; i++) {
  73440. var camera = this._scene.cameras[i];
  73441. this._originalColorPostProcess.dispose(camera);
  73442. this._ssaoPostProcess.dispose(camera);
  73443. this._blurHPostProcess.dispose(camera);
  73444. this._blurVPostProcess.dispose(camera);
  73445. this._ssaoCombinePostProcess.dispose(camera);
  73446. }
  73447. this._randomTexture.dispose();
  73448. if (disableGeometryBufferRenderer)
  73449. this._scene.disableGeometryBufferRenderer();
  73450. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73451. _super.prototype.dispose.call(this);
  73452. };
  73453. // Private Methods
  73454. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  73455. var _this = this;
  73456. this._samplerOffsets = [];
  73457. var expensive = this.expensiveBlur;
  73458. for (var i = -8; i < 8; i++) {
  73459. this._samplerOffsets.push(i * 2 + 0.5);
  73460. }
  73461. 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");
  73462. this._blurHPostProcess.onApply = function (effect) {
  73463. if (!_this._scene.activeCamera) {
  73464. return;
  73465. }
  73466. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  73467. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73468. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73469. effect.setFloat("radius", _this.radius);
  73470. effect.setTexture("depthSampler", _this._depthTexture);
  73471. if (_this._firstUpdate) {
  73472. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73473. }
  73474. };
  73475. 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");
  73476. this._blurVPostProcess.onApply = function (effect) {
  73477. if (!_this._scene.activeCamera) {
  73478. return;
  73479. }
  73480. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  73481. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73482. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73483. effect.setFloat("radius", _this.radius);
  73484. effect.setTexture("depthSampler", _this._depthTexture);
  73485. if (_this._firstUpdate) {
  73486. effect.setArray("samplerOffsets", _this._samplerOffsets);
  73487. _this._firstUpdate = false;
  73488. }
  73489. };
  73490. };
  73491. SSAO2RenderingPipeline.prototype._rebuild = function () {
  73492. this._firstUpdate = true;
  73493. _super.prototype._rebuild.call(this);
  73494. };
  73495. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  73496. var numSamples = this.samples;
  73497. var result = [];
  73498. var vector, scale;
  73499. var rand = function (min, max) {
  73500. return Math.random() * (max - min) + min;
  73501. };
  73502. var i = 0;
  73503. while (i < numSamples) {
  73504. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  73505. vector.normalize();
  73506. scale = i / numSamples;
  73507. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  73508. vector.scaleInPlace(scale);
  73509. result.push(vector.x, vector.y, vector.z);
  73510. i++;
  73511. }
  73512. return result;
  73513. };
  73514. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73515. var _this = this;
  73516. var numSamples = this.samples;
  73517. this._sampleSphere = this._generateHemisphere();
  73518. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  73519. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73520. "base", "range", "projection", "near", "far", "texelSize",
  73521. "xViewport", "yViewport", "maxZ", "minZAspect"
  73522. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73523. this._ssaoPostProcess.onApply = function (effect) {
  73524. if (_this._firstUpdate) {
  73525. effect.setArray3("sampleSphere", _this._sampleSphere);
  73526. effect.setFloat("randTextureTiles", 4.0);
  73527. }
  73528. if (!_this._scene.activeCamera) {
  73529. return;
  73530. }
  73531. effect.setFloat("samplesFactor", 1 / _this.samples);
  73532. effect.setFloat("totalStrength", _this.totalStrength);
  73533. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  73534. effect.setFloat("radius", _this.radius);
  73535. effect.setFloat("maxZ", _this.maxZ);
  73536. effect.setFloat("minZAspect", _this.minZAspect);
  73537. effect.setFloat("base", _this.base);
  73538. effect.setFloat("near", _this._scene.activeCamera.minZ);
  73539. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  73540. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  73541. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  73542. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  73543. effect.setTexture("textureSampler", _this._depthTexture);
  73544. effect.setTexture("normalSampler", _this._normalTexture);
  73545. effect.setTexture("randomSampler", _this._randomTexture);
  73546. };
  73547. };
  73548. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73549. var _this = this;
  73550. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73551. this._ssaoCombinePostProcess.onApply = function (effect) {
  73552. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73553. };
  73554. };
  73555. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  73556. var size = 512;
  73557. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73558. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73559. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73560. var context = this._randomTexture.getContext();
  73561. var rand = function (min, max) {
  73562. return Math.random() * (max - min) + min;
  73563. };
  73564. var randVector = BABYLON.Vector3.Zero();
  73565. for (var x = 0; x < size; x++) {
  73566. for (var y = 0; y < size; y++) {
  73567. randVector.x = rand(0.0, 1.0);
  73568. randVector.y = rand(0.0, 1.0);
  73569. randVector.z = 0.0;
  73570. randVector.normalize();
  73571. randVector.scaleInPlace(255);
  73572. randVector.x = Math.floor(randVector.x);
  73573. randVector.y = Math.floor(randVector.y);
  73574. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73575. context.fillRect(x, y, 1, 1);
  73576. }
  73577. }
  73578. this._randomTexture.update(false);
  73579. };
  73580. /**
  73581. * Serialize the rendering pipeline (Used when exporting)
  73582. * @returns the serialized object
  73583. */
  73584. SSAO2RenderingPipeline.prototype.serialize = function () {
  73585. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  73586. serializationObject.customType = "SSAO2RenderingPipeline";
  73587. return serializationObject;
  73588. };
  73589. /**
  73590. * Parse the serialized pipeline
  73591. * @param source Source pipeline.
  73592. * @param scene The scene to load the pipeline to.
  73593. * @param rootUrl The URL of the serialized pipeline.
  73594. * @returns An instantiated pipeline from the serialized object.
  73595. */
  73596. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  73597. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  73598. };
  73599. __decorate([
  73600. BABYLON.serialize()
  73601. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  73602. __decorate([
  73603. BABYLON.serialize()
  73604. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  73605. __decorate([
  73606. BABYLON.serialize()
  73607. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  73608. __decorate([
  73609. BABYLON.serialize("samples")
  73610. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  73611. __decorate([
  73612. BABYLON.serialize()
  73613. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  73614. __decorate([
  73615. BABYLON.serialize("expensiveBlur")
  73616. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  73617. __decorate([
  73618. BABYLON.serialize()
  73619. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  73620. __decorate([
  73621. BABYLON.serialize()
  73622. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  73623. return SSAO2RenderingPipeline;
  73624. }(BABYLON.PostProcessRenderPipeline));
  73625. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  73626. })(BABYLON || (BABYLON = {}));
  73627. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  73628. // BABYLON.JS Chromatic Aberration GLSL Shader
  73629. // Author: Olivier Guyot
  73630. // Separates very slightly R, G and B colors on the edges of the screen
  73631. // Inspired by Francois Tarlier & Martins Upitis
  73632. var BABYLON;
  73633. (function (BABYLON) {
  73634. var LensRenderingPipeline = /** @class */ (function (_super) {
  73635. __extends(LensRenderingPipeline, _super);
  73636. /**
  73637. * @constructor
  73638. *
  73639. * Effect parameters are as follow:
  73640. * {
  73641. * chromatic_aberration: number; // from 0 to x (1 for realism)
  73642. * edge_blur: number; // from 0 to x (1 for realism)
  73643. * distortion: number; // from 0 to x (1 for realism)
  73644. * grain_amount: number; // from 0 to 1
  73645. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  73646. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  73647. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  73648. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  73649. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  73650. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  73651. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  73652. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  73653. * }
  73654. * Note: if an effect parameter is unset, effect is disabled
  73655. *
  73656. * @param {string} name - The rendering pipeline name
  73657. * @param {object} parameters - An object containing all parameters (see above)
  73658. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73659. * @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)
  73660. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73661. */
  73662. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  73663. if (ratio === void 0) { ratio = 1.0; }
  73664. var _this = _super.call(this, scene.getEngine(), name) || this;
  73665. // Lens effects can be of the following:
  73666. // - chromatic aberration (slight shift of RGB colors)
  73667. // - blur on the edge of the lens
  73668. // - lens distortion
  73669. // - depth-of-field blur & highlights enhancing
  73670. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  73671. // - grain effect (noise or custom texture)
  73672. // Two additional texture samplers are needed:
  73673. // - depth map (for depth-of-field)
  73674. // - grain texture
  73675. /**
  73676. * The chromatic aberration PostProcess id in the pipeline
  73677. */
  73678. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  73679. /**
  73680. * The highlights enhancing PostProcess id in the pipeline
  73681. */
  73682. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  73683. /**
  73684. * The depth-of-field PostProcess id in the pipeline
  73685. */
  73686. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  73687. _this._scene = scene;
  73688. // Fetch texture samplers
  73689. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73690. if (parameters.grain_texture) {
  73691. _this._grainTexture = parameters.grain_texture;
  73692. }
  73693. else {
  73694. _this._createGrainTexture();
  73695. }
  73696. // save parameters
  73697. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  73698. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  73699. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  73700. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  73701. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  73702. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  73703. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  73704. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  73705. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  73706. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  73707. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  73708. // Create effects
  73709. _this._createChromaticAberrationPostProcess(ratio);
  73710. _this._createHighlightsPostProcess(ratio);
  73711. _this._createDepthOfFieldPostProcess(ratio / 4);
  73712. // Set up pipeline
  73713. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  73714. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  73715. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  73716. if (_this._highlightsGain === -1) {
  73717. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  73718. }
  73719. // Finish
  73720. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73721. if (cameras) {
  73722. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73723. }
  73724. return _this;
  73725. }
  73726. // public methods (self explanatory)
  73727. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  73728. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  73729. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  73730. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  73731. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  73732. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  73733. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  73734. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  73735. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  73736. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  73737. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  73738. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  73739. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  73740. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  73741. };
  73742. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  73743. this._highlightsPostProcess.updateEffect();
  73744. };
  73745. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  73746. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  73747. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  73748. this._highlightsGain = amount;
  73749. };
  73750. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  73751. if (this._highlightsGain === -1) {
  73752. this._highlightsGain = 1.0;
  73753. }
  73754. this._highlightsThreshold = amount;
  73755. };
  73756. LensRenderingPipeline.prototype.disableHighlights = function () {
  73757. this._highlightsGain = -1;
  73758. };
  73759. /**
  73760. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  73761. */
  73762. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73763. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73764. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73765. this._chromaticAberrationPostProcess = null;
  73766. this._highlightsPostProcess = null;
  73767. this._depthOfFieldPostProcess = null;
  73768. this._grainTexture.dispose();
  73769. if (disableDepthRender)
  73770. this._scene.disableDepthRenderer();
  73771. };
  73772. // colors shifting and distortion
  73773. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  73774. var _this = this;
  73775. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  73776. [], // samplers
  73777. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73778. this._chromaticAberrationPostProcess.onApply = function (effect) {
  73779. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  73780. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73781. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73782. effect.setFloat('radialIntensity', 1);
  73783. effect.setFloat2('direction', 17, 17);
  73784. effect.setFloat2('centerPosition', 0.5, 0.5);
  73785. };
  73786. };
  73787. // highlights enhancing
  73788. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  73789. var _this = this;
  73790. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  73791. [], // samplers
  73792. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  73793. this._highlightsPostProcess.onApply = function (effect) {
  73794. effect.setFloat('gain', _this._highlightsGain);
  73795. effect.setFloat('threshold', _this._highlightsThreshold);
  73796. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  73797. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73798. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73799. };
  73800. };
  73801. // colors shifting and distortion
  73802. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  73803. var _this = this;
  73804. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  73805. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  73806. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  73807. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73808. this._depthOfFieldPostProcess.onApply = function (effect) {
  73809. effect.setTexture("depthSampler", _this._depthTexture);
  73810. effect.setTexture("grainSampler", _this._grainTexture);
  73811. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  73812. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  73813. effect.setFloat('grain_amount', _this._grainAmount);
  73814. effect.setBool('blur_noise', _this._blurNoise);
  73815. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  73816. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  73817. effect.setFloat('distortion', _this._distortion);
  73818. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  73819. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  73820. effect.setFloat('aperture', _this._dofAperture);
  73821. effect.setFloat('darken', _this._dofDarken);
  73822. effect.setFloat('edge_blur', _this._edgeBlur);
  73823. effect.setBool('highlights', (_this._highlightsGain !== -1));
  73824. if (_this._scene.activeCamera) {
  73825. effect.setFloat('near', _this._scene.activeCamera.minZ);
  73826. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  73827. }
  73828. };
  73829. };
  73830. // creates a black and white random noise texture, 512x512
  73831. LensRenderingPipeline.prototype._createGrainTexture = function () {
  73832. var size = 512;
  73833. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  73834. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73835. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73836. var context = this._grainTexture.getContext();
  73837. var rand = function (min, max) {
  73838. return Math.random() * (max - min) + min;
  73839. };
  73840. var value;
  73841. for (var x = 0; x < size; x++) {
  73842. for (var y = 0; y < size; y++) {
  73843. value = Math.floor(rand(0.42, 0.58) * 255);
  73844. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  73845. context.fillRect(x, y, 1, 1);
  73846. }
  73847. }
  73848. this._grainTexture.update(false);
  73849. };
  73850. return LensRenderingPipeline;
  73851. }(BABYLON.PostProcessRenderPipeline));
  73852. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  73853. })(BABYLON || (BABYLON = {}));
  73854. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  73855. var BABYLON;
  73856. (function (BABYLON) {
  73857. var StandardRenderingPipeline = /** @class */ (function (_super) {
  73858. __extends(StandardRenderingPipeline, _super);
  73859. /**
  73860. * @constructor
  73861. * @param {string} name - The rendering pipeline name
  73862. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73863. * @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)
  73864. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  73865. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73866. */
  73867. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  73868. if (originalPostProcess === void 0) { originalPostProcess = null; }
  73869. var _this = _super.call(this, scene.getEngine(), name) || this;
  73870. _this.downSampleX4PostProcess = null;
  73871. _this.brightPassPostProcess = null;
  73872. _this.blurHPostProcesses = [];
  73873. _this.blurVPostProcesses = [];
  73874. _this.textureAdderPostProcess = null;
  73875. _this.volumetricLightPostProcess = null;
  73876. _this.volumetricLightSmoothXPostProcess = null;
  73877. _this.volumetricLightSmoothYPostProcess = null;
  73878. _this.volumetricLightMergePostProces = null;
  73879. _this.volumetricLightFinalPostProcess = null;
  73880. _this.luminancePostProcess = null;
  73881. _this.luminanceDownSamplePostProcesses = [];
  73882. _this.hdrPostProcess = null;
  73883. _this.textureAdderFinalPostProcess = null;
  73884. _this.lensFlareFinalPostProcess = null;
  73885. _this.hdrFinalPostProcess = null;
  73886. _this.lensFlarePostProcess = null;
  73887. _this.lensFlareComposePostProcess = null;
  73888. _this.motionBlurPostProcess = null;
  73889. _this.depthOfFieldPostProcess = null;
  73890. // Values
  73891. _this.brightThreshold = 1.0;
  73892. _this.blurWidth = 512.0;
  73893. _this.horizontalBlur = false;
  73894. _this.exposure = 1.0;
  73895. _this.lensTexture = null;
  73896. _this.volumetricLightCoefficient = 0.2;
  73897. _this.volumetricLightPower = 4.0;
  73898. _this.volumetricLightBlurScale = 64.0;
  73899. _this.sourceLight = null;
  73900. _this.hdrMinimumLuminance = 1.0;
  73901. _this.hdrDecreaseRate = 0.5;
  73902. _this.hdrIncreaseRate = 0.5;
  73903. _this.lensColorTexture = null;
  73904. _this.lensFlareStrength = 20.0;
  73905. _this.lensFlareGhostDispersal = 1.4;
  73906. _this.lensFlareHaloWidth = 0.7;
  73907. _this.lensFlareDistortionStrength = 16.0;
  73908. _this.lensStarTexture = null;
  73909. _this.lensFlareDirtTexture = null;
  73910. _this.depthOfFieldDistance = 10.0;
  73911. _this.depthOfFieldBlurWidth = 64.0;
  73912. _this.motionStrength = 1.0;
  73913. // IAnimatable
  73914. _this.animations = [];
  73915. _this._currentDepthOfFieldSource = null;
  73916. _this._hdrCurrentLuminance = 1.0;
  73917. // Getters and setters
  73918. _this._bloomEnabled = true;
  73919. _this._depthOfFieldEnabled = false;
  73920. _this._vlsEnabled = false;
  73921. _this._lensFlareEnabled = false;
  73922. _this._hdrEnabled = false;
  73923. _this._motionBlurEnabled = false;
  73924. _this._motionBlurSamples = 64.0;
  73925. _this._volumetricLightStepsCount = 50.0;
  73926. _this._cameras = cameras || [];
  73927. // Initialize
  73928. _this._scene = scene;
  73929. _this._basePostProcess = originalPostProcess;
  73930. _this._ratio = ratio;
  73931. // Misc
  73932. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  73933. // Finish
  73934. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73935. _this._buildPipeline();
  73936. return _this;
  73937. }
  73938. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  73939. get: function () {
  73940. return this._bloomEnabled;
  73941. },
  73942. set: function (enabled) {
  73943. if (this._bloomEnabled === enabled) {
  73944. return;
  73945. }
  73946. this._bloomEnabled = enabled;
  73947. this._buildPipeline();
  73948. },
  73949. enumerable: true,
  73950. configurable: true
  73951. });
  73952. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  73953. get: function () {
  73954. return this._depthOfFieldEnabled;
  73955. },
  73956. set: function (enabled) {
  73957. if (this._depthOfFieldEnabled === enabled) {
  73958. return;
  73959. }
  73960. this._depthOfFieldEnabled = enabled;
  73961. this._buildPipeline();
  73962. },
  73963. enumerable: true,
  73964. configurable: true
  73965. });
  73966. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  73967. get: function () {
  73968. return this._lensFlareEnabled;
  73969. },
  73970. set: function (enabled) {
  73971. if (this._lensFlareEnabled === enabled) {
  73972. return;
  73973. }
  73974. this._lensFlareEnabled = enabled;
  73975. this._buildPipeline();
  73976. },
  73977. enumerable: true,
  73978. configurable: true
  73979. });
  73980. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  73981. get: function () {
  73982. return this._hdrEnabled;
  73983. },
  73984. set: function (enabled) {
  73985. if (this._hdrEnabled === enabled) {
  73986. return;
  73987. }
  73988. this._hdrEnabled = enabled;
  73989. this._buildPipeline();
  73990. },
  73991. enumerable: true,
  73992. configurable: true
  73993. });
  73994. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  73995. get: function () {
  73996. return this._vlsEnabled;
  73997. },
  73998. set: function (enabled) {
  73999. if (this._vlsEnabled === enabled) {
  74000. return;
  74001. }
  74002. if (enabled) {
  74003. var geometry = this._scene.enableGeometryBufferRenderer();
  74004. if (!geometry) {
  74005. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74006. return;
  74007. }
  74008. }
  74009. this._vlsEnabled = enabled;
  74010. this._buildPipeline();
  74011. },
  74012. enumerable: true,
  74013. configurable: true
  74014. });
  74015. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74016. get: function () {
  74017. return this._motionBlurEnabled;
  74018. },
  74019. set: function (enabled) {
  74020. if (this._motionBlurEnabled === enabled) {
  74021. return;
  74022. }
  74023. this._motionBlurEnabled = enabled;
  74024. this._buildPipeline();
  74025. },
  74026. enumerable: true,
  74027. configurable: true
  74028. });
  74029. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74030. get: function () {
  74031. return this._volumetricLightStepsCount;
  74032. },
  74033. set: function (count) {
  74034. if (this.volumetricLightPostProcess) {
  74035. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74036. }
  74037. this._volumetricLightStepsCount = count;
  74038. },
  74039. enumerable: true,
  74040. configurable: true
  74041. });
  74042. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74043. get: function () {
  74044. return this._motionBlurSamples;
  74045. },
  74046. set: function (samples) {
  74047. if (this.motionBlurPostProcess) {
  74048. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74049. }
  74050. this._motionBlurSamples = samples;
  74051. },
  74052. enumerable: true,
  74053. configurable: true
  74054. });
  74055. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74056. var _this = this;
  74057. var ratio = this._ratio;
  74058. var scene = this._scene;
  74059. this._disposePostProcesses();
  74060. this._reset();
  74061. // Create pass post-process
  74062. if (!this._basePostProcess) {
  74063. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74064. this.originalPostProcess.onApply = function (effect) {
  74065. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74066. };
  74067. }
  74068. else {
  74069. this.originalPostProcess = this._basePostProcess;
  74070. }
  74071. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74072. this._currentDepthOfFieldSource = this.originalPostProcess;
  74073. if (this._bloomEnabled) {
  74074. // Create down sample X4 post-process
  74075. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74076. // Create bright pass post-process
  74077. this._createBrightPassPostProcess(scene, ratio / 2);
  74078. // Create gaussian blur post-processes (down sampling blurs)
  74079. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74080. // Create texture adder post-process
  74081. this._createTextureAdderPostProcess(scene, ratio);
  74082. // Create depth-of-field source post-process
  74083. 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);
  74084. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74085. }
  74086. if (this._vlsEnabled) {
  74087. // Create volumetric light
  74088. this._createVolumetricLightPostProcess(scene, ratio);
  74089. // Create volumetric light final post-process
  74090. 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);
  74091. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74092. }
  74093. if (this._lensFlareEnabled) {
  74094. // Create lens flare post-process
  74095. this._createLensFlarePostProcess(scene, ratio);
  74096. // Create depth-of-field source post-process post lens-flare and disable it now
  74097. 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);
  74098. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74099. }
  74100. if (this._hdrEnabled) {
  74101. // Create luminance
  74102. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74103. // Create HDR
  74104. this._createHdrPostProcess(scene, ratio);
  74105. // Create depth-of-field source post-process post hdr and disable it now
  74106. 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);
  74107. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74108. }
  74109. if (this._depthOfFieldEnabled) {
  74110. // Create gaussian blur used by depth-of-field
  74111. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74112. // Create depth-of-field post-process
  74113. this._createDepthOfFieldPostProcess(scene, ratio);
  74114. }
  74115. if (this._motionBlurEnabled) {
  74116. // Create motion blur post-process
  74117. this._createMotionBlurPostProcess(scene, ratio);
  74118. }
  74119. if (this._cameras !== null) {
  74120. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74121. }
  74122. };
  74123. // Down Sample X4 Post-Processs
  74124. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74125. var _this = this;
  74126. var downSampleX4Offsets = new Array(32);
  74127. 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);
  74128. this.downSampleX4PostProcess.onApply = function (effect) {
  74129. var id = 0;
  74130. var width = _this.downSampleX4PostProcess.width;
  74131. var height = _this.downSampleX4PostProcess.height;
  74132. for (var i = -2; i < 2; i++) {
  74133. for (var j = -2; j < 2; j++) {
  74134. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74135. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74136. id += 2;
  74137. }
  74138. }
  74139. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74140. };
  74141. // Add to pipeline
  74142. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74143. };
  74144. // Brightpass Post-Process
  74145. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74146. var _this = this;
  74147. var brightOffsets = new Array(8);
  74148. 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);
  74149. this.brightPassPostProcess.onApply = function (effect) {
  74150. var sU = (1.0 / _this.brightPassPostProcess.width);
  74151. var sV = (1.0 / _this.brightPassPostProcess.height);
  74152. brightOffsets[0] = -0.5 * sU;
  74153. brightOffsets[1] = 0.5 * sV;
  74154. brightOffsets[2] = 0.5 * sU;
  74155. brightOffsets[3] = 0.5 * sV;
  74156. brightOffsets[4] = -0.5 * sU;
  74157. brightOffsets[5] = -0.5 * sV;
  74158. brightOffsets[6] = 0.5 * sU;
  74159. brightOffsets[7] = -0.5 * sV;
  74160. effect.setArray2("dsOffsets", brightOffsets);
  74161. effect.setFloat("brightThreshold", _this.brightThreshold);
  74162. };
  74163. // Add to pipeline
  74164. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74165. };
  74166. // Create blur H&V post-processes
  74167. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74168. var _this = this;
  74169. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74170. var engine = scene.getEngine();
  74171. 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);
  74172. 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);
  74173. blurX.onActivateObservable.add(function () {
  74174. var dw = blurX.width / engine.getRenderWidth();
  74175. blurX.kernel = _this[blurWidthKey] * dw;
  74176. });
  74177. blurY.onActivateObservable.add(function () {
  74178. var dw = blurY.height / engine.getRenderHeight();
  74179. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74180. });
  74181. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74182. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74183. this.blurHPostProcesses.push(blurX);
  74184. this.blurVPostProcesses.push(blurY);
  74185. };
  74186. // Create texture adder post-process
  74187. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74188. var _this = this;
  74189. 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);
  74190. this.textureAdderPostProcess.onApply = function (effect) {
  74191. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74192. effect.setTexture("lensSampler", _this.lensTexture);
  74193. effect.setFloat("exposure", _this.exposure);
  74194. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74195. };
  74196. // Add to pipeline
  74197. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74198. };
  74199. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74200. var _this = this;
  74201. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74202. geometryRenderer.enablePosition = true;
  74203. var geometry = geometryRenderer.getGBuffer();
  74204. // Base post-process
  74205. 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));
  74206. var depthValues = BABYLON.Vector2.Zero();
  74207. this.volumetricLightPostProcess.onApply = function (effect) {
  74208. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74209. var generator = _this.sourceLight.getShadowGenerator();
  74210. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74211. effect.setTexture("positionSampler", geometry.textures[2]);
  74212. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74213. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74214. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74215. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74216. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74217. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74218. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74219. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74220. effect.setVector2("depthValues", depthValues);
  74221. }
  74222. };
  74223. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74224. // Smooth
  74225. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74226. // Merge
  74227. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74228. this.volumetricLightMergePostProces.onApply = function (effect) {
  74229. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74230. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74231. };
  74232. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74233. };
  74234. // Create luminance
  74235. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74236. var _this = this;
  74237. // Create luminance
  74238. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74239. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74240. var offsets = [];
  74241. this.luminancePostProcess.onApply = function (effect) {
  74242. var sU = (1.0 / _this.luminancePostProcess.width);
  74243. var sV = (1.0 / _this.luminancePostProcess.height);
  74244. offsets[0] = -0.5 * sU;
  74245. offsets[1] = 0.5 * sV;
  74246. offsets[2] = 0.5 * sU;
  74247. offsets[3] = 0.5 * sV;
  74248. offsets[4] = -0.5 * sU;
  74249. offsets[5] = -0.5 * sV;
  74250. offsets[6] = 0.5 * sU;
  74251. offsets[7] = -0.5 * sV;
  74252. effect.setArray2("lumOffsets", offsets);
  74253. };
  74254. // Add to pipeline
  74255. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74256. // Create down sample luminance
  74257. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74258. var size = Math.pow(3, i);
  74259. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74260. if (i === 0) {
  74261. defines += "#define FINAL_DOWN_SAMPLER";
  74262. }
  74263. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74264. this.luminanceDownSamplePostProcesses.push(postProcess);
  74265. }
  74266. // Create callbacks and add effects
  74267. var lastLuminance = this.luminancePostProcess;
  74268. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74269. var downSampleOffsets = new Array(18);
  74270. pp.onApply = function (effect) {
  74271. if (!lastLuminance) {
  74272. return;
  74273. }
  74274. var id = 0;
  74275. for (var x = -1; x < 2; x++) {
  74276. for (var y = -1; y < 2; y++) {
  74277. downSampleOffsets[id] = x / lastLuminance.width;
  74278. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74279. id += 2;
  74280. }
  74281. }
  74282. effect.setArray2("dsOffsets", downSampleOffsets);
  74283. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74284. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74285. lastLuminance = _this.luminancePostProcess;
  74286. }
  74287. else {
  74288. lastLuminance = pp;
  74289. }
  74290. };
  74291. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74292. pp.onAfterRender = function (effect) {
  74293. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74294. 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);
  74295. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74296. };
  74297. }
  74298. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74299. });
  74300. };
  74301. // Create HDR post-process
  74302. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74303. var _this = this;
  74304. 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);
  74305. var outputLiminance = 1;
  74306. var time = 0;
  74307. var lastTime = 0;
  74308. this.hdrPostProcess.onApply = function (effect) {
  74309. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74310. time += scene.getEngine().getDeltaTime();
  74311. if (outputLiminance < 0) {
  74312. outputLiminance = _this._hdrCurrentLuminance;
  74313. }
  74314. else {
  74315. var dt = (lastTime - time) / 1000.0;
  74316. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74317. outputLiminance += _this.hdrDecreaseRate * dt;
  74318. }
  74319. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74320. outputLiminance -= _this.hdrIncreaseRate * dt;
  74321. }
  74322. else {
  74323. outputLiminance = _this._hdrCurrentLuminance;
  74324. }
  74325. }
  74326. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74327. effect.setFloat("averageLuminance", outputLiminance);
  74328. lastTime = time;
  74329. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74330. };
  74331. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74332. };
  74333. // Create lens flare post-process
  74334. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74335. var _this = this;
  74336. 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);
  74337. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74338. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74339. 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);
  74340. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74341. var resolution = new BABYLON.Vector2(0, 0);
  74342. // Lens flare
  74343. this.lensFlarePostProcess.onApply = function (effect) {
  74344. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74345. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74346. effect.setFloat("strength", _this.lensFlareStrength);
  74347. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74348. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74349. // Shift
  74350. resolution.x = _this.lensFlarePostProcess.width;
  74351. resolution.y = _this.lensFlarePostProcess.height;
  74352. effect.setVector2("resolution", resolution);
  74353. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74354. };
  74355. // Compose
  74356. 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);
  74357. 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);
  74358. this.lensFlareComposePostProcess.onApply = function (effect) {
  74359. if (!_this._scene.activeCamera) {
  74360. return;
  74361. }
  74362. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74363. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74364. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74365. // Lens start rotation matrix
  74366. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74367. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74368. 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));
  74369. camRot *= 4.0;
  74370. 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);
  74371. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  74372. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  74373. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  74374. };
  74375. };
  74376. // Create depth-of-field post-process
  74377. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  74378. var _this = this;
  74379. 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);
  74380. this.depthOfFieldPostProcess.onApply = function (effect) {
  74381. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74382. effect.setTexture("depthSampler", _this._getDepthTexture());
  74383. effect.setFloat("distance", _this.depthOfFieldDistance);
  74384. };
  74385. // Add to pipeline
  74386. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  74387. };
  74388. // Create motion blur post-process
  74389. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  74390. var _this = this;
  74391. 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);
  74392. var motionScale = 0;
  74393. var prevViewProjection = BABYLON.Matrix.Identity();
  74394. var invViewProjection = BABYLON.Matrix.Identity();
  74395. var viewProjection = BABYLON.Matrix.Identity();
  74396. var screenSize = BABYLON.Vector2.Zero();
  74397. this.motionBlurPostProcess.onApply = function (effect) {
  74398. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  74399. viewProjection.invertToRef(invViewProjection);
  74400. effect.setMatrix("inverseViewProjection", invViewProjection);
  74401. effect.setMatrix("prevViewProjection", prevViewProjection);
  74402. prevViewProjection = viewProjection;
  74403. screenSize.x = _this.motionBlurPostProcess.width;
  74404. screenSize.y = _this.motionBlurPostProcess.height;
  74405. effect.setVector2("screenSize", screenSize);
  74406. motionScale = scene.getEngine().getFps() / 60.0;
  74407. effect.setFloat("motionScale", motionScale);
  74408. effect.setFloat("motionStrength", _this.motionStrength);
  74409. effect.setTexture("depthSampler", _this._getDepthTexture());
  74410. };
  74411. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  74412. };
  74413. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  74414. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  74415. var renderer = this._scene.enableGeometryBufferRenderer();
  74416. return renderer.getGBuffer().textures[0];
  74417. }
  74418. return this._scene.enableDepthRenderer().getDepthMap();
  74419. };
  74420. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  74421. for (var i = 0; i < this._cameras.length; i++) {
  74422. var camera = this._cameras[i];
  74423. if (this.originalPostProcess) {
  74424. this.originalPostProcess.dispose(camera);
  74425. }
  74426. if (this.downSampleX4PostProcess) {
  74427. this.downSampleX4PostProcess.dispose(camera);
  74428. }
  74429. if (this.brightPassPostProcess) {
  74430. this.brightPassPostProcess.dispose(camera);
  74431. }
  74432. if (this.textureAdderPostProcess) {
  74433. this.textureAdderPostProcess.dispose(camera);
  74434. }
  74435. if (this.textureAdderFinalPostProcess) {
  74436. this.textureAdderFinalPostProcess.dispose(camera);
  74437. }
  74438. if (this.volumetricLightPostProcess) {
  74439. this.volumetricLightPostProcess.dispose(camera);
  74440. }
  74441. if (this.volumetricLightSmoothXPostProcess) {
  74442. this.volumetricLightSmoothXPostProcess.dispose(camera);
  74443. }
  74444. if (this.volumetricLightSmoothYPostProcess) {
  74445. this.volumetricLightSmoothYPostProcess.dispose(camera);
  74446. }
  74447. if (this.volumetricLightMergePostProces) {
  74448. this.volumetricLightMergePostProces.dispose(camera);
  74449. }
  74450. if (this.volumetricLightFinalPostProcess) {
  74451. this.volumetricLightFinalPostProcess.dispose(camera);
  74452. }
  74453. if (this.lensFlarePostProcess) {
  74454. this.lensFlarePostProcess.dispose(camera);
  74455. }
  74456. if (this.lensFlareComposePostProcess) {
  74457. this.lensFlareComposePostProcess.dispose(camera);
  74458. }
  74459. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  74460. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  74461. }
  74462. if (this.luminancePostProcess) {
  74463. this.luminancePostProcess.dispose(camera);
  74464. }
  74465. if (this.hdrPostProcess) {
  74466. this.hdrPostProcess.dispose(camera);
  74467. }
  74468. if (this.hdrFinalPostProcess) {
  74469. this.hdrFinalPostProcess.dispose(camera);
  74470. }
  74471. if (this.depthOfFieldPostProcess) {
  74472. this.depthOfFieldPostProcess.dispose(camera);
  74473. }
  74474. if (this.motionBlurPostProcess) {
  74475. this.motionBlurPostProcess.dispose(camera);
  74476. }
  74477. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  74478. this.blurHPostProcesses[j].dispose(camera);
  74479. }
  74480. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  74481. this.blurVPostProcesses[j].dispose(camera);
  74482. }
  74483. }
  74484. this.originalPostProcess = null;
  74485. this.downSampleX4PostProcess = null;
  74486. this.brightPassPostProcess = null;
  74487. this.textureAdderPostProcess = null;
  74488. this.textureAdderFinalPostProcess = null;
  74489. this.volumetricLightPostProcess = null;
  74490. this.volumetricLightSmoothXPostProcess = null;
  74491. this.volumetricLightSmoothYPostProcess = null;
  74492. this.volumetricLightMergePostProces = null;
  74493. this.volumetricLightFinalPostProcess = null;
  74494. this.lensFlarePostProcess = null;
  74495. this.lensFlareComposePostProcess = null;
  74496. this.luminancePostProcess = null;
  74497. this.hdrPostProcess = null;
  74498. this.hdrFinalPostProcess = null;
  74499. this.depthOfFieldPostProcess = null;
  74500. this.motionBlurPostProcess = null;
  74501. this.luminanceDownSamplePostProcesses = [];
  74502. this.blurHPostProcesses = [];
  74503. this.blurVPostProcesses = [];
  74504. };
  74505. /**
  74506. * Dispose of the pipeline and stop all post processes
  74507. */
  74508. StandardRenderingPipeline.prototype.dispose = function () {
  74509. this._disposePostProcesses();
  74510. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  74511. _super.prototype.dispose.call(this);
  74512. };
  74513. /**
  74514. * Serialize the rendering pipeline (Used when exporting)
  74515. * @returns the serialized object
  74516. */
  74517. StandardRenderingPipeline.prototype.serialize = function () {
  74518. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74519. if (this.sourceLight) {
  74520. serializationObject.sourceLightId = this.sourceLight.id;
  74521. }
  74522. serializationObject.customType = "StandardRenderingPipeline";
  74523. return serializationObject;
  74524. };
  74525. /**
  74526. * Parse the serialized pipeline
  74527. * @param source Source pipeline.
  74528. * @param scene The scene to load the pipeline to.
  74529. * @param rootUrl The URL of the serialized pipeline.
  74530. * @returns An instantiated pipeline from the serialized object.
  74531. */
  74532. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  74533. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74534. if (source.sourceLightId) {
  74535. p.sourceLight = scene.getLightByID(source.sourceLightId);
  74536. }
  74537. return p;
  74538. };
  74539. // Luminance steps
  74540. StandardRenderingPipeline.LuminanceSteps = 6;
  74541. __decorate([
  74542. BABYLON.serialize()
  74543. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  74544. __decorate([
  74545. BABYLON.serialize()
  74546. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  74547. __decorate([
  74548. BABYLON.serialize()
  74549. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  74550. __decorate([
  74551. BABYLON.serialize()
  74552. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  74553. __decorate([
  74554. BABYLON.serializeAsTexture("lensTexture")
  74555. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  74556. __decorate([
  74557. BABYLON.serialize()
  74558. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  74559. __decorate([
  74560. BABYLON.serialize()
  74561. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  74562. __decorate([
  74563. BABYLON.serialize()
  74564. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  74565. __decorate([
  74566. BABYLON.serialize()
  74567. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  74568. __decorate([
  74569. BABYLON.serialize()
  74570. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  74571. __decorate([
  74572. BABYLON.serialize()
  74573. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  74574. __decorate([
  74575. BABYLON.serializeAsTexture("lensColorTexture")
  74576. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  74577. __decorate([
  74578. BABYLON.serialize()
  74579. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  74580. __decorate([
  74581. BABYLON.serialize()
  74582. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  74583. __decorate([
  74584. BABYLON.serialize()
  74585. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  74586. __decorate([
  74587. BABYLON.serialize()
  74588. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  74589. __decorate([
  74590. BABYLON.serializeAsTexture("lensStarTexture")
  74591. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  74592. __decorate([
  74593. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  74594. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  74595. __decorate([
  74596. BABYLON.serialize()
  74597. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  74598. __decorate([
  74599. BABYLON.serialize()
  74600. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  74601. __decorate([
  74602. BABYLON.serialize()
  74603. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  74604. __decorate([
  74605. BABYLON.serialize()
  74606. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  74607. __decorate([
  74608. BABYLON.serialize()
  74609. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  74610. __decorate([
  74611. BABYLON.serialize()
  74612. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  74613. __decorate([
  74614. BABYLON.serialize()
  74615. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  74616. __decorate([
  74617. BABYLON.serialize()
  74618. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  74619. __decorate([
  74620. BABYLON.serialize()
  74621. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  74622. __decorate([
  74623. BABYLON.serialize()
  74624. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  74625. __decorate([
  74626. BABYLON.serialize()
  74627. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  74628. __decorate([
  74629. BABYLON.serialize()
  74630. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  74631. return StandardRenderingPipeline;
  74632. }(BABYLON.PostProcessRenderPipeline));
  74633. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  74634. })(BABYLON || (BABYLON = {}));
  74635. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  74636. var BABYLON;
  74637. (function (BABYLON) {
  74638. var FxaaPostProcess = /** @class */ (function (_super) {
  74639. __extends(FxaaPostProcess, _super);
  74640. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  74641. if (camera === void 0) { camera = null; }
  74642. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74643. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  74644. var defines = _this._getDefines();
  74645. _this.updateEffect(defines);
  74646. _this.onApplyObservable.add(function (effect) {
  74647. var texelSize = _this.texelSize;
  74648. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  74649. });
  74650. return _this;
  74651. }
  74652. FxaaPostProcess.prototype._getDefines = function () {
  74653. var engine = this.getEngine();
  74654. if (!engine) {
  74655. return null;
  74656. }
  74657. var glInfo = engine.getGlInfo();
  74658. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  74659. return "#define MALI 1\n";
  74660. }
  74661. return null;
  74662. };
  74663. return FxaaPostProcess;
  74664. }(BABYLON.PostProcess));
  74665. BABYLON.FxaaPostProcess = FxaaPostProcess;
  74666. })(BABYLON || (BABYLON = {}));
  74667. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  74668. var BABYLON;
  74669. (function (BABYLON) {
  74670. /**
  74671. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  74672. */
  74673. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  74674. __extends(ChromaticAberrationPostProcess, _super);
  74675. /**
  74676. * Creates a new instance ChromaticAberrationPostProcess
  74677. * @param name The name of the effect.
  74678. * @param screenWidth The width of the screen to apply the effect on.
  74679. * @param screenHeight The height of the screen to apply the effect on.
  74680. * @param options The required width/height ratio to downsize to before computing the render pass.
  74681. * @param camera The camera to apply the render pass to.
  74682. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74683. * @param engine The engine which the post process will be applied. (default: current engine)
  74684. * @param reusable If the post process can be reused on the same frame. (default: false)
  74685. * @param textureType Type of textures used when performing the post process. (default: 0)
  74686. * @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)
  74687. */
  74688. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74689. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74690. if (blockCompilation === void 0) { blockCompilation = false; }
  74691. 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;
  74692. /**
  74693. * The amount of seperation of rgb channels (default: 30)
  74694. */
  74695. _this.aberrationAmount = 30;
  74696. /**
  74697. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  74698. */
  74699. _this.radialIntensity = 0;
  74700. /**
  74701. * 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))
  74702. */
  74703. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  74704. /**
  74705. * 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))
  74706. */
  74707. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  74708. _this.onApplyObservable.add(function (effect) {
  74709. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  74710. effect.setFloat('screen_width', screenWidth);
  74711. effect.setFloat('screen_height', screenHeight);
  74712. effect.setFloat('radialIntensity', _this.radialIntensity);
  74713. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  74714. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  74715. });
  74716. return _this;
  74717. }
  74718. return ChromaticAberrationPostProcess;
  74719. }(BABYLON.PostProcess));
  74720. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  74721. })(BABYLON || (BABYLON = {}));
  74722. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  74723. var BABYLON;
  74724. (function (BABYLON) {
  74725. /**
  74726. * The GrainPostProcess adds noise to the image at mid luminance levels
  74727. */
  74728. var GrainPostProcess = /** @class */ (function (_super) {
  74729. __extends(GrainPostProcess, _super);
  74730. /**
  74731. * Creates a new instance of @see GrainPostProcess
  74732. * @param name The name of the effect.
  74733. * @param options The required width/height ratio to downsize to before computing the render pass.
  74734. * @param camera The camera to apply the render pass to.
  74735. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74736. * @param engine The engine which the post process will be applied. (default: current engine)
  74737. * @param reusable If the post process can be reused on the same frame. (default: false)
  74738. * @param textureType Type of textures used when performing the post process. (default: 0)
  74739. * @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)
  74740. */
  74741. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74742. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74743. if (blockCompilation === void 0) { blockCompilation = false; }
  74744. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74745. /**
  74746. * The intensity of the grain added (default: 30)
  74747. */
  74748. _this.intensity = 30;
  74749. /**
  74750. * If the grain should be randomized on every frame
  74751. */
  74752. _this.animated = false;
  74753. _this.onApplyObservable.add(function (effect) {
  74754. effect.setFloat('intensity', _this.intensity);
  74755. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  74756. });
  74757. return _this;
  74758. }
  74759. return GrainPostProcess;
  74760. }(BABYLON.PostProcess));
  74761. BABYLON.GrainPostProcess = GrainPostProcess;
  74762. })(BABYLON || (BABYLON = {}));
  74763. //# sourceMappingURL=babylon.grainPostProcess.js.map
  74764. var BABYLON;
  74765. (function (BABYLON) {
  74766. /**
  74767. * The SharpenPostProcess applies a sharpen kernel to every pixel
  74768. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  74769. */
  74770. var SharpenPostProcess = /** @class */ (function (_super) {
  74771. __extends(SharpenPostProcess, _super);
  74772. /**
  74773. * Creates a new instance ConvolutionPostProcess
  74774. * @param name The name of the effect.
  74775. * @param options The required width/height ratio to downsize to before computing the render pass.
  74776. * @param camera The camera to apply the render pass to.
  74777. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74778. * @param engine The engine which the post process will be applied. (default: current engine)
  74779. * @param reusable If the post process can be reused on the same frame. (default: false)
  74780. * @param textureType Type of textures used when performing the post process. (default: 0)
  74781. * @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)
  74782. */
  74783. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  74784. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74785. if (blockCompilation === void 0) { blockCompilation = false; }
  74786. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  74787. /**
  74788. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  74789. */
  74790. _this.colorAmount = 1.0;
  74791. /**
  74792. * How much sharpness should be applied (default: 0.3)
  74793. */
  74794. _this.edgeAmount = 0.3;
  74795. _this.onApply = function (effect) {
  74796. effect.setFloat2("screenSize", _this.width, _this.height);
  74797. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  74798. };
  74799. return _this;
  74800. }
  74801. return SharpenPostProcess;
  74802. }(BABYLON.PostProcess));
  74803. BABYLON.SharpenPostProcess = SharpenPostProcess;
  74804. })(BABYLON || (BABYLON = {}));
  74805. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  74806. var BABYLON;
  74807. (function (BABYLON) {
  74808. /**
  74809. * The Blur Post Process which blurs an image based on a kernel and direction.
  74810. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  74811. */
  74812. var BlurPostProcess = /** @class */ (function (_super) {
  74813. __extends(BlurPostProcess, _super);
  74814. /**
  74815. * Creates a new instance BlurPostProcess
  74816. * @param name The name of the effect.
  74817. * @param direction The direction in which to blur the image.
  74818. * @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.
  74819. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  74820. * @param camera The camera to apply the render pass to.
  74821. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  74822. * @param engine The engine which the post process will be applied. (default: current engine)
  74823. * @param reusable If the post process can be reused on the same frame. (default: false)
  74824. * @param textureType Type of textures used when performing the post process. (default: 0)
  74825. * @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)
  74826. */
  74827. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  74828. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  74829. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  74830. if (defines === void 0) { defines = ""; }
  74831. if (blockCompilation === void 0) { blockCompilation = false; }
  74832. 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;
  74833. _this.direction = direction;
  74834. _this.blockCompilation = blockCompilation;
  74835. _this._packedFloat = false;
  74836. _this._staticDefines = "";
  74837. _this._staticDefines = defines;
  74838. _this.onApplyObservable.add(function (effect) {
  74839. if (_this._outputTexture) {
  74840. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  74841. }
  74842. else {
  74843. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  74844. }
  74845. });
  74846. _this.kernel = kernel;
  74847. return _this;
  74848. }
  74849. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  74850. /**
  74851. * Gets the length in pixels of the blur sample region
  74852. */
  74853. get: function () {
  74854. return this._idealKernel;
  74855. },
  74856. /**
  74857. * Sets the length in pixels of the blur sample region
  74858. */
  74859. set: function (v) {
  74860. if (this._idealKernel === v) {
  74861. return;
  74862. }
  74863. v = Math.max(v, 1);
  74864. this._idealKernel = v;
  74865. this._kernel = this._nearestBestKernel(v);
  74866. if (!this.blockCompilation) {
  74867. this._updateParameters();
  74868. }
  74869. },
  74870. enumerable: true,
  74871. configurable: true
  74872. });
  74873. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  74874. /**
  74875. * Gets wether or not the blur is unpacking/repacking floats
  74876. */
  74877. get: function () {
  74878. return this._packedFloat;
  74879. },
  74880. /**
  74881. * Sets wether or not the blur needs to unpack/repack floats
  74882. */
  74883. set: function (v) {
  74884. if (this._packedFloat === v) {
  74885. return;
  74886. }
  74887. this._packedFloat = v;
  74888. if (!this.blockCompilation) {
  74889. this._updateParameters();
  74890. }
  74891. },
  74892. enumerable: true,
  74893. configurable: true
  74894. });
  74895. /**
  74896. * Updates the effect with the current post process compile time values and recompiles the shader.
  74897. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  74898. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  74899. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  74900. * @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
  74901. * @param onCompiled Called when the shader has been compiled.
  74902. * @param onError Called if there is an error when compiling a shader.
  74903. */
  74904. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  74905. if (defines === void 0) { defines = null; }
  74906. if (uniforms === void 0) { uniforms = null; }
  74907. if (samplers === void 0) { samplers = null; }
  74908. this._updateParameters(onCompiled, onError);
  74909. };
  74910. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  74911. // Generate sampling offsets and weights
  74912. var N = this._kernel;
  74913. var centerIndex = (N - 1) / 2;
  74914. // Generate Gaussian sampling weights over kernel
  74915. var offsets = [];
  74916. var weights = [];
  74917. var totalWeight = 0;
  74918. for (var i = 0; i < N; i++) {
  74919. var u = i / (N - 1);
  74920. var w = this._gaussianWeight(u * 2.0 - 1);
  74921. offsets[i] = (i - centerIndex);
  74922. weights[i] = w;
  74923. totalWeight += w;
  74924. }
  74925. // Normalize weights
  74926. for (var i = 0; i < weights.length; i++) {
  74927. weights[i] /= totalWeight;
  74928. }
  74929. // Optimize: combine samples to take advantage of hardware linear sampling
  74930. // Walk from left to center, combining pairs (symmetrically)
  74931. var linearSamplingWeights = [];
  74932. var linearSamplingOffsets = [];
  74933. var linearSamplingMap = [];
  74934. for (var i = 0; i <= centerIndex; i += 2) {
  74935. var j = Math.min(i + 1, Math.floor(centerIndex));
  74936. var singleCenterSample = i === j;
  74937. if (singleCenterSample) {
  74938. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74939. }
  74940. else {
  74941. var sharedCell = j === centerIndex;
  74942. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  74943. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  74944. if (offsetLinear === 0) {
  74945. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  74946. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  74947. }
  74948. else {
  74949. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  74950. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  74951. }
  74952. }
  74953. }
  74954. for (var i = 0; i < linearSamplingMap.length; i++) {
  74955. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  74956. linearSamplingWeights[i] = linearSamplingMap[i].w;
  74957. }
  74958. // Replace with optimized
  74959. offsets = linearSamplingOffsets;
  74960. weights = linearSamplingWeights;
  74961. // Generate shaders
  74962. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  74963. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  74964. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  74965. var defines = "";
  74966. defines += this._staticDefines;
  74967. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  74968. if (this._staticDefines.indexOf("DOF") != -1) {
  74969. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  74970. varyingCount--;
  74971. }
  74972. for (var i = 0; i < varyingCount; i++) {
  74973. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  74974. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  74975. }
  74976. var depCount = 0;
  74977. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  74978. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  74979. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  74980. depCount++;
  74981. }
  74982. if (this.packedFloat) {
  74983. defines += "#define PACKEDFLOAT 1";
  74984. }
  74985. this.blockCompilation = false;
  74986. _super.prototype.updateEffect.call(this, defines, null, null, {
  74987. varyingCount: varyingCount,
  74988. depCount: depCount
  74989. }, onCompiled, onError);
  74990. };
  74991. /**
  74992. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  74993. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  74994. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  74995. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  74996. * The gaps between physical kernels are compensated for in the weighting of the samples
  74997. * @param idealKernel Ideal blur kernel.
  74998. * @return Nearest best kernel.
  74999. */
  75000. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75001. var v = Math.round(idealKernel);
  75002. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75003. var k = _a[_i];
  75004. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75005. return Math.max(k, 3);
  75006. }
  75007. }
  75008. return Math.max(v, 3);
  75009. };
  75010. /**
  75011. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75012. * @param x The point on the Gaussian distribution to sample.
  75013. * @return the value of the Gaussian function at x.
  75014. */
  75015. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75016. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75017. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75018. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75019. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75020. // truncated at around 1.3% of peak strength.
  75021. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75022. var sigma = (1 / 3);
  75023. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75024. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75025. var weight = (1.0 / denominator) * Math.exp(exponent);
  75026. return weight;
  75027. };
  75028. /**
  75029. * Generates a string that can be used as a floating point number in GLSL.
  75030. * @param x Value to print.
  75031. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75032. * @return GLSL float string.
  75033. */
  75034. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75035. if (decimalFigures === void 0) { decimalFigures = 8; }
  75036. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75037. };
  75038. return BlurPostProcess;
  75039. }(BABYLON.PostProcess));
  75040. BABYLON.BlurPostProcess = BlurPostProcess;
  75041. })(BABYLON || (BABYLON = {}));
  75042. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75043. var BABYLON;
  75044. (function (BABYLON) {
  75045. /**
  75046. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75047. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75048. * based on samples that have a large difference in distance than the center pixel.
  75049. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75050. */
  75051. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75052. __extends(DepthOfFieldBlurPostProcess, _super);
  75053. /**
  75054. * Creates a new instance CircleOfConfusionPostProcess
  75055. * @param name The name of the effect.
  75056. * @param scene The scene the effect belongs to.
  75057. * @param direction The direction the blur should be applied.
  75058. * @param kernel The size of the kernel used to blur.
  75059. * @param options The required width/height ratio to downsize to before computing the render pass.
  75060. * @param camera The camera to apply the render pass to.
  75061. * @param circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75062. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75063. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75064. * @param engine The engine which the post process will be applied. (default: current engine)
  75065. * @param reusable If the post process can be reused on the same frame. (default: false)
  75066. * @param textureType Type of textures used when performing the post process. (default: 0)
  75067. * @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)
  75068. */
  75069. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75070. if (imageToBlur === void 0) { imageToBlur = null; }
  75071. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75072. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75073. if (blockCompilation === void 0) { blockCompilation = false; }
  75074. 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;
  75075. _this.direction = direction;
  75076. _this.onApplyObservable.add(function (effect) {
  75077. if (imageToBlur != null) {
  75078. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75079. }
  75080. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75081. if (scene.activeCamera) {
  75082. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75083. }
  75084. });
  75085. return _this;
  75086. }
  75087. return DepthOfFieldBlurPostProcess;
  75088. }(BABYLON.BlurPostProcess));
  75089. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75090. })(BABYLON || (BABYLON = {}));
  75091. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75092. var BABYLON;
  75093. (function (BABYLON) {
  75094. /**
  75095. * Options to be set when merging outputs from the default pipeline.
  75096. */
  75097. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75098. function DepthOfFieldMergePostProcessOptions() {
  75099. }
  75100. return DepthOfFieldMergePostProcessOptions;
  75101. }());
  75102. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75103. /**
  75104. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75105. */
  75106. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75107. __extends(DepthOfFieldMergePostProcess, _super);
  75108. /**
  75109. * Creates a new instance of DepthOfFieldMergePostProcess
  75110. * @param name The name of the effect.
  75111. * @param originalFromInput Post process which's input will be used for the merge.
  75112. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75113. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75114. * @param options The required width/height ratio to downsize to before computing the render pass.
  75115. * @param camera The camera to apply the render pass to.
  75116. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75117. * @param engine The engine which the post process will be applied. (default: current engine)
  75118. * @param reusable If the post process can be reused on the same frame. (default: false)
  75119. * @param textureType Type of textures used when performing the post process. (default: 0)
  75120. * @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)
  75121. */
  75122. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75123. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75124. if (blockCompilation === void 0) { blockCompilation = false; }
  75125. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75126. _this.blurSteps = blurSteps;
  75127. _this.onApplyObservable.add(function (effect) {
  75128. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75129. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75130. blurSteps.forEach(function (step, index) {
  75131. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75132. });
  75133. });
  75134. if (!blockCompilation) {
  75135. _this.updateEffect();
  75136. }
  75137. return _this;
  75138. }
  75139. /**
  75140. * Updates the effect with the current post process compile time values and recompiles the shader.
  75141. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75142. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75143. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75144. * @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
  75145. * @param onCompiled Called when the shader has been compiled.
  75146. * @param onError Called if there is an error when compiling a shader.
  75147. */
  75148. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75149. if (defines === void 0) { defines = null; }
  75150. if (uniforms === void 0) { uniforms = null; }
  75151. if (samplers === void 0) { samplers = null; }
  75152. if (!defines) {
  75153. defines = "";
  75154. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75155. }
  75156. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75157. };
  75158. return DepthOfFieldMergePostProcess;
  75159. }(BABYLON.PostProcess));
  75160. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75161. })(BABYLON || (BABYLON = {}));
  75162. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75163. var BABYLON;
  75164. (function (BABYLON) {
  75165. /**
  75166. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75167. */
  75168. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75169. __extends(CircleOfConfusionPostProcess, _super);
  75170. /**
  75171. * Creates a new instance CircleOfConfusionPostProcess
  75172. * @param name The name of the effect.
  75173. * @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.
  75174. * @param options The required width/height ratio to downsize to before computing the render pass.
  75175. * @param camera The camera to apply the render pass to.
  75176. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75177. * @param engine The engine which the post process will be applied. (default: current engine)
  75178. * @param reusable If the post process can be reused on the same frame. (default: false)
  75179. * @param textureType Type of textures used when performing the post process. (default: 0)
  75180. * @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)
  75181. */
  75182. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75183. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75184. if (blockCompilation === void 0) { blockCompilation = false; }
  75185. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75186. /**
  75187. * 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.
  75188. */
  75189. _this.lensSize = 50;
  75190. /**
  75191. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75192. */
  75193. _this.fStop = 1.4;
  75194. /**
  75195. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75196. */
  75197. _this.focusDistance = 2000;
  75198. /**
  75199. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75200. */
  75201. _this.focalLength = 50;
  75202. _this._depthTexture = null;
  75203. _this._depthTexture = depthTexture;
  75204. _this.onApplyObservable.add(function (effect) {
  75205. if (!_this._depthTexture) {
  75206. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75207. return;
  75208. }
  75209. effect.setTexture("depthSampler", _this._depthTexture);
  75210. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75211. var aperture = _this.lensSize / _this.fStop;
  75212. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75213. effect.setFloat('focusDistance', _this.focusDistance);
  75214. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75215. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75216. });
  75217. return _this;
  75218. }
  75219. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75220. /**
  75221. * 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.
  75222. */
  75223. set: function (value) {
  75224. this._depthTexture = value;
  75225. },
  75226. enumerable: true,
  75227. configurable: true
  75228. });
  75229. return CircleOfConfusionPostProcess;
  75230. }(BABYLON.PostProcess));
  75231. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75232. })(BABYLON || (BABYLON = {}));
  75233. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75234. var BABYLON;
  75235. (function (BABYLON) {
  75236. /**
  75237. * Specifies the level of max blur that should be applied when using the depth of field effect
  75238. */
  75239. var DepthOfFieldEffectBlurLevel;
  75240. (function (DepthOfFieldEffectBlurLevel) {
  75241. /**
  75242. * Subtle blur
  75243. */
  75244. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75245. /**
  75246. * Medium blur
  75247. */
  75248. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75249. /**
  75250. * Large blur
  75251. */
  75252. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75253. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75254. ;
  75255. /**
  75256. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75257. */
  75258. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75259. __extends(DepthOfFieldEffect, _super);
  75260. /**
  75261. * Creates a new instance DepthOfFieldEffect
  75262. * @param scene The scene the effect belongs to.
  75263. * @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.
  75264. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75265. * @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)
  75266. */
  75267. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75268. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75269. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75270. if (blockCompilation === void 0) { blockCompilation = false; }
  75271. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75272. return _this._effects;
  75273. }, true) || this;
  75274. /**
  75275. * Internal post processes in depth of field effect
  75276. */
  75277. _this._effects = [];
  75278. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75279. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75280. // 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)
  75281. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75282. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75283. _this._depthOfFieldBlurY = [];
  75284. _this._depthOfFieldBlurX = [];
  75285. var blurCount = 1;
  75286. var kernelSize = 15;
  75287. switch (blurLevel) {
  75288. case DepthOfFieldEffectBlurLevel.High: {
  75289. blurCount = 3;
  75290. kernelSize = 51;
  75291. break;
  75292. }
  75293. case DepthOfFieldEffectBlurLevel.Medium: {
  75294. blurCount = 2;
  75295. kernelSize = 31;
  75296. break;
  75297. }
  75298. default: {
  75299. kernelSize = 15;
  75300. blurCount = 1;
  75301. break;
  75302. }
  75303. }
  75304. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75305. var ratio = 1.0;
  75306. for (var i = 0; i < blurCount; i++) {
  75307. 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);
  75308. blurY.autoClear = false;
  75309. ratio = 0.75 / Math.pow(2, i);
  75310. 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);
  75311. blurX.autoClear = false;
  75312. _this._depthOfFieldBlurY.push(blurY);
  75313. _this._depthOfFieldBlurX.push(blurX);
  75314. }
  75315. // Set all post processes on the effect.
  75316. _this._effects = [_this._circleOfConfusion];
  75317. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75318. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75319. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75320. }
  75321. // Merge blurred images with original image based on circleOfConfusion
  75322. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75323. _this._dofMerge.autoClear = false;
  75324. _this._effects.push(_this._dofMerge);
  75325. return _this;
  75326. }
  75327. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75328. get: function () {
  75329. return this._circleOfConfusion.focalLength;
  75330. },
  75331. /**
  75332. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75333. */
  75334. set: function (value) {
  75335. this._circleOfConfusion.focalLength = value;
  75336. },
  75337. enumerable: true,
  75338. configurable: true
  75339. });
  75340. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75341. get: function () {
  75342. return this._circleOfConfusion.fStop;
  75343. },
  75344. /**
  75345. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75346. */
  75347. set: function (value) {
  75348. this._circleOfConfusion.fStop = value;
  75349. },
  75350. enumerable: true,
  75351. configurable: true
  75352. });
  75353. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75354. get: function () {
  75355. return this._circleOfConfusion.focusDistance;
  75356. },
  75357. /**
  75358. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75359. */
  75360. set: function (value) {
  75361. this._circleOfConfusion.focusDistance = value;
  75362. },
  75363. enumerable: true,
  75364. configurable: true
  75365. });
  75366. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75367. get: function () {
  75368. return this._circleOfConfusion.lensSize;
  75369. },
  75370. /**
  75371. * 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.
  75372. */
  75373. set: function (value) {
  75374. this._circleOfConfusion.lensSize = value;
  75375. },
  75376. enumerable: true,
  75377. configurable: true
  75378. });
  75379. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  75380. /**
  75381. * 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.
  75382. */
  75383. set: function (value) {
  75384. this._circleOfConfusion.depthTexture = value;
  75385. },
  75386. enumerable: true,
  75387. configurable: true
  75388. });
  75389. /**
  75390. * Disposes each of the internal effects for a given camera.
  75391. * @param camera The camera to dispose the effect on.
  75392. */
  75393. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  75394. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75395. this._effects[effectIndex].dispose(camera);
  75396. }
  75397. };
  75398. /**
  75399. * Internal
  75400. */
  75401. DepthOfFieldEffect.prototype._updateEffects = function () {
  75402. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75403. this._effects[effectIndex].updateEffect();
  75404. }
  75405. };
  75406. /**
  75407. * Internal
  75408. * @returns if all the contained post processes are ready.
  75409. */
  75410. DepthOfFieldEffect.prototype._isReady = function () {
  75411. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75412. if (!this._effects[effectIndex].isReady()) {
  75413. return false;
  75414. }
  75415. }
  75416. return true;
  75417. };
  75418. return DepthOfFieldEffect;
  75419. }(BABYLON.PostProcessRenderEffect));
  75420. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  75421. })(BABYLON || (BABYLON = {}));
  75422. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  75423. var BABYLON;
  75424. (function (BABYLON) {
  75425. /**
  75426. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75427. */
  75428. var BloomMergePostProcess = /** @class */ (function (_super) {
  75429. __extends(BloomMergePostProcess, _super);
  75430. /**
  75431. * Creates a new instance of @see BloomMergePostProcess
  75432. * @param name The name of the effect.
  75433. * @param originalFromInput Post process which's input will be used for the merge.
  75434. * @param blurred Blurred highlights post process which's output will be used.
  75435. * @param weight Weight of the bloom to be added to the original input.
  75436. * @param options The required width/height ratio to downsize to before computing the render pass.
  75437. * @param camera The camera to apply the render pass to.
  75438. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75439. * @param engine The engine which the post process will be applied. (default: current engine)
  75440. * @param reusable If the post process can be reused on the same frame. (default: false)
  75441. * @param textureType Type of textures used when performing the post process. (default: 0)
  75442. * @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)
  75443. */
  75444. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75445. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75446. if (blockCompilation === void 0) { blockCompilation = false; }
  75447. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75448. _this.weight = weight;
  75449. _this.onApplyObservable.add(function (effect) {
  75450. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75451. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  75452. effect.setFloat("bloomWeight", _this.weight);
  75453. });
  75454. if (!blockCompilation) {
  75455. _this.updateEffect();
  75456. }
  75457. return _this;
  75458. }
  75459. return BloomMergePostProcess;
  75460. }(BABYLON.PostProcess));
  75461. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  75462. })(BABYLON || (BABYLON = {}));
  75463. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  75464. var BABYLON;
  75465. (function (BABYLON) {
  75466. /**
  75467. * 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.
  75468. */
  75469. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  75470. __extends(ExtractHighlightsPostProcess, _super);
  75471. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75472. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75473. if (blockCompilation === void 0) { blockCompilation = false; }
  75474. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75475. /**
  75476. * The luminance threshold, pixels below this value will be set to black.
  75477. */
  75478. _this.threshold = 0.9;
  75479. /**
  75480. * Internal
  75481. */
  75482. _this._exposure = 1;
  75483. /**
  75484. * Post process which has the input texture to be used when performing highlight extraction
  75485. */
  75486. _this._inputPostProcess = null;
  75487. _this.onApplyObservable.add(function (effect) {
  75488. if (_this._inputPostProcess) {
  75489. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  75490. }
  75491. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  75492. effect.setFloat('exposure', _this._exposure);
  75493. });
  75494. return _this;
  75495. }
  75496. return ExtractHighlightsPostProcess;
  75497. }(BABYLON.PostProcess));
  75498. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  75499. })(BABYLON || (BABYLON = {}));
  75500. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  75501. var BABYLON;
  75502. (function (BABYLON) {
  75503. /**
  75504. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  75505. */
  75506. var BloomEffect = /** @class */ (function (_super) {
  75507. __extends(BloomEffect, _super);
  75508. /**
  75509. * Creates a new instance of @see BloomEffect
  75510. * @param scene The scene the effect belongs to.
  75511. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  75512. * @param bloomKernel The size of the kernel to be used when applying the blur.
  75513. * @param bloomWeight The the strength of bloom.
  75514. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75515. * @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)
  75516. */
  75517. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  75518. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75519. if (blockCompilation === void 0) { blockCompilation = false; }
  75520. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  75521. return _this._effects;
  75522. }, true) || this;
  75523. _this.bloomScale = bloomScale;
  75524. /**
  75525. * Internal
  75526. */
  75527. _this._effects = [];
  75528. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75529. _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);
  75530. _this._blurX.alwaysForcePOT = true;
  75531. _this._blurX.autoClear = false;
  75532. _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);
  75533. _this._blurY.alwaysForcePOT = true;
  75534. _this._blurY.autoClear = false;
  75535. _this.kernel = bloomKernel;
  75536. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  75537. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75538. _this._merge.autoClear = false;
  75539. _this._effects.push(_this._merge);
  75540. return _this;
  75541. }
  75542. Object.defineProperty(BloomEffect.prototype, "threshold", {
  75543. /**
  75544. * The luminance threshold to find bright areas of the image to bloom.
  75545. */
  75546. get: function () {
  75547. return this._downscale.threshold;
  75548. },
  75549. set: function (value) {
  75550. this._downscale.threshold = value;
  75551. },
  75552. enumerable: true,
  75553. configurable: true
  75554. });
  75555. Object.defineProperty(BloomEffect.prototype, "weight", {
  75556. /**
  75557. * The strength of the bloom.
  75558. */
  75559. get: function () {
  75560. return this._merge.weight;
  75561. },
  75562. set: function (value) {
  75563. this._merge.weight = value;
  75564. },
  75565. enumerable: true,
  75566. configurable: true
  75567. });
  75568. Object.defineProperty(BloomEffect.prototype, "kernel", {
  75569. /**
  75570. * Specifies the size of the bloom blur kernel, relative to the final output size
  75571. */
  75572. get: function () {
  75573. return this._blurX.kernel / this.bloomScale;
  75574. },
  75575. set: function (value) {
  75576. this._blurX.kernel = value * this.bloomScale;
  75577. this._blurY.kernel = value * this.bloomScale;
  75578. },
  75579. enumerable: true,
  75580. configurable: true
  75581. });
  75582. /**
  75583. * Disposes each of the internal effects for a given camera.
  75584. * @param camera The camera to dispose the effect on.
  75585. */
  75586. BloomEffect.prototype.disposeEffects = function (camera) {
  75587. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75588. this._effects[effectIndex].dispose(camera);
  75589. }
  75590. };
  75591. /**
  75592. * Internal
  75593. */
  75594. BloomEffect.prototype._updateEffects = function () {
  75595. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75596. this._effects[effectIndex].updateEffect();
  75597. }
  75598. };
  75599. /**
  75600. * Internal
  75601. * @returns if all the contained post processes are ready.
  75602. */
  75603. BloomEffect.prototype._isReady = function () {
  75604. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  75605. if (!this._effects[effectIndex].isReady()) {
  75606. return false;
  75607. }
  75608. }
  75609. return true;
  75610. };
  75611. return BloomEffect;
  75612. }(BABYLON.PostProcessRenderEffect));
  75613. BABYLON.BloomEffect = BloomEffect;
  75614. })(BABYLON || (BABYLON = {}));
  75615. //# sourceMappingURL=babylon.bloomEffect.js.map
  75616. var BABYLON;
  75617. (function (BABYLON) {
  75618. /**
  75619. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  75620. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  75621. */
  75622. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  75623. __extends(DefaultRenderingPipeline, _super);
  75624. /**
  75625. * @constructor
  75626. * @param {string} name - The rendering pipeline name
  75627. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  75628. * @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)
  75629. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  75630. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline
  75631. */
  75632. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  75633. if (automaticBuild === void 0) { automaticBuild = true; }
  75634. var _this = _super.call(this, scene.getEngine(), name) || this;
  75635. _this._originalCameras = [];
  75636. /**
  75637. * ID of the sharpen post process,
  75638. */
  75639. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  75640. /**
  75641. * ID of the image processing post process;
  75642. */
  75643. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  75644. /**
  75645. * ID of the Fast Approximate Anti-Aliasing post process;
  75646. */
  75647. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  75648. /**
  75649. * ID of the chromatic aberration post process,
  75650. */
  75651. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  75652. /**
  75653. * ID of the grain post process
  75654. */
  75655. _this.GrainPostProcessId = "GrainPostProcessEffect";
  75656. /**
  75657. * Animations which can be used to tweak settings over a period of time
  75658. */
  75659. _this.animations = [];
  75660. _this._imageProcessingConfigurationObserver = null;
  75661. // Values
  75662. _this._sharpenEnabled = false;
  75663. _this._bloomEnabled = false;
  75664. _this._depthOfFieldEnabled = false;
  75665. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  75666. _this._fxaaEnabled = false;
  75667. _this._imageProcessingEnabled = true;
  75668. _this._bloomScale = 0.5;
  75669. _this._chromaticAberrationEnabled = false;
  75670. _this._grainEnabled = false;
  75671. _this._buildAllowed = true;
  75672. _this._resizeObserver = null;
  75673. _this._hardwareScaleLevel = 1.0;
  75674. _this._bloomKernel = 64;
  75675. /**
  75676. * Specifies the weight of the bloom in the final rendering
  75677. */
  75678. _this._bloomWeight = 0.15;
  75679. /**
  75680. * Specifies the luma threshold for the area that will be blurred by the bloom
  75681. */
  75682. _this._bloomThreshold = 0.9;
  75683. _this._samples = 1;
  75684. _this._hasCleared = false;
  75685. _this._prevPostProcess = null;
  75686. _this._prevPrevPostProcess = null;
  75687. _this._cameras = cameras || [];
  75688. _this._originalCameras = _this._cameras.slice();
  75689. _this._buildAllowed = automaticBuild;
  75690. // Initialize
  75691. _this._scene = scene;
  75692. var caps = _this._scene.getEngine().getCaps();
  75693. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  75694. // Misc
  75695. if (_this._hdr) {
  75696. if (caps.textureHalfFloatRender) {
  75697. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  75698. }
  75699. else if (caps.textureFloatRender) {
  75700. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  75701. }
  75702. }
  75703. else {
  75704. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  75705. }
  75706. // Attach
  75707. scene.postProcessRenderPipelineManager.addPipeline(_this);
  75708. var engine = _this._scene.getEngine();
  75709. // Create post processes before hand so they can be modified before enabled.
  75710. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  75711. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75712. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  75713. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  75714. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  75715. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75716. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  75717. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  75718. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  75719. _this._resizeObserver = engine.onResizeObservable.add(function () {
  75720. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  75721. _this.bloomKernel = _this.bloomKernel;
  75722. });
  75723. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  75724. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  75725. });
  75726. _this._buildPipeline();
  75727. return _this;
  75728. }
  75729. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  75730. get: function () {
  75731. return this._sharpenEnabled;
  75732. },
  75733. /**
  75734. * Enable or disable the sharpen process from the pipeline
  75735. */
  75736. set: function (enabled) {
  75737. if (this._sharpenEnabled === enabled) {
  75738. return;
  75739. }
  75740. this._sharpenEnabled = enabled;
  75741. this._buildPipeline();
  75742. },
  75743. enumerable: true,
  75744. configurable: true
  75745. });
  75746. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  75747. /**
  75748. * Specifies the size of the bloom blur kernel, relative to the final output size
  75749. */
  75750. get: function () {
  75751. return this._bloomKernel;
  75752. },
  75753. set: function (value) {
  75754. this._bloomKernel = value;
  75755. this.bloom.kernel = value / this._hardwareScaleLevel;
  75756. },
  75757. enumerable: true,
  75758. configurable: true
  75759. });
  75760. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  75761. get: function () {
  75762. return this._bloomWeight;
  75763. },
  75764. /**
  75765. * The strength of the bloom.
  75766. */
  75767. set: function (value) {
  75768. if (this._bloomWeight === value) {
  75769. return;
  75770. }
  75771. this.bloom.weight = value;
  75772. this._bloomWeight = value;
  75773. },
  75774. enumerable: true,
  75775. configurable: true
  75776. });
  75777. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  75778. get: function () {
  75779. return this._bloomThreshold;
  75780. },
  75781. /**
  75782. * The strength of the bloom.
  75783. */
  75784. set: function (value) {
  75785. if (this._bloomThreshold === value) {
  75786. return;
  75787. }
  75788. this.bloom.threshold = value;
  75789. this._bloomThreshold = value;
  75790. },
  75791. enumerable: true,
  75792. configurable: true
  75793. });
  75794. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  75795. get: function () {
  75796. return this._bloomScale;
  75797. },
  75798. /**
  75799. * The scale of the bloom, lower value will provide better performance.
  75800. */
  75801. set: function (value) {
  75802. if (this._bloomScale === value) {
  75803. return;
  75804. }
  75805. this._bloomScale = value;
  75806. // recreate bloom and dispose old as this setting is not dynamic
  75807. this._rebuildBloom();
  75808. this._buildPipeline();
  75809. },
  75810. enumerable: true,
  75811. configurable: true
  75812. });
  75813. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  75814. get: function () {
  75815. return this._bloomEnabled;
  75816. },
  75817. /**
  75818. * Enable or disable the bloom from the pipeline
  75819. */
  75820. set: function (enabled) {
  75821. if (this._bloomEnabled === enabled) {
  75822. return;
  75823. }
  75824. this._bloomEnabled = enabled;
  75825. this._buildPipeline();
  75826. },
  75827. enumerable: true,
  75828. configurable: true
  75829. });
  75830. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  75831. // recreate bloom and dispose old as this setting is not dynamic
  75832. var oldBloom = this.bloom;
  75833. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  75834. this.bloom.threshold = oldBloom.threshold;
  75835. for (var i = 0; i < this._cameras.length; i++) {
  75836. oldBloom.disposeEffects(this._cameras[i]);
  75837. }
  75838. };
  75839. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  75840. /**
  75841. * If the depth of field is enabled.
  75842. */
  75843. get: function () {
  75844. return this._depthOfFieldEnabled;
  75845. },
  75846. set: function (enabled) {
  75847. if (this._depthOfFieldEnabled === enabled) {
  75848. return;
  75849. }
  75850. this._depthOfFieldEnabled = enabled;
  75851. this._buildPipeline();
  75852. },
  75853. enumerable: true,
  75854. configurable: true
  75855. });
  75856. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  75857. /**
  75858. * Blur level of the depth of field effect. (Higher blur will effect performance)
  75859. */
  75860. get: function () {
  75861. return this._depthOfFieldBlurLevel;
  75862. },
  75863. set: function (value) {
  75864. if (this._depthOfFieldBlurLevel === value) {
  75865. return;
  75866. }
  75867. this._depthOfFieldBlurLevel = value;
  75868. // recreate dof and dispose old as this setting is not dynamic
  75869. var oldDof = this.depthOfField;
  75870. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  75871. this.depthOfField.focalLength = oldDof.focalLength;
  75872. this.depthOfField.focusDistance = oldDof.focusDistance;
  75873. this.depthOfField.fStop = oldDof.fStop;
  75874. this.depthOfField.lensSize = oldDof.lensSize;
  75875. for (var i = 0; i < this._cameras.length; i++) {
  75876. oldDof.disposeEffects(this._cameras[i]);
  75877. }
  75878. this._buildPipeline();
  75879. },
  75880. enumerable: true,
  75881. configurable: true
  75882. });
  75883. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  75884. get: function () {
  75885. return this._fxaaEnabled;
  75886. },
  75887. /**
  75888. * If the anti aliasing is enabled.
  75889. */
  75890. set: function (enabled) {
  75891. if (this._fxaaEnabled === enabled) {
  75892. return;
  75893. }
  75894. this._fxaaEnabled = enabled;
  75895. this._buildPipeline();
  75896. },
  75897. enumerable: true,
  75898. configurable: true
  75899. });
  75900. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  75901. get: function () {
  75902. return this._samples;
  75903. },
  75904. /**
  75905. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  75906. */
  75907. set: function (sampleCount) {
  75908. if (this._samples === sampleCount) {
  75909. return;
  75910. }
  75911. this._samples = sampleCount;
  75912. this._buildPipeline();
  75913. },
  75914. enumerable: true,
  75915. configurable: true
  75916. });
  75917. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  75918. get: function () {
  75919. return this._imageProcessingEnabled;
  75920. },
  75921. /**
  75922. * If image processing is enabled.
  75923. */
  75924. set: function (enabled) {
  75925. if (this._imageProcessingEnabled === enabled) {
  75926. return;
  75927. }
  75928. this._imageProcessingEnabled = enabled;
  75929. this._buildPipeline();
  75930. },
  75931. enumerable: true,
  75932. configurable: true
  75933. });
  75934. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  75935. get: function () {
  75936. return this._chromaticAberrationEnabled;
  75937. },
  75938. /**
  75939. * Enable or disable the chromaticAberration process from the pipeline
  75940. */
  75941. set: function (enabled) {
  75942. if (this._chromaticAberrationEnabled === enabled) {
  75943. return;
  75944. }
  75945. this._chromaticAberrationEnabled = enabled;
  75946. this._buildPipeline();
  75947. },
  75948. enumerable: true,
  75949. configurable: true
  75950. });
  75951. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  75952. get: function () {
  75953. return this._grainEnabled;
  75954. },
  75955. /**
  75956. * Enable or disable the grain process from the pipeline
  75957. */
  75958. set: function (enabled) {
  75959. if (this._grainEnabled === enabled) {
  75960. return;
  75961. }
  75962. this._grainEnabled = enabled;
  75963. this._buildPipeline();
  75964. },
  75965. enumerable: true,
  75966. configurable: true
  75967. });
  75968. /**
  75969. * Force the compilation of the entire pipeline.
  75970. */
  75971. DefaultRenderingPipeline.prototype.prepare = function () {
  75972. var previousState = this._buildAllowed;
  75973. this._buildAllowed = true;
  75974. this._buildPipeline();
  75975. this._buildAllowed = previousState;
  75976. };
  75977. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  75978. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  75979. if (this._hasCleared) {
  75980. postProcess.autoClear = false;
  75981. }
  75982. else {
  75983. postProcess.autoClear = true;
  75984. this._scene.autoClear = false;
  75985. this._hasCleared = true;
  75986. }
  75987. if (!skipTextureSharing) {
  75988. if (this._prevPrevPostProcess) {
  75989. postProcess.shareOutputWith(this._prevPrevPostProcess);
  75990. }
  75991. else {
  75992. postProcess.useOwnOutput();
  75993. }
  75994. if (this._prevPostProcess) {
  75995. this._prevPrevPostProcess = this._prevPostProcess;
  75996. }
  75997. this._prevPostProcess = postProcess;
  75998. }
  75999. };
  76000. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76001. var _this = this;
  76002. if (!this._buildAllowed) {
  76003. return;
  76004. }
  76005. this._scene.autoClear = true;
  76006. var engine = this._scene.getEngine();
  76007. this._disposePostProcesses();
  76008. if (this._cameras !== null) {
  76009. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76010. // get back cameras to be used to reattach pipeline
  76011. this._cameras = this._originalCameras.slice();
  76012. }
  76013. this._reset();
  76014. this._prevPostProcess = null;
  76015. this._prevPrevPostProcess = null;
  76016. this._hasCleared = false;
  76017. if (this.depthOfFieldEnabled) {
  76018. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76019. this.depthOfField.depthTexture = depthTexture;
  76020. if (!this.depthOfField._isReady()) {
  76021. this.depthOfField._updateEffects();
  76022. }
  76023. this.addEffect(this.depthOfField);
  76024. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76025. }
  76026. if (this.bloomEnabled) {
  76027. if (!this.bloom._isReady()) {
  76028. this.bloom._updateEffects();
  76029. }
  76030. this.addEffect(this.bloom);
  76031. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76032. }
  76033. if (this._imageProcessingEnabled) {
  76034. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76035. if (this._hdr) {
  76036. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76037. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76038. }
  76039. else {
  76040. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76041. }
  76042. }
  76043. if (this.sharpenEnabled) {
  76044. if (!this.sharpen.isReady()) {
  76045. this.sharpen.updateEffect();
  76046. }
  76047. this.addEffect(this._sharpenEffect);
  76048. this._setAutoClearAndTextureSharing(this.sharpen);
  76049. }
  76050. if (this.grainEnabled) {
  76051. if (!this.grain.isReady()) {
  76052. this.grain.updateEffect();
  76053. }
  76054. this.addEffect(this._grainEffect);
  76055. this._setAutoClearAndTextureSharing(this.grain);
  76056. }
  76057. if (this.chromaticAberrationEnabled) {
  76058. if (!this.chromaticAberration.isReady()) {
  76059. this.chromaticAberration.updateEffect();
  76060. }
  76061. this.addEffect(this._chromaticAberrationEffect);
  76062. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76063. }
  76064. if (this.fxaaEnabled) {
  76065. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76066. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76067. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76068. }
  76069. if (this._cameras !== null) {
  76070. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76071. }
  76072. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76073. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76074. }
  76075. };
  76076. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76077. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76078. for (var i = 0; i < this._cameras.length; i++) {
  76079. var camera = this._cameras[i];
  76080. if (this.imageProcessing) {
  76081. this.imageProcessing.dispose(camera);
  76082. }
  76083. if (this.fxaa) {
  76084. this.fxaa.dispose(camera);
  76085. }
  76086. // These are created in the constructor and should not be disposed on every pipeline change
  76087. if (disposeNonRecreated) {
  76088. if (this.sharpen) {
  76089. this.sharpen.dispose(camera);
  76090. }
  76091. if (this.depthOfField) {
  76092. this.depthOfField.disposeEffects(camera);
  76093. }
  76094. if (this.bloom) {
  76095. this.bloom.disposeEffects(camera);
  76096. }
  76097. if (this.chromaticAberration) {
  76098. this.chromaticAberration.dispose(camera);
  76099. }
  76100. if (this.grain) {
  76101. this.grain.dispose(camera);
  76102. }
  76103. }
  76104. }
  76105. this.imageProcessing = null;
  76106. this.fxaa = null;
  76107. if (disposeNonRecreated) {
  76108. this.sharpen = null;
  76109. this._sharpenEffect = null;
  76110. this.depthOfField = null;
  76111. this.bloom = null;
  76112. this.chromaticAberration = null;
  76113. this._chromaticAberrationEffect = null;
  76114. this.grain = null;
  76115. this._grainEffect = null;
  76116. }
  76117. };
  76118. /**
  76119. * Dispose of the pipeline and stop all post processes
  76120. */
  76121. DefaultRenderingPipeline.prototype.dispose = function () {
  76122. this._disposePostProcesses(true);
  76123. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76124. this._scene.autoClear = true;
  76125. if (this._resizeObserver) {
  76126. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76127. this._resizeObserver = null;
  76128. }
  76129. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76130. _super.prototype.dispose.call(this);
  76131. };
  76132. /**
  76133. * Serialize the rendering pipeline (Used when exporting)
  76134. * @returns the serialized object
  76135. */
  76136. DefaultRenderingPipeline.prototype.serialize = function () {
  76137. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76138. serializationObject.customType = "DefaultRenderingPipeline";
  76139. return serializationObject;
  76140. };
  76141. /**
  76142. * Parse the serialized pipeline
  76143. * @param source Source pipeline.
  76144. * @param scene The scene to load the pipeline to.
  76145. * @param rootUrl The URL of the serialized pipeline.
  76146. * @returns An instantiated pipeline from the serialized object.
  76147. */
  76148. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76149. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76150. };
  76151. __decorate([
  76152. BABYLON.serialize()
  76153. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76154. __decorate([
  76155. BABYLON.serialize()
  76156. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76157. __decorate([
  76158. BABYLON.serialize()
  76159. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76160. __decorate([
  76161. BABYLON.serialize()
  76162. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76163. __decorate([
  76164. BABYLON.serialize()
  76165. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76166. __decorate([
  76167. BABYLON.serialize()
  76168. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76169. __decorate([
  76170. BABYLON.serialize()
  76171. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76172. __decorate([
  76173. BABYLON.serialize()
  76174. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76175. __decorate([
  76176. BABYLON.serialize()
  76177. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76178. __decorate([
  76179. BABYLON.serialize()
  76180. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76181. __decorate([
  76182. BABYLON.serialize()
  76183. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76184. __decorate([
  76185. BABYLON.serialize()
  76186. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76187. __decorate([
  76188. BABYLON.serialize()
  76189. ], DefaultRenderingPipeline.prototype, "samples", null);
  76190. __decorate([
  76191. BABYLON.serialize()
  76192. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76193. __decorate([
  76194. BABYLON.serialize()
  76195. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76196. __decorate([
  76197. BABYLON.serialize()
  76198. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76199. return DefaultRenderingPipeline;
  76200. }(BABYLON.PostProcessRenderPipeline));
  76201. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76202. })(BABYLON || (BABYLON = {}));
  76203. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76204. var BABYLON;
  76205. (function (BABYLON) {
  76206. /**
  76207. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76208. */
  76209. var GeometryBufferRenderer = /** @class */ (function () {
  76210. /**
  76211. * Creates a new G Buffer for the scene
  76212. * @param scene The scene the buffer belongs to
  76213. * @param ratio How big is the buffer related to the main canvas.
  76214. */
  76215. function GeometryBufferRenderer(scene, ratio) {
  76216. if (ratio === void 0) { ratio = 1; }
  76217. this._enablePosition = false;
  76218. this._scene = scene;
  76219. this._ratio = ratio;
  76220. // Render target
  76221. this._createRenderTargets();
  76222. }
  76223. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76224. /**
  76225. * Set the render list (meshes to be rendered) used in the G buffer.
  76226. */
  76227. set: function (meshes) {
  76228. this._multiRenderTarget.renderList = meshes;
  76229. },
  76230. enumerable: true,
  76231. configurable: true
  76232. });
  76233. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76234. /**
  76235. * Gets wether or not G buffer are supported by the running hardware.
  76236. * This requires draw buffer supports
  76237. */
  76238. get: function () {
  76239. return this._multiRenderTarget.isSupported;
  76240. },
  76241. enumerable: true,
  76242. configurable: true
  76243. });
  76244. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76245. /**
  76246. * Gets wether or not position are enabled for the G buffer.
  76247. */
  76248. get: function () {
  76249. return this._enablePosition;
  76250. },
  76251. /**
  76252. * Sets wether or not position are enabled for the G buffer.
  76253. */
  76254. set: function (enable) {
  76255. this._enablePosition = enable;
  76256. this.dispose();
  76257. this._createRenderTargets();
  76258. },
  76259. enumerable: true,
  76260. configurable: true
  76261. });
  76262. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76263. /**
  76264. * Gets the scene associated with the buffer.
  76265. */
  76266. get: function () {
  76267. return this._scene;
  76268. },
  76269. enumerable: true,
  76270. configurable: true
  76271. });
  76272. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76273. /**
  76274. * Gets the ratio used by the buffer during its creation.
  76275. * How big is the buffer related to the main canvas.
  76276. */
  76277. get: function () {
  76278. return this._ratio;
  76279. },
  76280. enumerable: true,
  76281. configurable: true
  76282. });
  76283. /**
  76284. * Checks wether everything is ready to render a submesh to the G buffer.
  76285. * @param subMesh the submesh to check readiness for
  76286. * @param useInstances is the mesh drawn using instance or not
  76287. * @returns true if ready otherwise false
  76288. */
  76289. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76290. var material = subMesh.getMaterial();
  76291. if (material && material.disableDepthWrite) {
  76292. return false;
  76293. }
  76294. var defines = [];
  76295. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76296. var mesh = subMesh.getMesh();
  76297. // Alpha test
  76298. if (material && material.needAlphaTesting()) {
  76299. defines.push("#define ALPHATEST");
  76300. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76301. attribs.push(BABYLON.VertexBuffer.UVKind);
  76302. defines.push("#define UV1");
  76303. }
  76304. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76305. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76306. defines.push("#define UV2");
  76307. }
  76308. }
  76309. // Buffers
  76310. if (this._enablePosition) {
  76311. defines.push("#define POSITION");
  76312. }
  76313. // Bones
  76314. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76315. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76316. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76317. if (mesh.numBoneInfluencers > 4) {
  76318. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76319. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76320. }
  76321. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76322. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  76323. }
  76324. else {
  76325. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76326. }
  76327. // Instances
  76328. if (useInstances) {
  76329. defines.push("#define INSTANCES");
  76330. attribs.push("world0");
  76331. attribs.push("world1");
  76332. attribs.push("world2");
  76333. attribs.push("world3");
  76334. }
  76335. // Get correct effect
  76336. var join = defines.join("\n");
  76337. if (this._cachedDefines !== join) {
  76338. this._cachedDefines = join;
  76339. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  76340. }
  76341. return this._effect.isReady();
  76342. };
  76343. /**
  76344. * Gets the current underlying G Buffer.
  76345. * @returns the buffer
  76346. */
  76347. GeometryBufferRenderer.prototype.getGBuffer = function () {
  76348. return this._multiRenderTarget;
  76349. };
  76350. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  76351. /**
  76352. * Gets the number of samples used to render the buffer (anti aliasing).
  76353. */
  76354. get: function () {
  76355. return this._multiRenderTarget.samples;
  76356. },
  76357. /**
  76358. * Sets the number of samples used to render the buffer (anti aliasing).
  76359. */
  76360. set: function (value) {
  76361. this._multiRenderTarget.samples = value;
  76362. },
  76363. enumerable: true,
  76364. configurable: true
  76365. });
  76366. /**
  76367. * Disposes the renderer and frees up associated resources.
  76368. */
  76369. GeometryBufferRenderer.prototype.dispose = function () {
  76370. this.getGBuffer().dispose();
  76371. };
  76372. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  76373. var _this = this;
  76374. var engine = this._scene.getEngine();
  76375. var count = this._enablePosition ? 3 : 2;
  76376. 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 });
  76377. if (!this.isSupported) {
  76378. return;
  76379. }
  76380. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76381. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76382. this._multiRenderTarget.refreshRate = 1;
  76383. this._multiRenderTarget.renderParticles = false;
  76384. this._multiRenderTarget.renderList = null;
  76385. // set default depth value to 1.0 (far away)
  76386. this._multiRenderTarget.onClearObservable.add(function (engine) {
  76387. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  76388. });
  76389. // Custom render function
  76390. var renderSubMesh = function (subMesh) {
  76391. var mesh = subMesh.getRenderingMesh();
  76392. var scene = _this._scene;
  76393. var engine = scene.getEngine();
  76394. var material = subMesh.getMaterial();
  76395. if (!material) {
  76396. return;
  76397. }
  76398. // Culling
  76399. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  76400. // Managing instances
  76401. var batch = mesh._getInstancesRenderList(subMesh._id);
  76402. if (batch.mustReturn) {
  76403. return;
  76404. }
  76405. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76406. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  76407. engine.enableEffect(_this._effect);
  76408. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  76409. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  76410. _this._effect.setMatrix("view", scene.getViewMatrix());
  76411. // Alpha test
  76412. if (material && material.needAlphaTesting()) {
  76413. var alphaTexture = material.getAlphaTestTexture();
  76414. if (alphaTexture) {
  76415. _this._effect.setTexture("diffuseSampler", alphaTexture);
  76416. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76417. }
  76418. }
  76419. // Bones
  76420. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76421. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76422. }
  76423. // Draw
  76424. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  76425. }
  76426. };
  76427. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76428. var index;
  76429. if (depthOnlySubMeshes.length) {
  76430. engine.setColorWrite(false);
  76431. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76432. renderSubMesh(depthOnlySubMeshes.data[index]);
  76433. }
  76434. engine.setColorWrite(true);
  76435. }
  76436. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76437. renderSubMesh(opaqueSubMeshes.data[index]);
  76438. }
  76439. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76440. renderSubMesh(alphaTestSubMeshes.data[index]);
  76441. }
  76442. };
  76443. };
  76444. return GeometryBufferRenderer;
  76445. }());
  76446. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  76447. })(BABYLON || (BABYLON = {}));
  76448. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  76449. var BABYLON;
  76450. (function (BABYLON) {
  76451. var RefractionPostProcess = /** @class */ (function (_super) {
  76452. __extends(RefractionPostProcess, _super);
  76453. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  76454. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  76455. _this.color = color;
  76456. _this.depth = depth;
  76457. _this.colorLevel = colorLevel;
  76458. _this._ownRefractionTexture = true;
  76459. _this.onActivateObservable.add(function (cam) {
  76460. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  76461. });
  76462. _this.onApplyObservable.add(function (effect) {
  76463. effect.setColor3("baseColor", _this.color);
  76464. effect.setFloat("depth", _this.depth);
  76465. effect.setFloat("colorLevel", _this.colorLevel);
  76466. effect.setTexture("refractionSampler", _this._refTexture);
  76467. });
  76468. return _this;
  76469. }
  76470. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  76471. /**
  76472. * Gets or sets the refraction texture
  76473. * Please note that you are responsible for disposing the texture if you set it manually
  76474. */
  76475. get: function () {
  76476. return this._refTexture;
  76477. },
  76478. set: function (value) {
  76479. if (this._refTexture && this._ownRefractionTexture) {
  76480. this._refTexture.dispose();
  76481. }
  76482. this._refTexture = value;
  76483. this._ownRefractionTexture = false;
  76484. },
  76485. enumerable: true,
  76486. configurable: true
  76487. });
  76488. // Methods
  76489. RefractionPostProcess.prototype.dispose = function (camera) {
  76490. if (this._refTexture && this._ownRefractionTexture) {
  76491. this._refTexture.dispose();
  76492. this._refTexture = null;
  76493. }
  76494. _super.prototype.dispose.call(this, camera);
  76495. };
  76496. return RefractionPostProcess;
  76497. }(BABYLON.PostProcess));
  76498. BABYLON.RefractionPostProcess = RefractionPostProcess;
  76499. })(BABYLON || (BABYLON = {}));
  76500. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  76501. var BABYLON;
  76502. (function (BABYLON) {
  76503. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  76504. __extends(BlackAndWhitePostProcess, _super);
  76505. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  76506. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  76507. _this.degree = 1;
  76508. _this.onApplyObservable.add(function (effect) {
  76509. effect.setFloat("degree", _this.degree);
  76510. });
  76511. return _this;
  76512. }
  76513. return BlackAndWhitePostProcess;
  76514. }(BABYLON.PostProcess));
  76515. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  76516. })(BABYLON || (BABYLON = {}));
  76517. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  76518. var BABYLON;
  76519. (function (BABYLON) {
  76520. /**
  76521. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  76522. * input texture to perform effects such as edge detection or sharpening
  76523. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  76524. */
  76525. var ConvolutionPostProcess = /** @class */ (function (_super) {
  76526. __extends(ConvolutionPostProcess, _super);
  76527. /**
  76528. * Creates a new instance ConvolutionPostProcess
  76529. * @param name The name of the effect.
  76530. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  76531. * @param options The required width/height ratio to downsize to before computing the render pass.
  76532. * @param camera The camera to apply the render pass to.
  76533. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76534. * @param engine The engine which the post process will be applied. (default: current engine)
  76535. * @param reusable If the post process can be reused on the same frame. (default: false)
  76536. * @param textureType Type of textures used when performing the post process. (default: 0)
  76537. */
  76538. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  76539. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76540. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  76541. _this.kernel = kernel;
  76542. _this.onApply = function (effect) {
  76543. effect.setFloat2("screenSize", _this.width, _this.height);
  76544. effect.setArray("kernel", _this.kernel);
  76545. };
  76546. return _this;
  76547. }
  76548. // Statics
  76549. /**
  76550. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76551. */
  76552. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  76553. /**
  76554. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76555. */
  76556. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  76557. /**
  76558. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76559. */
  76560. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  76561. /**
  76562. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76563. */
  76564. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  76565. /**
  76566. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76567. */
  76568. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  76569. /**
  76570. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  76571. */
  76572. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  76573. return ConvolutionPostProcess;
  76574. }(BABYLON.PostProcess));
  76575. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  76576. })(BABYLON || (BABYLON = {}));
  76577. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  76578. var BABYLON;
  76579. (function (BABYLON) {
  76580. var FilterPostProcess = /** @class */ (function (_super) {
  76581. __extends(FilterPostProcess, _super);
  76582. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  76583. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  76584. _this.kernelMatrix = kernelMatrix;
  76585. _this.onApply = function (effect) {
  76586. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  76587. };
  76588. return _this;
  76589. }
  76590. return FilterPostProcess;
  76591. }(BABYLON.PostProcess));
  76592. BABYLON.FilterPostProcess = FilterPostProcess;
  76593. })(BABYLON || (BABYLON = {}));
  76594. //# sourceMappingURL=babylon.filterPostProcess.js.map
  76595. var BABYLON;
  76596. (function (BABYLON) {
  76597. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  76598. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  76599. __extends(VolumetricLightScatteringPostProcess, _super);
  76600. /**
  76601. * @constructor
  76602. * @param {string} name - The post-process name
  76603. * @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)
  76604. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  76605. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  76606. * @param {number} samples - The post-process quality, default 100
  76607. * @param {number} samplingMode - The post-process filtering mode
  76608. * @param {BABYLON.Engine} engine - The babylon engine
  76609. * @param {boolean} reusable - If the post-process is reusable
  76610. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  76611. */
  76612. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  76613. if (samples === void 0) { samples = 100; }
  76614. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  76615. 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;
  76616. _this._screenCoordinates = BABYLON.Vector2.Zero();
  76617. /**
  76618. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  76619. */
  76620. _this.customMeshPosition = BABYLON.Vector3.Zero();
  76621. /**
  76622. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  76623. */
  76624. _this.useCustomMeshPosition = false;
  76625. /**
  76626. * If the post-process should inverse the light scattering direction
  76627. */
  76628. _this.invert = true;
  76629. /**
  76630. * Array containing the excluded meshes not rendered in the internal pass
  76631. */
  76632. _this.excludedMeshes = new Array();
  76633. /**
  76634. * Controls the overall intensity of the post-process
  76635. */
  76636. _this.exposure = 0.3;
  76637. /**
  76638. * Dissipates each sample's contribution in range [0, 1]
  76639. */
  76640. _this.decay = 0.96815;
  76641. /**
  76642. * Controls the overall intensity of each sample
  76643. */
  76644. _this.weight = 0.58767;
  76645. /**
  76646. * Controls the density of each sample
  76647. */
  76648. _this.density = 0.926;
  76649. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  76650. engine = scene.getEngine();
  76651. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  76652. // Configure mesh
  76653. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  76654. // Configure
  76655. _this._createPass(scene, ratio.passRatio || ratio);
  76656. _this.onActivate = function (camera) {
  76657. if (!_this.isSupported) {
  76658. _this.dispose(camera);
  76659. }
  76660. _this.onActivate = null;
  76661. };
  76662. _this.onApplyObservable.add(function (effect) {
  76663. _this._updateMeshScreenCoordinates(scene);
  76664. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  76665. effect.setFloat("exposure", _this.exposure);
  76666. effect.setFloat("decay", _this.decay);
  76667. effect.setFloat("weight", _this.weight);
  76668. effect.setFloat("density", _this.density);
  76669. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  76670. });
  76671. return _this;
  76672. }
  76673. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  76674. get: function () {
  76675. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76676. return false;
  76677. },
  76678. set: function (useDiffuseColor) {
  76679. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  76680. },
  76681. enumerable: true,
  76682. configurable: true
  76683. });
  76684. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  76685. return "VolumetricLightScatteringPostProcess";
  76686. };
  76687. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  76688. var mesh = subMesh.getMesh();
  76689. // Render this.mesh as default
  76690. if (mesh === this.mesh && mesh.material) {
  76691. return mesh.material.isReady(mesh);
  76692. }
  76693. var defines = [];
  76694. var attribs = [BABYLON.VertexBuffer.PositionKind];
  76695. var material = subMesh.getMaterial();
  76696. // Alpha test
  76697. if (material) {
  76698. if (material.needAlphaTesting()) {
  76699. defines.push("#define ALPHATEST");
  76700. }
  76701. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76702. attribs.push(BABYLON.VertexBuffer.UVKind);
  76703. defines.push("#define UV1");
  76704. }
  76705. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76706. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76707. defines.push("#define UV2");
  76708. }
  76709. }
  76710. // Bones
  76711. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76712. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76713. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76714. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  76715. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  76716. }
  76717. else {
  76718. defines.push("#define NUM_BONE_INFLUENCERS 0");
  76719. }
  76720. // Instances
  76721. if (useInstances) {
  76722. defines.push("#define INSTANCES");
  76723. attribs.push("world0");
  76724. attribs.push("world1");
  76725. attribs.push("world2");
  76726. attribs.push("world3");
  76727. }
  76728. // Get correct effect
  76729. var join = defines.join("\n");
  76730. if (this._cachedDefines !== join) {
  76731. this._cachedDefines = join;
  76732. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  76733. }
  76734. return this._volumetricLightScatteringPass.isReady();
  76735. };
  76736. /**
  76737. * Sets the new light position for light scattering effect
  76738. * @param {BABYLON.Vector3} The new custom light position
  76739. */
  76740. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  76741. this.customMeshPosition = position;
  76742. };
  76743. /**
  76744. * Returns the light position for light scattering effect
  76745. * @return {BABYLON.Vector3} The custom light position
  76746. */
  76747. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  76748. return this.customMeshPosition;
  76749. };
  76750. /**
  76751. * Disposes the internal assets and detaches the post-process from the camera
  76752. */
  76753. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  76754. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  76755. if (rttIndex !== -1) {
  76756. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  76757. }
  76758. this._volumetricLightScatteringRTT.dispose();
  76759. _super.prototype.dispose.call(this, camera);
  76760. };
  76761. /**
  76762. * Returns the render target texture used by the post-process
  76763. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  76764. */
  76765. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  76766. return this._volumetricLightScatteringRTT;
  76767. };
  76768. // Private methods
  76769. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  76770. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  76771. return true;
  76772. }
  76773. return false;
  76774. };
  76775. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  76776. var _this = this;
  76777. var engine = scene.getEngine();
  76778. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  76779. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76780. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76781. this._volumetricLightScatteringRTT.renderList = null;
  76782. this._volumetricLightScatteringRTT.renderParticles = false;
  76783. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  76784. var camera = this.getCamera();
  76785. if (camera) {
  76786. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76787. }
  76788. else {
  76789. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  76790. }
  76791. // Custom render function for submeshes
  76792. var renderSubMesh = function (subMesh) {
  76793. var mesh = subMesh.getRenderingMesh();
  76794. if (_this._meshExcluded(mesh)) {
  76795. return;
  76796. }
  76797. var material = subMesh.getMaterial();
  76798. if (!material) {
  76799. return;
  76800. }
  76801. var scene = mesh.getScene();
  76802. var engine = scene.getEngine();
  76803. // Culling
  76804. engine.setState(material.backFaceCulling);
  76805. // Managing instances
  76806. var batch = mesh._getInstancesRenderList(subMesh._id);
  76807. if (batch.mustReturn) {
  76808. return;
  76809. }
  76810. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  76811. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  76812. var effect = _this._volumetricLightScatteringPass;
  76813. if (mesh === _this.mesh) {
  76814. if (subMesh.effect) {
  76815. effect = subMesh.effect;
  76816. }
  76817. else {
  76818. effect = material.getEffect();
  76819. }
  76820. }
  76821. engine.enableEffect(effect);
  76822. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  76823. if (mesh === _this.mesh) {
  76824. material.bind(mesh.getWorldMatrix(), mesh);
  76825. }
  76826. else {
  76827. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  76828. // Alpha test
  76829. if (material && material.needAlphaTesting()) {
  76830. var alphaTexture = material.getAlphaTestTexture();
  76831. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  76832. if (alphaTexture) {
  76833. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  76834. }
  76835. }
  76836. // Bones
  76837. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  76838. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  76839. }
  76840. }
  76841. // Draw
  76842. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  76843. }
  76844. };
  76845. // Render target texture callbacks
  76846. var savedSceneClearColor;
  76847. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  76848. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  76849. savedSceneClearColor = scene.clearColor;
  76850. scene.clearColor = sceneClearColor;
  76851. });
  76852. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  76853. scene.clearColor = savedSceneClearColor;
  76854. });
  76855. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  76856. var engine = scene.getEngine();
  76857. var index;
  76858. if (depthOnlySubMeshes.length) {
  76859. engine.setColorWrite(false);
  76860. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  76861. renderSubMesh(depthOnlySubMeshes.data[index]);
  76862. }
  76863. engine.setColorWrite(true);
  76864. }
  76865. for (index = 0; index < opaqueSubMeshes.length; index++) {
  76866. renderSubMesh(opaqueSubMeshes.data[index]);
  76867. }
  76868. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  76869. renderSubMesh(alphaTestSubMeshes.data[index]);
  76870. }
  76871. if (transparentSubMeshes.length) {
  76872. // Sort sub meshes
  76873. for (index = 0; index < transparentSubMeshes.length; index++) {
  76874. var submesh = transparentSubMeshes.data[index];
  76875. var boundingInfo = submesh.getBoundingInfo();
  76876. if (boundingInfo && scene.activeCamera) {
  76877. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  76878. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  76879. }
  76880. }
  76881. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  76882. sortedArray.sort(function (a, b) {
  76883. // Alpha index first
  76884. if (a._alphaIndex > b._alphaIndex) {
  76885. return 1;
  76886. }
  76887. if (a._alphaIndex < b._alphaIndex) {
  76888. return -1;
  76889. }
  76890. // Then distance to camera
  76891. if (a._distanceToCamera < b._distanceToCamera) {
  76892. return 1;
  76893. }
  76894. if (a._distanceToCamera > b._distanceToCamera) {
  76895. return -1;
  76896. }
  76897. return 0;
  76898. });
  76899. // Render sub meshes
  76900. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  76901. for (index = 0; index < sortedArray.length; index++) {
  76902. renderSubMesh(sortedArray[index]);
  76903. }
  76904. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  76905. }
  76906. };
  76907. };
  76908. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  76909. var transform = scene.getTransformMatrix();
  76910. var meshPosition;
  76911. if (this.useCustomMeshPosition) {
  76912. meshPosition = this.customMeshPosition;
  76913. }
  76914. else if (this.attachedNode) {
  76915. meshPosition = this.attachedNode.position;
  76916. }
  76917. else {
  76918. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  76919. }
  76920. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  76921. this._screenCoordinates.x = pos.x / this._viewPort.width;
  76922. this._screenCoordinates.y = pos.y / this._viewPort.height;
  76923. if (this.invert)
  76924. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  76925. };
  76926. // Static methods
  76927. /**
  76928. * Creates a default mesh for the Volumeric Light Scattering post-process
  76929. * @param {string} The mesh name
  76930. * @param {BABYLON.Scene} The scene where to create the mesh
  76931. * @return {BABYLON.Mesh} the default mesh
  76932. */
  76933. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  76934. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  76935. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  76936. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  76937. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  76938. mesh.material = material;
  76939. return mesh;
  76940. };
  76941. __decorate([
  76942. BABYLON.serializeAsVector3()
  76943. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  76944. __decorate([
  76945. BABYLON.serialize()
  76946. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  76947. __decorate([
  76948. BABYLON.serialize()
  76949. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  76950. __decorate([
  76951. BABYLON.serializeAsMeshReference()
  76952. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  76953. __decorate([
  76954. BABYLON.serialize()
  76955. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  76956. __decorate([
  76957. BABYLON.serialize()
  76958. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  76959. __decorate([
  76960. BABYLON.serialize()
  76961. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  76962. __decorate([
  76963. BABYLON.serialize()
  76964. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  76965. __decorate([
  76966. BABYLON.serialize()
  76967. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  76968. return VolumetricLightScatteringPostProcess;
  76969. }(BABYLON.PostProcess));
  76970. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  76971. })(BABYLON || (BABYLON = {}));
  76972. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  76973. //
  76974. // This post-process allows the modification of rendered colors by using
  76975. // a 'look-up table' (LUT). This effect is also called Color Grading.
  76976. //
  76977. // The object needs to be provided an url to a texture containing the color
  76978. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  76979. // Use an image editing software to tweak the LUT to match your needs.
  76980. //
  76981. // For an example of a color LUT, see here:
  76982. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  76983. // For explanations on color grading, see here:
  76984. // http://udn.epicgames.com/Three/ColorGrading.html
  76985. //
  76986. var BABYLON;
  76987. (function (BABYLON) {
  76988. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  76989. __extends(ColorCorrectionPostProcess, _super);
  76990. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  76991. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  76992. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  76993. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  76994. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76995. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  76996. _this.onApply = function (effect) {
  76997. effect.setTexture("colorTable", _this._colorTableTexture);
  76998. };
  76999. return _this;
  77000. }
  77001. return ColorCorrectionPostProcess;
  77002. }(BABYLON.PostProcess));
  77003. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  77004. })(BABYLON || (BABYLON = {}));
  77005. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  77006. var BABYLON;
  77007. (function (BABYLON) {
  77008. /** Defines operator used for tonemapping */
  77009. var TonemappingOperator;
  77010. (function (TonemappingOperator) {
  77011. /** Hable */
  77012. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  77013. /** Reinhard */
  77014. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  77015. /** HejiDawson */
  77016. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  77017. /** Photographic */
  77018. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  77019. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  77020. ;
  77021. /**
  77022. * Defines a post process to apply tone mapping
  77023. */
  77024. var TonemapPostProcess = /** @class */ (function (_super) {
  77025. __extends(TonemapPostProcess, _super);
  77026. /**
  77027. * Creates a new TonemapPostProcess
  77028. * @param name defines the name of the postprocess
  77029. * @param _operator defines the operator to use
  77030. * @param exposureAdjustment defines the required exposure adjustement
  77031. * @param camera defines the camera to use (can be null)
  77032. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  77033. * @param engine defines the hosting engine (can be ignore if camera is set)
  77034. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  77035. */
  77036. function TonemapPostProcess(name, _operator,
  77037. /** Defines the required exposure adjustement */
  77038. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  77039. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  77040. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77041. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  77042. _this._operator = _operator;
  77043. _this.exposureAdjustment = exposureAdjustment;
  77044. var defines = "#define ";
  77045. if (_this._operator === TonemappingOperator.Hable)
  77046. defines += "HABLE_TONEMAPPING";
  77047. else if (_this._operator === TonemappingOperator.Reinhard)
  77048. defines += "REINHARD_TONEMAPPING";
  77049. else if (_this._operator === TonemappingOperator.HejiDawson)
  77050. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  77051. else if (_this._operator === TonemappingOperator.Photographic)
  77052. defines += "PHOTOGRAPHIC_TONEMAPPING";
  77053. //sadly a second call to create the effect.
  77054. _this.updateEffect(defines);
  77055. _this.onApply = function (effect) {
  77056. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  77057. };
  77058. return _this;
  77059. }
  77060. return TonemapPostProcess;
  77061. }(BABYLON.PostProcess));
  77062. BABYLON.TonemapPostProcess = TonemapPostProcess;
  77063. })(BABYLON || (BABYLON = {}));
  77064. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  77065. var BABYLON;
  77066. (function (BABYLON) {
  77067. var DisplayPassPostProcess = /** @class */ (function (_super) {
  77068. __extends(DisplayPassPostProcess, _super);
  77069. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  77070. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  77071. }
  77072. return DisplayPassPostProcess;
  77073. }(BABYLON.PostProcess));
  77074. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  77075. })(BABYLON || (BABYLON = {}));
  77076. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  77077. var BABYLON;
  77078. (function (BABYLON) {
  77079. var HighlightsPostProcess = /** @class */ (function (_super) {
  77080. __extends(HighlightsPostProcess, _super);
  77081. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  77082. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77083. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  77084. }
  77085. return HighlightsPostProcess;
  77086. }(BABYLON.PostProcess));
  77087. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  77088. })(BABYLON || (BABYLON = {}));
  77089. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  77090. var BABYLON;
  77091. (function (BABYLON) {
  77092. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  77093. __extends(ImageProcessingPostProcess, _super);
  77094. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  77095. if (camera === void 0) { camera = null; }
  77096. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  77097. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  77098. _this._fromLinearSpace = true;
  77099. /**
  77100. * Defines cache preventing GC.
  77101. */
  77102. _this._defines = {
  77103. IMAGEPROCESSING: false,
  77104. VIGNETTE: false,
  77105. VIGNETTEBLENDMODEMULTIPLY: false,
  77106. VIGNETTEBLENDMODEOPAQUE: false,
  77107. TONEMAPPING: false,
  77108. CONTRAST: false,
  77109. COLORCURVES: false,
  77110. COLORGRADING: false,
  77111. COLORGRADING3D: false,
  77112. FROMLINEARSPACE: false,
  77113. SAMPLER3DGREENDEPTH: false,
  77114. SAMPLER3DBGRMAP: false,
  77115. IMAGEPROCESSINGPOSTPROCESS: false,
  77116. EXPOSURE: false,
  77117. };
  77118. // Setup the configuration as forced by the constructor. This would then not force the
  77119. // scene materials output in linear space and let untouched the default forward pass.
  77120. if (imageProcessingConfiguration) {
  77121. imageProcessingConfiguration.applyByPostProcess = true;
  77122. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  77123. // This will cause the shader to be compiled
  77124. _this.fromLinearSpace = false;
  77125. }
  77126. // Setup the default processing configuration to the scene.
  77127. else {
  77128. _this._attachImageProcessingConfiguration(null, true);
  77129. _this.imageProcessingConfiguration.applyByPostProcess = true;
  77130. }
  77131. _this.onApply = function (effect) {
  77132. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  77133. };
  77134. return _this;
  77135. }
  77136. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  77137. /**
  77138. * Gets the image processing configuration used either in this material.
  77139. */
  77140. get: function () {
  77141. return this._imageProcessingConfiguration;
  77142. },
  77143. /**
  77144. * Sets the Default image processing configuration used either in the this material.
  77145. *
  77146. * If sets to null, the scene one is in use.
  77147. */
  77148. set: function (value) {
  77149. this._attachImageProcessingConfiguration(value);
  77150. },
  77151. enumerable: true,
  77152. configurable: true
  77153. });
  77154. /**
  77155. * Attaches a new image processing configuration to the PBR Material.
  77156. * @param configuration
  77157. */
  77158. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  77159. var _this = this;
  77160. if (doNotBuild === void 0) { doNotBuild = false; }
  77161. if (configuration === this._imageProcessingConfiguration) {
  77162. return;
  77163. }
  77164. // Detaches observer.
  77165. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77166. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77167. }
  77168. // Pick the scene configuration if needed.
  77169. if (!configuration) {
  77170. var scene = null;
  77171. var engine = this.getEngine();
  77172. var camera = this.getCamera();
  77173. if (camera) {
  77174. scene = camera.getScene();
  77175. }
  77176. else if (engine && engine.scenes) {
  77177. var scenes = engine.scenes;
  77178. scene = scenes[scenes.length - 1];
  77179. }
  77180. else {
  77181. scene = BABYLON.Engine.LastCreatedScene;
  77182. }
  77183. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  77184. }
  77185. else {
  77186. this._imageProcessingConfiguration = configuration;
  77187. }
  77188. // Attaches observer.
  77189. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  77190. _this._updateParameters();
  77191. });
  77192. // Ensure the effect will be rebuilt.
  77193. if (!doNotBuild) {
  77194. this._updateParameters();
  77195. }
  77196. };
  77197. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  77198. /**
  77199. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77200. */
  77201. get: function () {
  77202. return this.imageProcessingConfiguration.colorCurves;
  77203. },
  77204. /**
  77205. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  77206. */
  77207. set: function (value) {
  77208. this.imageProcessingConfiguration.colorCurves = value;
  77209. },
  77210. enumerable: true,
  77211. configurable: true
  77212. });
  77213. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  77214. /**
  77215. * Gets wether the color curves effect is enabled.
  77216. */
  77217. get: function () {
  77218. return this.imageProcessingConfiguration.colorCurvesEnabled;
  77219. },
  77220. /**
  77221. * Sets wether the color curves effect is enabled.
  77222. */
  77223. set: function (value) {
  77224. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  77225. },
  77226. enumerable: true,
  77227. configurable: true
  77228. });
  77229. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  77230. /**
  77231. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77232. */
  77233. get: function () {
  77234. return this.imageProcessingConfiguration.colorGradingTexture;
  77235. },
  77236. /**
  77237. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  77238. */
  77239. set: function (value) {
  77240. this.imageProcessingConfiguration.colorGradingTexture = value;
  77241. },
  77242. enumerable: true,
  77243. configurable: true
  77244. });
  77245. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  77246. /**
  77247. * Gets wether the color grading effect is enabled.
  77248. */
  77249. get: function () {
  77250. return this.imageProcessingConfiguration.colorGradingEnabled;
  77251. },
  77252. /**
  77253. * Gets wether the color grading effect is enabled.
  77254. */
  77255. set: function (value) {
  77256. this.imageProcessingConfiguration.colorGradingEnabled = value;
  77257. },
  77258. enumerable: true,
  77259. configurable: true
  77260. });
  77261. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  77262. /**
  77263. * Gets exposure used in the effect.
  77264. */
  77265. get: function () {
  77266. return this.imageProcessingConfiguration.exposure;
  77267. },
  77268. /**
  77269. * Sets exposure used in the effect.
  77270. */
  77271. set: function (value) {
  77272. this.imageProcessingConfiguration.exposure = value;
  77273. },
  77274. enumerable: true,
  77275. configurable: true
  77276. });
  77277. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  77278. /**
  77279. * Gets wether tonemapping is enabled or not.
  77280. */
  77281. get: function () {
  77282. return this._imageProcessingConfiguration.toneMappingEnabled;
  77283. },
  77284. /**
  77285. * Sets wether tonemapping is enabled or not
  77286. */
  77287. set: function (value) {
  77288. this._imageProcessingConfiguration.toneMappingEnabled = value;
  77289. },
  77290. enumerable: true,
  77291. configurable: true
  77292. });
  77293. ;
  77294. ;
  77295. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  77296. /**
  77297. * Gets contrast used in the effect.
  77298. */
  77299. get: function () {
  77300. return this.imageProcessingConfiguration.contrast;
  77301. },
  77302. /**
  77303. * Sets contrast used in the effect.
  77304. */
  77305. set: function (value) {
  77306. this.imageProcessingConfiguration.contrast = value;
  77307. },
  77308. enumerable: true,
  77309. configurable: true
  77310. });
  77311. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  77312. /**
  77313. * Gets Vignette stretch size.
  77314. */
  77315. get: function () {
  77316. return this.imageProcessingConfiguration.vignetteStretch;
  77317. },
  77318. /**
  77319. * Sets Vignette stretch size.
  77320. */
  77321. set: function (value) {
  77322. this.imageProcessingConfiguration.vignetteStretch = value;
  77323. },
  77324. enumerable: true,
  77325. configurable: true
  77326. });
  77327. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  77328. /**
  77329. * Gets Vignette centre X Offset.
  77330. */
  77331. get: function () {
  77332. return this.imageProcessingConfiguration.vignetteCentreX;
  77333. },
  77334. /**
  77335. * Sets Vignette centre X Offset.
  77336. */
  77337. set: function (value) {
  77338. this.imageProcessingConfiguration.vignetteCentreX = value;
  77339. },
  77340. enumerable: true,
  77341. configurable: true
  77342. });
  77343. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  77344. /**
  77345. * Gets Vignette centre Y Offset.
  77346. */
  77347. get: function () {
  77348. return this.imageProcessingConfiguration.vignetteCentreY;
  77349. },
  77350. /**
  77351. * Sets Vignette centre Y Offset.
  77352. */
  77353. set: function (value) {
  77354. this.imageProcessingConfiguration.vignetteCentreY = value;
  77355. },
  77356. enumerable: true,
  77357. configurable: true
  77358. });
  77359. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  77360. /**
  77361. * Gets Vignette weight or intensity of the vignette effect.
  77362. */
  77363. get: function () {
  77364. return this.imageProcessingConfiguration.vignetteWeight;
  77365. },
  77366. /**
  77367. * Sets Vignette weight or intensity of the vignette effect.
  77368. */
  77369. set: function (value) {
  77370. this.imageProcessingConfiguration.vignetteWeight = value;
  77371. },
  77372. enumerable: true,
  77373. configurable: true
  77374. });
  77375. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  77376. /**
  77377. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77378. * if vignetteEnabled is set to true.
  77379. */
  77380. get: function () {
  77381. return this.imageProcessingConfiguration.vignetteColor;
  77382. },
  77383. /**
  77384. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77385. * if vignetteEnabled is set to true.
  77386. */
  77387. set: function (value) {
  77388. this.imageProcessingConfiguration.vignetteColor = value;
  77389. },
  77390. enumerable: true,
  77391. configurable: true
  77392. });
  77393. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  77394. /**
  77395. * Gets Camera field of view used by the Vignette effect.
  77396. */
  77397. get: function () {
  77398. return this.imageProcessingConfiguration.vignetteCameraFov;
  77399. },
  77400. /**
  77401. * Sets Camera field of view used by the Vignette effect.
  77402. */
  77403. set: function (value) {
  77404. this.imageProcessingConfiguration.vignetteCameraFov = value;
  77405. },
  77406. enumerable: true,
  77407. configurable: true
  77408. });
  77409. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  77410. /**
  77411. * Gets the vignette blend mode allowing different kind of effect.
  77412. */
  77413. get: function () {
  77414. return this.imageProcessingConfiguration.vignetteBlendMode;
  77415. },
  77416. /**
  77417. * Sets the vignette blend mode allowing different kind of effect.
  77418. */
  77419. set: function (value) {
  77420. this.imageProcessingConfiguration.vignetteBlendMode = value;
  77421. },
  77422. enumerable: true,
  77423. configurable: true
  77424. });
  77425. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  77426. /**
  77427. * Gets wether the vignette effect is enabled.
  77428. */
  77429. get: function () {
  77430. return this.imageProcessingConfiguration.vignetteEnabled;
  77431. },
  77432. /**
  77433. * Sets wether the vignette effect is enabled.
  77434. */
  77435. set: function (value) {
  77436. this.imageProcessingConfiguration.vignetteEnabled = value;
  77437. },
  77438. enumerable: true,
  77439. configurable: true
  77440. });
  77441. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  77442. /**
  77443. * Gets wether the input of the processing is in Gamma or Linear Space.
  77444. */
  77445. get: function () {
  77446. return this._fromLinearSpace;
  77447. },
  77448. /**
  77449. * Sets wether the input of the processing is in Gamma or Linear Space.
  77450. */
  77451. set: function (value) {
  77452. if (this._fromLinearSpace === value) {
  77453. return;
  77454. }
  77455. this._fromLinearSpace = value;
  77456. this._updateParameters();
  77457. },
  77458. enumerable: true,
  77459. configurable: true
  77460. });
  77461. ImageProcessingPostProcess.prototype.getClassName = function () {
  77462. return "ImageProcessingPostProcess";
  77463. };
  77464. ImageProcessingPostProcess.prototype._updateParameters = function () {
  77465. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  77466. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  77467. var defines = "";
  77468. for (var define in this._defines) {
  77469. if (this._defines[define]) {
  77470. defines += "#define " + define + ";\r\n";
  77471. }
  77472. }
  77473. var samplers = ["textureSampler"];
  77474. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  77475. var uniforms = ["scale"];
  77476. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  77477. this.updateEffect(defines, uniforms, samplers);
  77478. };
  77479. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  77480. _super.prototype.dispose.call(this, camera);
  77481. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  77482. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  77483. }
  77484. this.imageProcessingConfiguration.applyByPostProcess = false;
  77485. };
  77486. __decorate([
  77487. BABYLON.serialize()
  77488. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  77489. return ImageProcessingPostProcess;
  77490. }(BABYLON.PostProcess));
  77491. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  77492. })(BABYLON || (BABYLON = {}));
  77493. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  77494. var BABYLON;
  77495. (function (BABYLON) {
  77496. /**
  77497. * Class used to store bone information
  77498. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  77499. */
  77500. var Bone = /** @class */ (function (_super) {
  77501. __extends(Bone, _super);
  77502. /**
  77503. * Create a new bone
  77504. * @param name defines the bone name
  77505. * @param skeleton defines the parent skeleton
  77506. * @param parentBone defines the parent (can be null if the bone is the root)
  77507. * @param localMatrix defines the local matrix
  77508. * @param restPose defines the rest pose matrix
  77509. * @param baseMatrix defines the base matrix
  77510. * @param index defines index of the bone in the hiearchy
  77511. */
  77512. function Bone(
  77513. /**
  77514. * defines the bone name
  77515. */
  77516. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  77517. if (parentBone === void 0) { parentBone = null; }
  77518. if (localMatrix === void 0) { localMatrix = null; }
  77519. if (restPose === void 0) { restPose = null; }
  77520. if (baseMatrix === void 0) { baseMatrix = null; }
  77521. if (index === void 0) { index = null; }
  77522. var _this = _super.call(this, name, skeleton.getScene()) || this;
  77523. _this.name = name;
  77524. /**
  77525. * Gets the list of child bones
  77526. */
  77527. _this.children = new Array();
  77528. /** Gets the animations associated with this bone */
  77529. _this.animations = new Array();
  77530. /**
  77531. * @hidden Internal only
  77532. * Set this value to map this bone to a different index in the transform matrices
  77533. * Set this value to -1 to exclude the bone from the transform matrices
  77534. */
  77535. _this._index = null;
  77536. _this._absoluteTransform = new BABYLON.Matrix();
  77537. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  77538. _this._scalingDeterminant = 1;
  77539. _this._worldTransform = new BABYLON.Matrix();
  77540. _this._needToDecompose = true;
  77541. _this._needToCompose = false;
  77542. _this._skeleton = skeleton;
  77543. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  77544. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  77545. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  77546. _this._index = index;
  77547. skeleton.bones.push(_this);
  77548. _this.setParent(parentBone, false);
  77549. if (baseMatrix || localMatrix) {
  77550. _this._updateDifferenceMatrix();
  77551. }
  77552. return _this;
  77553. }
  77554. Object.defineProperty(Bone.prototype, "_matrix", {
  77555. /** @hidden */
  77556. get: function () {
  77557. this._compose();
  77558. return this._localMatrix;
  77559. },
  77560. /** @hidden */
  77561. set: function (value) {
  77562. this._localMatrix.copyFrom(value);
  77563. this._needToDecompose = true;
  77564. },
  77565. enumerable: true,
  77566. configurable: true
  77567. });
  77568. // Members
  77569. /**
  77570. * Gets the parent skeleton
  77571. * @returns a skeleton
  77572. */
  77573. Bone.prototype.getSkeleton = function () {
  77574. return this._skeleton;
  77575. };
  77576. /**
  77577. * Gets parent bone
  77578. * @returns a bone or null if the bone is the root of the bone hierarchy
  77579. */
  77580. Bone.prototype.getParent = function () {
  77581. return this._parent;
  77582. };
  77583. /**
  77584. * Sets the parent bone
  77585. * @param parent defines the parent (can be null if the bone is the root)
  77586. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77587. */
  77588. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  77589. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77590. if (this._parent === parent) {
  77591. return;
  77592. }
  77593. if (this._parent) {
  77594. var index = this._parent.children.indexOf(this);
  77595. if (index !== -1) {
  77596. this._parent.children.splice(index, 1);
  77597. }
  77598. }
  77599. this._parent = parent;
  77600. if (this._parent) {
  77601. this._parent.children.push(this);
  77602. }
  77603. if (updateDifferenceMatrix) {
  77604. this._updateDifferenceMatrix();
  77605. }
  77606. this.markAsDirty();
  77607. };
  77608. /**
  77609. * Gets the local matrix
  77610. * @returns a matrix
  77611. */
  77612. Bone.prototype.getLocalMatrix = function () {
  77613. this._compose();
  77614. return this._localMatrix;
  77615. };
  77616. /**
  77617. * Gets the base matrix (initial matrix which remains unchanged)
  77618. * @returns a matrix
  77619. */
  77620. Bone.prototype.getBaseMatrix = function () {
  77621. return this._baseMatrix;
  77622. };
  77623. /**
  77624. * Gets the rest pose matrix
  77625. * @returns a matrix
  77626. */
  77627. Bone.prototype.getRestPose = function () {
  77628. return this._restPose;
  77629. };
  77630. /**
  77631. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  77632. */
  77633. Bone.prototype.getWorldMatrix = function () {
  77634. return this._worldTransform;
  77635. };
  77636. /**
  77637. * Sets the local matrix to rest pose matrix
  77638. */
  77639. Bone.prototype.returnToRest = function () {
  77640. this.updateMatrix(this._restPose.clone());
  77641. };
  77642. /**
  77643. * Gets the inverse of the absolute transform matrix.
  77644. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  77645. * @returns a matrix
  77646. */
  77647. Bone.prototype.getInvertedAbsoluteTransform = function () {
  77648. return this._invertedAbsoluteTransform;
  77649. };
  77650. /**
  77651. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  77652. * @returns a matrix
  77653. */
  77654. Bone.prototype.getAbsoluteTransform = function () {
  77655. return this._absoluteTransform;
  77656. };
  77657. Object.defineProperty(Bone.prototype, "position", {
  77658. // Properties (matches AbstractMesh properties)
  77659. /** Gets or sets current position (in local space) */
  77660. get: function () {
  77661. this._decompose();
  77662. return this._localPosition;
  77663. },
  77664. set: function (newPosition) {
  77665. this._decompose();
  77666. this._localPosition.copyFrom(newPosition);
  77667. this._markAsDirtyAndCompose();
  77668. },
  77669. enumerable: true,
  77670. configurable: true
  77671. });
  77672. Object.defineProperty(Bone.prototype, "rotation", {
  77673. /** Gets or sets current rotation (in local space) */
  77674. get: function () {
  77675. return this.getRotation();
  77676. },
  77677. set: function (newRotation) {
  77678. this.setRotation(newRotation);
  77679. },
  77680. enumerable: true,
  77681. configurable: true
  77682. });
  77683. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  77684. /** Gets or sets current rotation quaternion (in local space) */
  77685. get: function () {
  77686. this._decompose();
  77687. return this._localRotation;
  77688. },
  77689. set: function (newRotation) {
  77690. this.setRotationQuaternion(newRotation);
  77691. },
  77692. enumerable: true,
  77693. configurable: true
  77694. });
  77695. Object.defineProperty(Bone.prototype, "scaling", {
  77696. /** Gets or sets current scaling (in local space) */
  77697. get: function () {
  77698. return this.getScale();
  77699. },
  77700. set: function (newScaling) {
  77701. this.setScale(newScaling);
  77702. },
  77703. enumerable: true,
  77704. configurable: true
  77705. });
  77706. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  77707. /**
  77708. * Gets the animation properties override
  77709. */
  77710. get: function () {
  77711. return this._skeleton.animationPropertiesOverride;
  77712. },
  77713. enumerable: true,
  77714. configurable: true
  77715. });
  77716. // Methods
  77717. Bone.prototype._decompose = function () {
  77718. if (!this._needToDecompose) {
  77719. return;
  77720. }
  77721. this._needToDecompose = false;
  77722. if (!this._localScaling) {
  77723. this._localScaling = BABYLON.Vector3.Zero();
  77724. this._localRotation = BABYLON.Quaternion.Zero();
  77725. this._localPosition = BABYLON.Vector3.Zero();
  77726. }
  77727. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  77728. };
  77729. Bone.prototype._compose = function () {
  77730. if (!this._needToCompose) {
  77731. return;
  77732. }
  77733. this._needToCompose = false;
  77734. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  77735. };
  77736. /**
  77737. * Update the base and local matrices
  77738. * @param matrix defines the new base or local matrix
  77739. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  77740. * @param updateLocalMatrix defines if the local matrix should be updated
  77741. */
  77742. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  77743. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  77744. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  77745. this._baseMatrix.copyFrom(matrix);
  77746. if (updateDifferenceMatrix) {
  77747. this._updateDifferenceMatrix();
  77748. }
  77749. if (updateLocalMatrix) {
  77750. this._localMatrix.copyFrom(matrix);
  77751. this._markAsDirtyAndDecompose();
  77752. }
  77753. else {
  77754. this.markAsDirty();
  77755. }
  77756. };
  77757. /** @hidden */
  77758. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  77759. if (updateChildren === void 0) { updateChildren = true; }
  77760. if (!rootMatrix) {
  77761. rootMatrix = this._baseMatrix;
  77762. }
  77763. if (this._parent) {
  77764. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  77765. }
  77766. else {
  77767. this._absoluteTransform.copyFrom(rootMatrix);
  77768. }
  77769. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  77770. if (updateChildren) {
  77771. for (var index = 0; index < this.children.length; index++) {
  77772. this.children[index]._updateDifferenceMatrix();
  77773. }
  77774. }
  77775. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  77776. };
  77777. /**
  77778. * Flag the bone as dirty (Forcing it to update everything)
  77779. */
  77780. Bone.prototype.markAsDirty = function () {
  77781. this._currentRenderId++;
  77782. this._childRenderId++;
  77783. this._skeleton._markAsDirty();
  77784. };
  77785. Bone.prototype._markAsDirtyAndCompose = function () {
  77786. this.markAsDirty();
  77787. this._needToCompose = true;
  77788. };
  77789. Bone.prototype._markAsDirtyAndDecompose = function () {
  77790. this.markAsDirty();
  77791. this._needToDecompose = true;
  77792. };
  77793. /**
  77794. * Copy an animation range from another bone
  77795. * @param source defines the source bone
  77796. * @param rangeName defines the range name to copy
  77797. * @param frameOffset defines the frame offset
  77798. * @param rescaleAsRequired defines if rescaling must be applied if required
  77799. * @param skelDimensionsRatio defines the scaling ratio
  77800. * @returns true if operation was successful
  77801. */
  77802. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  77803. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  77804. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  77805. // all animation may be coming from a library skeleton, so may need to create animation
  77806. if (this.animations.length === 0) {
  77807. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  77808. this.animations[0].setKeys([]);
  77809. }
  77810. // get animation info / verify there is such a range from the source bone
  77811. var sourceRange = source.animations[0].getRange(rangeName);
  77812. if (!sourceRange) {
  77813. return false;
  77814. }
  77815. var from = sourceRange.from;
  77816. var to = sourceRange.to;
  77817. var sourceKeys = source.animations[0].getKeys();
  77818. // rescaling prep
  77819. var sourceBoneLength = source.length;
  77820. var sourceParent = source.getParent();
  77821. var parent = this.getParent();
  77822. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  77823. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  77824. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  77825. var destKeys = this.animations[0].getKeys();
  77826. // loop vars declaration
  77827. var orig;
  77828. var origTranslation;
  77829. var mat;
  77830. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  77831. orig = sourceKeys[key];
  77832. if (orig.frame >= from && orig.frame <= to) {
  77833. if (rescaleAsRequired) {
  77834. mat = orig.value.clone();
  77835. // scale based on parent ratio, when bone has parent
  77836. if (parentScalingReqd) {
  77837. origTranslation = mat.getTranslation();
  77838. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  77839. // scale based on skeleton dimension ratio when root bone, and value is passed
  77840. }
  77841. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  77842. origTranslation = mat.getTranslation();
  77843. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  77844. // use original when root bone, and no data for skelDimensionsRatio
  77845. }
  77846. else {
  77847. mat = orig.value;
  77848. }
  77849. }
  77850. else {
  77851. mat = orig.value;
  77852. }
  77853. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  77854. }
  77855. }
  77856. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  77857. return true;
  77858. };
  77859. /**
  77860. * Translate the bone in local or world space
  77861. * @param vec The amount to translate the bone
  77862. * @param space The space that the translation is in
  77863. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77864. */
  77865. Bone.prototype.translate = function (vec, space, mesh) {
  77866. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77867. var lm = this.getLocalMatrix();
  77868. if (space == BABYLON.Space.LOCAL) {
  77869. lm.m[12] += vec.x;
  77870. lm.m[13] += vec.y;
  77871. lm.m[14] += vec.z;
  77872. }
  77873. else {
  77874. var wm = null;
  77875. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77876. if (mesh) {
  77877. wm = mesh.getWorldMatrix();
  77878. }
  77879. this._skeleton.computeAbsoluteTransforms();
  77880. var tmat = Bone._tmpMats[0];
  77881. var tvec = Bone._tmpVecs[0];
  77882. if (this._parent) {
  77883. if (mesh && wm) {
  77884. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77885. tmat.multiplyToRef(wm, tmat);
  77886. }
  77887. else {
  77888. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77889. }
  77890. }
  77891. tmat.m[12] = 0;
  77892. tmat.m[13] = 0;
  77893. tmat.m[14] = 0;
  77894. tmat.invert();
  77895. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  77896. lm.m[12] += tvec.x;
  77897. lm.m[13] += tvec.y;
  77898. lm.m[14] += tvec.z;
  77899. }
  77900. this._markAsDirtyAndDecompose();
  77901. };
  77902. /**
  77903. * Set the postion of the bone in local or world space
  77904. * @param position The position to set the bone
  77905. * @param space The space that the position is in
  77906. * @param mesh The mesh that this bone is attached to. This is only used in world space
  77907. */
  77908. Bone.prototype.setPosition = function (position, space, mesh) {
  77909. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  77910. var lm = this.getLocalMatrix();
  77911. if (space == BABYLON.Space.LOCAL) {
  77912. lm.m[12] = position.x;
  77913. lm.m[13] = position.y;
  77914. lm.m[14] = position.z;
  77915. }
  77916. else {
  77917. var wm = null;
  77918. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  77919. if (mesh) {
  77920. wm = mesh.getWorldMatrix();
  77921. }
  77922. this._skeleton.computeAbsoluteTransforms();
  77923. var tmat = Bone._tmpMats[0];
  77924. var vec = Bone._tmpVecs[0];
  77925. if (this._parent) {
  77926. if (mesh && wm) {
  77927. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77928. tmat.multiplyToRef(wm, tmat);
  77929. }
  77930. else {
  77931. tmat.copyFrom(this._parent.getAbsoluteTransform());
  77932. }
  77933. }
  77934. tmat.invert();
  77935. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  77936. lm.m[12] = vec.x;
  77937. lm.m[13] = vec.y;
  77938. lm.m[14] = vec.z;
  77939. }
  77940. this._markAsDirtyAndDecompose();
  77941. };
  77942. /**
  77943. * Set the absolute position of the bone (world space)
  77944. * @param position The position to set the bone
  77945. * @param mesh The mesh that this bone is attached to
  77946. */
  77947. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  77948. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  77949. };
  77950. /**
  77951. * Scale the bone on the x, y and z axes (in local space)
  77952. * @param x The amount to scale the bone on the x axis
  77953. * @param y The amount to scale the bone on the y axis
  77954. * @param z The amount to scale the bone on the z axis
  77955. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  77956. */
  77957. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  77958. if (scaleChildren === void 0) { scaleChildren = false; }
  77959. var locMat = this.getLocalMatrix();
  77960. // Apply new scaling on top of current local matrix
  77961. var scaleMat = Bone._tmpMats[0];
  77962. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  77963. scaleMat.multiplyToRef(locMat, locMat);
  77964. // Invert scaling matrix and apply the inverse to all children
  77965. scaleMat.invert();
  77966. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  77967. var child = _a[_i];
  77968. var cm = child.getLocalMatrix();
  77969. cm.multiplyToRef(scaleMat, cm);
  77970. cm.m[12] *= x;
  77971. cm.m[13] *= y;
  77972. cm.m[14] *= z;
  77973. child._markAsDirtyAndDecompose();
  77974. }
  77975. this._markAsDirtyAndDecompose();
  77976. if (scaleChildren) {
  77977. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  77978. var child = _c[_b];
  77979. child.scale(x, y, z, scaleChildren);
  77980. }
  77981. }
  77982. };
  77983. /**
  77984. * Set the bone scaling in local space
  77985. * @param scale defines the scaling vector
  77986. */
  77987. Bone.prototype.setScale = function (scale) {
  77988. this._decompose();
  77989. this._localScaling.copyFrom(scale);
  77990. this._markAsDirtyAndCompose();
  77991. };
  77992. /**
  77993. * Gets the current scaling in local space
  77994. * @returns the current scaling vector
  77995. */
  77996. Bone.prototype.getScale = function () {
  77997. this._decompose();
  77998. return this._localScaling;
  77999. };
  78000. /**
  78001. * Gets the current scaling in local space and stores it in a target vector
  78002. * @param result defines the target vector
  78003. */
  78004. Bone.prototype.getScaleToRef = function (result) {
  78005. this._decompose();
  78006. result.copyFrom(this._localScaling);
  78007. };
  78008. /**
  78009. * Set the yaw, pitch, and roll of the bone in local or world space
  78010. * @param yaw The rotation of the bone on the y axis
  78011. * @param pitch The rotation of the bone on the x axis
  78012. * @param roll The rotation of the bone on the z axis
  78013. * @param space The space that the axes of rotation are in
  78014. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78015. */
  78016. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  78017. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78018. if (space === BABYLON.Space.LOCAL) {
  78019. var quat = Bone._tmpQuat;
  78020. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  78021. this.setRotationQuaternion(quat, space, mesh);
  78022. return;
  78023. }
  78024. var rotMatInv = Bone._tmpMats[0];
  78025. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78026. return;
  78027. }
  78028. var rotMat = Bone._tmpMats[1];
  78029. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  78030. rotMatInv.multiplyToRef(rotMat, rotMat);
  78031. this._rotateWithMatrix(rotMat, space, mesh);
  78032. };
  78033. /**
  78034. * Add a rotation to the bone on an axis in local or world space
  78035. * @param axis The axis to rotate the bone on
  78036. * @param amount The amount to rotate the bone
  78037. * @param space The space that the axis is in
  78038. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78039. */
  78040. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  78041. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78042. var rmat = Bone._tmpMats[0];
  78043. rmat.m[12] = 0;
  78044. rmat.m[13] = 0;
  78045. rmat.m[14] = 0;
  78046. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  78047. this._rotateWithMatrix(rmat, space, mesh);
  78048. };
  78049. /**
  78050. * Set the rotation of the bone to a particular axis angle in local or world space
  78051. * @param axis The axis to rotate the bone on
  78052. * @param angle The angle that the bone should be rotated to
  78053. * @param space The space that the axis is in
  78054. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78055. */
  78056. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  78057. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78058. if (space === BABYLON.Space.LOCAL) {
  78059. var quat = Bone._tmpQuat;
  78060. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  78061. this.setRotationQuaternion(quat, space, mesh);
  78062. return;
  78063. }
  78064. var rotMatInv = Bone._tmpMats[0];
  78065. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78066. return;
  78067. }
  78068. var rotMat = Bone._tmpMats[1];
  78069. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  78070. rotMatInv.multiplyToRef(rotMat, rotMat);
  78071. this._rotateWithMatrix(rotMat, space, mesh);
  78072. };
  78073. /**
  78074. * Set the euler rotation of the bone in local of world space
  78075. * @param rotation The euler rotation that the bone should be set to
  78076. * @param space The space that the rotation is in
  78077. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78078. */
  78079. Bone.prototype.setRotation = function (rotation, space, mesh) {
  78080. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78081. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  78082. };
  78083. /**
  78084. * Set the quaternion rotation of the bone in local of world space
  78085. * @param quat The quaternion rotation that the bone should be set to
  78086. * @param space The space that the rotation is in
  78087. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78088. */
  78089. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  78090. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78091. if (space === BABYLON.Space.LOCAL) {
  78092. this._decompose();
  78093. this._localRotation.copyFrom(quat);
  78094. this._markAsDirtyAndCompose();
  78095. return;
  78096. }
  78097. var rotMatInv = Bone._tmpMats[0];
  78098. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78099. return;
  78100. }
  78101. var rotMat = Bone._tmpMats[1];
  78102. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  78103. rotMatInv.multiplyToRef(rotMat, rotMat);
  78104. this._rotateWithMatrix(rotMat, space, mesh);
  78105. };
  78106. /**
  78107. * Set the rotation matrix of the bone in local of world space
  78108. * @param rotMat The rotation matrix that the bone should be set to
  78109. * @param space The space that the rotation is in
  78110. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78111. */
  78112. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  78113. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78114. if (space === BABYLON.Space.LOCAL) {
  78115. var quat = Bone._tmpQuat;
  78116. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  78117. this.setRotationQuaternion(quat, space, mesh);
  78118. return;
  78119. }
  78120. var rotMatInv = Bone._tmpMats[0];
  78121. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  78122. return;
  78123. }
  78124. var rotMat2 = Bone._tmpMats[1];
  78125. rotMat2.copyFrom(rotMat);
  78126. rotMatInv.multiplyToRef(rotMat, rotMat2);
  78127. this._rotateWithMatrix(rotMat2, space, mesh);
  78128. };
  78129. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  78130. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78131. var lmat = this.getLocalMatrix();
  78132. var lx = lmat.m[12];
  78133. var ly = lmat.m[13];
  78134. var lz = lmat.m[14];
  78135. var parent = this.getParent();
  78136. var parentScale = Bone._tmpMats[3];
  78137. var parentScaleInv = Bone._tmpMats[4];
  78138. if (parent && space == BABYLON.Space.WORLD) {
  78139. if (mesh) {
  78140. parentScale.copyFrom(mesh.getWorldMatrix());
  78141. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  78142. }
  78143. else {
  78144. parentScale.copyFrom(parent.getAbsoluteTransform());
  78145. }
  78146. parentScaleInv.copyFrom(parentScale);
  78147. parentScaleInv.invert();
  78148. lmat.multiplyToRef(parentScale, lmat);
  78149. lmat.multiplyToRef(rmat, lmat);
  78150. lmat.multiplyToRef(parentScaleInv, lmat);
  78151. }
  78152. else {
  78153. if (space == BABYLON.Space.WORLD && mesh) {
  78154. parentScale.copyFrom(mesh.getWorldMatrix());
  78155. parentScaleInv.copyFrom(parentScale);
  78156. parentScaleInv.invert();
  78157. lmat.multiplyToRef(parentScale, lmat);
  78158. lmat.multiplyToRef(rmat, lmat);
  78159. lmat.multiplyToRef(parentScaleInv, lmat);
  78160. }
  78161. else {
  78162. lmat.multiplyToRef(rmat, lmat);
  78163. }
  78164. }
  78165. lmat.m[12] = lx;
  78166. lmat.m[13] = ly;
  78167. lmat.m[14] = lz;
  78168. this.computeAbsoluteTransforms();
  78169. this._markAsDirtyAndDecompose();
  78170. };
  78171. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  78172. var scaleMatrix = Bone._tmpMats[2];
  78173. rotMatInv.copyFrom(this.getAbsoluteTransform());
  78174. if (mesh) {
  78175. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  78176. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  78177. }
  78178. rotMatInv.invert();
  78179. if (isNaN(rotMatInv.m[0])) {
  78180. // Matrix failed to invert.
  78181. // This can happen if scale is zero for example.
  78182. return false;
  78183. }
  78184. scaleMatrix.m[0] *= this._scalingDeterminant;
  78185. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  78186. return true;
  78187. };
  78188. /**
  78189. * Get the position of the bone in local or world space
  78190. * @param space The space that the returned position is in
  78191. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78192. * @returns The position of the bone
  78193. */
  78194. Bone.prototype.getPosition = function (space, mesh) {
  78195. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78196. if (mesh === void 0) { mesh = null; }
  78197. var pos = BABYLON.Vector3.Zero();
  78198. this.getPositionToRef(space, mesh, pos);
  78199. return pos;
  78200. };
  78201. /**
  78202. * Copy the position of the bone to a vector3 in local or world space
  78203. * @param space The space that the returned position is in
  78204. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78205. * @param result The vector3 to copy the position to
  78206. */
  78207. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  78208. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78209. if (space == BABYLON.Space.LOCAL) {
  78210. var lm = this.getLocalMatrix();
  78211. result.x = lm.m[12];
  78212. result.y = lm.m[13];
  78213. result.z = lm.m[14];
  78214. }
  78215. else {
  78216. var wm = null;
  78217. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78218. if (mesh) {
  78219. wm = mesh.getWorldMatrix();
  78220. }
  78221. this._skeleton.computeAbsoluteTransforms();
  78222. var tmat = Bone._tmpMats[0];
  78223. if (mesh && wm) {
  78224. tmat.copyFrom(this.getAbsoluteTransform());
  78225. tmat.multiplyToRef(wm, tmat);
  78226. }
  78227. else {
  78228. tmat = this.getAbsoluteTransform();
  78229. }
  78230. result.x = tmat.m[12];
  78231. result.y = tmat.m[13];
  78232. result.z = tmat.m[14];
  78233. }
  78234. };
  78235. /**
  78236. * Get the absolute position of the bone (world space)
  78237. * @param mesh The mesh that this bone is attached to
  78238. * @returns The absolute position of the bone
  78239. */
  78240. Bone.prototype.getAbsolutePosition = function (mesh) {
  78241. if (mesh === void 0) { mesh = null; }
  78242. var pos = BABYLON.Vector3.Zero();
  78243. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  78244. return pos;
  78245. };
  78246. /**
  78247. * Copy the absolute position of the bone (world space) to the result param
  78248. * @param mesh The mesh that this bone is attached to
  78249. * @param result The vector3 to copy the absolute position to
  78250. */
  78251. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  78252. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  78253. };
  78254. /**
  78255. * Compute the absolute transforms of this bone and its children
  78256. */
  78257. Bone.prototype.computeAbsoluteTransforms = function () {
  78258. this._compose();
  78259. if (this._parent) {
  78260. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  78261. }
  78262. else {
  78263. this._absoluteTransform.copyFrom(this._localMatrix);
  78264. var poseMatrix = this._skeleton.getPoseMatrix();
  78265. if (poseMatrix) {
  78266. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  78267. }
  78268. }
  78269. var children = this.children;
  78270. var len = children.length;
  78271. for (var i = 0; i < len; i++) {
  78272. children[i].computeAbsoluteTransforms();
  78273. }
  78274. };
  78275. /**
  78276. * Get the world direction from an axis that is in the local space of the bone
  78277. * @param localAxis The local direction that is used to compute the world direction
  78278. * @param mesh The mesh that this bone is attached to
  78279. * @returns The world direction
  78280. */
  78281. Bone.prototype.getDirection = function (localAxis, mesh) {
  78282. if (mesh === void 0) { mesh = null; }
  78283. var result = BABYLON.Vector3.Zero();
  78284. this.getDirectionToRef(localAxis, mesh, result);
  78285. return result;
  78286. };
  78287. /**
  78288. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  78289. * @param localAxis The local direction that is used to compute the world direction
  78290. * @param mesh The mesh that this bone is attached to
  78291. * @param result The vector3 that the world direction will be copied to
  78292. */
  78293. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  78294. if (mesh === void 0) { mesh = null; }
  78295. var wm = null;
  78296. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78297. if (mesh) {
  78298. wm = mesh.getWorldMatrix();
  78299. }
  78300. this._skeleton.computeAbsoluteTransforms();
  78301. var mat = Bone._tmpMats[0];
  78302. mat.copyFrom(this.getAbsoluteTransform());
  78303. if (mesh && wm) {
  78304. mat.multiplyToRef(wm, mat);
  78305. }
  78306. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  78307. result.normalize();
  78308. };
  78309. /**
  78310. * Get the euler rotation of the bone in local or world space
  78311. * @param space The space that the rotation should be in
  78312. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78313. * @returns The euler rotation
  78314. */
  78315. Bone.prototype.getRotation = function (space, mesh) {
  78316. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78317. if (mesh === void 0) { mesh = null; }
  78318. var result = BABYLON.Vector3.Zero();
  78319. this.getRotationToRef(space, mesh, result);
  78320. return result;
  78321. };
  78322. /**
  78323. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  78324. * @param space The space that the rotation should be in
  78325. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78326. * @param result The vector3 that the rotation should be copied to
  78327. */
  78328. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  78329. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78330. if (mesh === void 0) { mesh = null; }
  78331. var quat = Bone._tmpQuat;
  78332. this.getRotationQuaternionToRef(space, mesh, quat);
  78333. quat.toEulerAnglesToRef(result);
  78334. };
  78335. /**
  78336. * Get the quaternion rotation of the bone in either local or world space
  78337. * @param space The space that the rotation should be in
  78338. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78339. * @returns The quaternion rotation
  78340. */
  78341. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  78342. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78343. if (mesh === void 0) { mesh = null; }
  78344. var result = BABYLON.Quaternion.Identity();
  78345. this.getRotationQuaternionToRef(space, mesh, result);
  78346. return result;
  78347. };
  78348. /**
  78349. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  78350. * @param space The space that the rotation should be in
  78351. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78352. * @param result The quaternion that the rotation should be copied to
  78353. */
  78354. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  78355. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78356. if (mesh === void 0) { mesh = null; }
  78357. if (space == BABYLON.Space.LOCAL) {
  78358. this._decompose();
  78359. result.copyFrom(this._localRotation);
  78360. }
  78361. else {
  78362. var mat = Bone._tmpMats[0];
  78363. var amat = this.getAbsoluteTransform();
  78364. if (mesh) {
  78365. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78366. }
  78367. else {
  78368. mat.copyFrom(amat);
  78369. }
  78370. mat.m[0] *= this._scalingDeterminant;
  78371. mat.m[1] *= this._scalingDeterminant;
  78372. mat.m[2] *= this._scalingDeterminant;
  78373. mat.decompose(undefined, result, undefined);
  78374. }
  78375. };
  78376. /**
  78377. * Get the rotation matrix of the bone in local or world space
  78378. * @param space The space that the rotation should be in
  78379. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78380. * @returns The rotation matrix
  78381. */
  78382. Bone.prototype.getRotationMatrix = function (space, mesh) {
  78383. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78384. var result = BABYLON.Matrix.Identity();
  78385. this.getRotationMatrixToRef(space, mesh, result);
  78386. return result;
  78387. };
  78388. /**
  78389. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  78390. * @param space The space that the rotation should be in
  78391. * @param mesh The mesh that this bone is attached to. This is only used in world space
  78392. * @param result The quaternion that the rotation should be copied to
  78393. */
  78394. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  78395. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  78396. if (space == BABYLON.Space.LOCAL) {
  78397. this.getLocalMatrix().getRotationMatrixToRef(result);
  78398. }
  78399. else {
  78400. var mat = Bone._tmpMats[0];
  78401. var amat = this.getAbsoluteTransform();
  78402. if (mesh) {
  78403. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  78404. }
  78405. else {
  78406. mat.copyFrom(amat);
  78407. }
  78408. mat.m[0] *= this._scalingDeterminant;
  78409. mat.m[1] *= this._scalingDeterminant;
  78410. mat.m[2] *= this._scalingDeterminant;
  78411. mat.getRotationMatrixToRef(result);
  78412. }
  78413. };
  78414. /**
  78415. * Get the world position of a point that is in the local space of the bone
  78416. * @param position The local position
  78417. * @param mesh The mesh that this bone is attached to
  78418. * @returns The world position
  78419. */
  78420. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  78421. if (mesh === void 0) { mesh = null; }
  78422. var result = BABYLON.Vector3.Zero();
  78423. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  78424. return result;
  78425. };
  78426. /**
  78427. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  78428. * @param position The local position
  78429. * @param mesh The mesh that this bone is attached to
  78430. * @param result The vector3 that the world position should be copied to
  78431. */
  78432. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  78433. if (mesh === void 0) { mesh = null; }
  78434. var wm = null;
  78435. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78436. if (mesh) {
  78437. wm = mesh.getWorldMatrix();
  78438. }
  78439. this._skeleton.computeAbsoluteTransforms();
  78440. var tmat = Bone._tmpMats[0];
  78441. if (mesh && wm) {
  78442. tmat.copyFrom(this.getAbsoluteTransform());
  78443. tmat.multiplyToRef(wm, tmat);
  78444. }
  78445. else {
  78446. tmat = this.getAbsoluteTransform();
  78447. }
  78448. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78449. };
  78450. /**
  78451. * Get the local position of a point that is in world space
  78452. * @param position The world position
  78453. * @param mesh The mesh that this bone is attached to
  78454. * @returns The local position
  78455. */
  78456. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  78457. if (mesh === void 0) { mesh = null; }
  78458. var result = BABYLON.Vector3.Zero();
  78459. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  78460. return result;
  78461. };
  78462. /**
  78463. * Get the local position of a point that is in world space and copy it to the result param
  78464. * @param position The world position
  78465. * @param mesh The mesh that this bone is attached to
  78466. * @param result The vector3 that the local position should be copied to
  78467. */
  78468. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  78469. if (mesh === void 0) { mesh = null; }
  78470. var wm = null;
  78471. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  78472. if (mesh) {
  78473. wm = mesh.getWorldMatrix();
  78474. }
  78475. this._skeleton.computeAbsoluteTransforms();
  78476. var tmat = Bone._tmpMats[0];
  78477. tmat.copyFrom(this.getAbsoluteTransform());
  78478. if (mesh && wm) {
  78479. tmat.multiplyToRef(wm, tmat);
  78480. }
  78481. tmat.invert();
  78482. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  78483. };
  78484. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78485. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  78486. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78487. return Bone;
  78488. }(BABYLON.Node));
  78489. BABYLON.Bone = Bone;
  78490. })(BABYLON || (BABYLON = {}));
  78491. //# sourceMappingURL=babylon.bone.js.map
  78492. var BABYLON;
  78493. (function (BABYLON) {
  78494. /**
  78495. * Class used to apply inverse kinematics to bones
  78496. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  78497. */
  78498. var BoneIKController = /** @class */ (function () {
  78499. /**
  78500. * Creates a new BoneIKController
  78501. * @param mesh defines the mesh to control
  78502. * @param bone defines the bone to control
  78503. * @param options defines options to set up the controller
  78504. */
  78505. function BoneIKController(mesh, bone, options) {
  78506. /**
  78507. * Gets or sets the target position
  78508. */
  78509. this.targetPosition = BABYLON.Vector3.Zero();
  78510. /**
  78511. * Gets or sets the pole target position
  78512. */
  78513. this.poleTargetPosition = BABYLON.Vector3.Zero();
  78514. /**
  78515. * Gets or sets the pole target local offset
  78516. */
  78517. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  78518. /**
  78519. * Gets or sets the pole angle
  78520. */
  78521. this.poleAngle = 0;
  78522. /**
  78523. * 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)
  78524. */
  78525. this.slerpAmount = 1;
  78526. this._bone1Quat = BABYLON.Quaternion.Identity();
  78527. this._bone1Mat = BABYLON.Matrix.Identity();
  78528. this._bone2Ang = Math.PI;
  78529. this._maxAngle = Math.PI;
  78530. this._rightHandedSystem = false;
  78531. this._bendAxis = BABYLON.Vector3.Right();
  78532. this._slerping = false;
  78533. this._adjustRoll = 0;
  78534. this._bone2 = bone;
  78535. this._bone1 = bone.getParent();
  78536. if (!this._bone1) {
  78537. return;
  78538. }
  78539. this.mesh = mesh;
  78540. var bonePos = bone.getPosition();
  78541. if (bone.getAbsoluteTransform().determinant() > 0) {
  78542. this._rightHandedSystem = true;
  78543. this._bendAxis.x = 0;
  78544. this._bendAxis.y = 0;
  78545. this._bendAxis.z = -1;
  78546. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  78547. this._adjustRoll = Math.PI * .5;
  78548. this._bendAxis.z = 1;
  78549. }
  78550. }
  78551. if (this._bone1.length) {
  78552. var boneScale1 = this._bone1.getScale();
  78553. var boneScale2 = this._bone2.getScale();
  78554. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  78555. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  78556. }
  78557. else if (this._bone1.children[0]) {
  78558. mesh.computeWorldMatrix(true);
  78559. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  78560. var pos2 = this._bone2.getAbsolutePosition(mesh);
  78561. var pos3 = this._bone1.getAbsolutePosition(mesh);
  78562. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  78563. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  78564. }
  78565. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  78566. this.maxAngle = Math.PI;
  78567. if (options) {
  78568. if (options.targetMesh) {
  78569. this.targetMesh = options.targetMesh;
  78570. this.targetMesh.computeWorldMatrix(true);
  78571. }
  78572. if (options.poleTargetMesh) {
  78573. this.poleTargetMesh = options.poleTargetMesh;
  78574. this.poleTargetMesh.computeWorldMatrix(true);
  78575. }
  78576. else if (options.poleTargetBone) {
  78577. this.poleTargetBone = options.poleTargetBone;
  78578. }
  78579. else if (this._bone1.getParent()) {
  78580. this.poleTargetBone = this._bone1.getParent();
  78581. }
  78582. if (options.poleTargetLocalOffset) {
  78583. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  78584. }
  78585. if (options.poleAngle) {
  78586. this.poleAngle = options.poleAngle;
  78587. }
  78588. if (options.bendAxis) {
  78589. this._bendAxis.copyFrom(options.bendAxis);
  78590. }
  78591. if (options.maxAngle) {
  78592. this.maxAngle = options.maxAngle;
  78593. }
  78594. if (options.slerpAmount) {
  78595. this.slerpAmount = options.slerpAmount;
  78596. }
  78597. }
  78598. }
  78599. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  78600. /**
  78601. * Gets or sets maximum allowed angle
  78602. */
  78603. get: function () {
  78604. return this._maxAngle;
  78605. },
  78606. set: function (value) {
  78607. this._setMaxAngle(value);
  78608. },
  78609. enumerable: true,
  78610. configurable: true
  78611. });
  78612. BoneIKController.prototype._setMaxAngle = function (ang) {
  78613. if (ang < 0) {
  78614. ang = 0;
  78615. }
  78616. if (ang > Math.PI || ang == undefined) {
  78617. ang = Math.PI;
  78618. }
  78619. this._maxAngle = ang;
  78620. var a = this._bone1Length;
  78621. var b = this._bone2Length;
  78622. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  78623. };
  78624. /**
  78625. * Force the controller to update the bones
  78626. */
  78627. BoneIKController.prototype.update = function () {
  78628. var bone1 = this._bone1;
  78629. if (!bone1) {
  78630. return;
  78631. }
  78632. var target = this.targetPosition;
  78633. var poleTarget = this.poleTargetPosition;
  78634. var mat1 = BoneIKController._tmpMats[0];
  78635. var mat2 = BoneIKController._tmpMats[1];
  78636. if (this.targetMesh) {
  78637. target.copyFrom(this.targetMesh.getAbsolutePosition());
  78638. }
  78639. if (this.poleTargetBone) {
  78640. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  78641. }
  78642. else if (this.poleTargetMesh) {
  78643. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  78644. }
  78645. var bonePos = BoneIKController._tmpVecs[0];
  78646. var zaxis = BoneIKController._tmpVecs[1];
  78647. var xaxis = BoneIKController._tmpVecs[2];
  78648. var yaxis = BoneIKController._tmpVecs[3];
  78649. var upAxis = BoneIKController._tmpVecs[4];
  78650. var _tmpQuat = BoneIKController._tmpQuat;
  78651. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  78652. poleTarget.subtractToRef(bonePos, upAxis);
  78653. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  78654. upAxis.y = 1;
  78655. }
  78656. else {
  78657. upAxis.normalize();
  78658. }
  78659. target.subtractToRef(bonePos, yaxis);
  78660. yaxis.normalize();
  78661. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  78662. zaxis.normalize();
  78663. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  78664. xaxis.normalize();
  78665. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  78666. var a = this._bone1Length;
  78667. var b = this._bone2Length;
  78668. var c = BABYLON.Vector3.Distance(bonePos, target);
  78669. if (this._maxReach > 0) {
  78670. c = Math.min(this._maxReach, c);
  78671. }
  78672. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  78673. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  78674. if (acosa > 1) {
  78675. acosa = 1;
  78676. }
  78677. if (acosb > 1) {
  78678. acosb = 1;
  78679. }
  78680. if (acosa < -1) {
  78681. acosa = -1;
  78682. }
  78683. if (acosb < -1) {
  78684. acosb = -1;
  78685. }
  78686. var angA = Math.acos(acosa);
  78687. var angB = Math.acos(acosb);
  78688. var angC = -angA - angB;
  78689. if (this._rightHandedSystem) {
  78690. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  78691. mat2.multiplyToRef(mat1, mat1);
  78692. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  78693. mat2.multiplyToRef(mat1, mat1);
  78694. }
  78695. else {
  78696. var _tmpVec = BoneIKController._tmpVecs[5];
  78697. _tmpVec.copyFrom(this._bendAxis);
  78698. _tmpVec.x *= -1;
  78699. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  78700. mat2.multiplyToRef(mat1, mat1);
  78701. }
  78702. if (this.poleAngle) {
  78703. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  78704. mat1.multiplyToRef(mat2, mat1);
  78705. }
  78706. if (this._bone1) {
  78707. if (this.slerpAmount < 1) {
  78708. if (!this._slerping) {
  78709. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  78710. }
  78711. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  78712. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  78713. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  78714. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  78715. this._slerping = true;
  78716. }
  78717. else {
  78718. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  78719. this._bone1Mat.copyFrom(mat1);
  78720. this._slerping = false;
  78721. }
  78722. }
  78723. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  78724. this._bone2Ang = angC;
  78725. };
  78726. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  78727. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  78728. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  78729. return BoneIKController;
  78730. }());
  78731. BABYLON.BoneIKController = BoneIKController;
  78732. })(BABYLON || (BABYLON = {}));
  78733. //# sourceMappingURL=babylon.boneIKController.js.map
  78734. var BABYLON;
  78735. (function (BABYLON) {
  78736. /**
  78737. * Class used to make a bone look toward a point in space
  78738. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  78739. */
  78740. var BoneLookController = /** @class */ (function () {
  78741. /**
  78742. * Create a BoneLookController
  78743. * @param mesh the mesh that the bone belongs to
  78744. * @param bone the bone that will be looking to the target
  78745. * @param target the target Vector3 to look at
  78746. * @param settings optional settings:
  78747. * * maxYaw: the maximum angle the bone will yaw to
  78748. * * minYaw: the minimum angle the bone will yaw to
  78749. * * maxPitch: the maximum angle the bone will pitch to
  78750. * * minPitch: the minimum angle the bone will yaw to
  78751. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  78752. * * upAxis: the up axis of the coordinate system
  78753. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  78754. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  78755. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  78756. * * adjustYaw: used to make an adjustment to the yaw of the bone
  78757. * * adjustPitch: used to make an adjustment to the pitch of the bone
  78758. * * adjustRoll: used to make an adjustment to the roll of the bone
  78759. **/
  78760. function BoneLookController(mesh, bone, target, options) {
  78761. /**
  78762. * The up axis of the coordinate system that is used when the bone is rotated
  78763. */
  78764. this.upAxis = BABYLON.Vector3.Up();
  78765. /**
  78766. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  78767. */
  78768. this.upAxisSpace = BABYLON.Space.LOCAL;
  78769. /**
  78770. * Used to make an adjustment to the yaw of the bone
  78771. */
  78772. this.adjustYaw = 0;
  78773. /**
  78774. * Used to make an adjustment to the pitch of the bone
  78775. */
  78776. this.adjustPitch = 0;
  78777. /**
  78778. * Used to make an adjustment to the roll of the bone
  78779. */
  78780. this.adjustRoll = 0;
  78781. /**
  78782. * 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)
  78783. */
  78784. this.slerpAmount = 1;
  78785. this._boneQuat = BABYLON.Quaternion.Identity();
  78786. this._slerping = false;
  78787. this._firstFrameSkipped = false;
  78788. this._fowardAxis = BABYLON.Vector3.Forward();
  78789. this.mesh = mesh;
  78790. this.bone = bone;
  78791. this.target = target;
  78792. if (options) {
  78793. if (options.adjustYaw) {
  78794. this.adjustYaw = options.adjustYaw;
  78795. }
  78796. if (options.adjustPitch) {
  78797. this.adjustPitch = options.adjustPitch;
  78798. }
  78799. if (options.adjustRoll) {
  78800. this.adjustRoll = options.adjustRoll;
  78801. }
  78802. if (options.maxYaw != null) {
  78803. this.maxYaw = options.maxYaw;
  78804. }
  78805. else {
  78806. this.maxYaw = Math.PI;
  78807. }
  78808. if (options.minYaw != null) {
  78809. this.minYaw = options.minYaw;
  78810. }
  78811. else {
  78812. this.minYaw = -Math.PI;
  78813. }
  78814. if (options.maxPitch != null) {
  78815. this.maxPitch = options.maxPitch;
  78816. }
  78817. else {
  78818. this.maxPitch = Math.PI;
  78819. }
  78820. if (options.minPitch != null) {
  78821. this.minPitch = options.minPitch;
  78822. }
  78823. else {
  78824. this.minPitch = -Math.PI;
  78825. }
  78826. if (options.slerpAmount != null) {
  78827. this.slerpAmount = options.slerpAmount;
  78828. }
  78829. if (options.upAxis != null) {
  78830. this.upAxis = options.upAxis;
  78831. }
  78832. if (options.upAxisSpace != null) {
  78833. this.upAxisSpace = options.upAxisSpace;
  78834. }
  78835. if (options.yawAxis != null || options.pitchAxis != null) {
  78836. var newYawAxis = BABYLON.Axis.Y;
  78837. var newPitchAxis = BABYLON.Axis.X;
  78838. if (options.yawAxis != null) {
  78839. newYawAxis = options.yawAxis.clone();
  78840. newYawAxis.normalize();
  78841. }
  78842. if (options.pitchAxis != null) {
  78843. newPitchAxis = options.pitchAxis.clone();
  78844. newPitchAxis.normalize();
  78845. }
  78846. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  78847. this._transformYawPitch = BABYLON.Matrix.Identity();
  78848. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  78849. this._transformYawPitchInv = this._transformYawPitch.clone();
  78850. this._transformYawPitch.invert();
  78851. }
  78852. }
  78853. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  78854. this.upAxisSpace = BABYLON.Space.LOCAL;
  78855. }
  78856. }
  78857. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  78858. /**
  78859. * Gets or sets the minimum yaw angle that the bone can look to
  78860. */
  78861. get: function () {
  78862. return this._minYaw;
  78863. },
  78864. set: function (value) {
  78865. this._minYaw = value;
  78866. this._minYawSin = Math.sin(value);
  78867. this._minYawCos = Math.cos(value);
  78868. if (this._maxYaw != null) {
  78869. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78870. this._yawRange = this._maxYaw - this._minYaw;
  78871. }
  78872. },
  78873. enumerable: true,
  78874. configurable: true
  78875. });
  78876. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  78877. /**
  78878. * Gets or sets the maximum yaw angle that the bone can look to
  78879. */
  78880. get: function () {
  78881. return this._maxYaw;
  78882. },
  78883. set: function (value) {
  78884. this._maxYaw = value;
  78885. this._maxYawSin = Math.sin(value);
  78886. this._maxYawCos = Math.cos(value);
  78887. if (this._minYaw != null) {
  78888. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  78889. this._yawRange = this._maxYaw - this._minYaw;
  78890. }
  78891. },
  78892. enumerable: true,
  78893. configurable: true
  78894. });
  78895. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  78896. /**
  78897. * Gets or sets the minimum pitch angle that the bone can look to
  78898. */
  78899. get: function () {
  78900. return this._minPitch;
  78901. },
  78902. set: function (value) {
  78903. this._minPitch = value;
  78904. this._minPitchTan = Math.tan(value);
  78905. },
  78906. enumerable: true,
  78907. configurable: true
  78908. });
  78909. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  78910. /**
  78911. * Gets or sets the maximum pitch angle that the bone can look to
  78912. */
  78913. get: function () {
  78914. return this._maxPitch;
  78915. },
  78916. set: function (value) {
  78917. this._maxPitch = value;
  78918. this._maxPitchTan = Math.tan(value);
  78919. },
  78920. enumerable: true,
  78921. configurable: true
  78922. });
  78923. /**
  78924. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  78925. */
  78926. BoneLookController.prototype.update = function () {
  78927. //skip the first frame when slerping so that the mesh rotation is correct
  78928. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  78929. this._firstFrameSkipped = true;
  78930. return;
  78931. }
  78932. var bone = this.bone;
  78933. var bonePos = BoneLookController._tmpVecs[0];
  78934. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  78935. var target = this.target;
  78936. var _tmpMat1 = BoneLookController._tmpMats[0];
  78937. var _tmpMat2 = BoneLookController._tmpMats[1];
  78938. var mesh = this.mesh;
  78939. var parentBone = bone.getParent();
  78940. var upAxis = BoneLookController._tmpVecs[1];
  78941. upAxis.copyFrom(this.upAxis);
  78942. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  78943. if (this._transformYawPitch) {
  78944. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  78945. }
  78946. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  78947. }
  78948. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  78949. mesh.getDirectionToRef(upAxis, upAxis);
  78950. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  78951. upAxis.normalize();
  78952. }
  78953. }
  78954. var checkYaw = false;
  78955. var checkPitch = false;
  78956. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  78957. checkYaw = true;
  78958. }
  78959. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  78960. checkPitch = true;
  78961. }
  78962. if (checkYaw || checkPitch) {
  78963. var spaceMat = BoneLookController._tmpMats[2];
  78964. var spaceMatInv = BoneLookController._tmpMats[3];
  78965. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  78966. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  78967. }
  78968. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  78969. spaceMat.copyFrom(mesh.getWorldMatrix());
  78970. }
  78971. else {
  78972. var forwardAxis = BoneLookController._tmpVecs[2];
  78973. forwardAxis.copyFrom(this._fowardAxis);
  78974. if (this._transformYawPitch) {
  78975. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  78976. }
  78977. if (parentBone) {
  78978. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  78979. }
  78980. else {
  78981. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  78982. }
  78983. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  78984. rightAxis.normalize();
  78985. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  78986. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  78987. }
  78988. spaceMat.invertToRef(spaceMatInv);
  78989. var xzlen = null;
  78990. if (checkPitch) {
  78991. var localTarget = BoneLookController._tmpVecs[3];
  78992. target.subtractToRef(bonePos, localTarget);
  78993. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  78994. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  78995. var pitch = Math.atan2(localTarget.y, xzlen);
  78996. var newPitch = pitch;
  78997. if (pitch > this._maxPitch) {
  78998. localTarget.y = this._maxPitchTan * xzlen;
  78999. newPitch = this._maxPitch;
  79000. }
  79001. else if (pitch < this._minPitch) {
  79002. localTarget.y = this._minPitchTan * xzlen;
  79003. newPitch = this._minPitch;
  79004. }
  79005. if (pitch != newPitch) {
  79006. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79007. localTarget.addInPlace(bonePos);
  79008. target = localTarget;
  79009. }
  79010. }
  79011. if (checkYaw) {
  79012. var localTarget = BoneLookController._tmpVecs[4];
  79013. target.subtractToRef(bonePos, localTarget);
  79014. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  79015. var yaw = Math.atan2(localTarget.x, localTarget.z);
  79016. var newYaw = yaw;
  79017. if (yaw > this._maxYaw || yaw < this._minYaw) {
  79018. if (xzlen == null) {
  79019. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79020. }
  79021. if (this._yawRange > Math.PI) {
  79022. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  79023. localTarget.z = this._maxYawCos * xzlen;
  79024. localTarget.x = this._maxYawSin * xzlen;
  79025. newYaw = this._maxYaw;
  79026. }
  79027. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  79028. localTarget.z = this._minYawCos * xzlen;
  79029. localTarget.x = this._minYawSin * xzlen;
  79030. newYaw = this._minYaw;
  79031. }
  79032. }
  79033. else {
  79034. if (yaw > this._maxYaw) {
  79035. localTarget.z = this._maxYawCos * xzlen;
  79036. localTarget.x = this._maxYawSin * xzlen;
  79037. newYaw = this._maxYaw;
  79038. }
  79039. else if (yaw < this._minYaw) {
  79040. localTarget.z = this._minYawCos * xzlen;
  79041. localTarget.x = this._minYawSin * xzlen;
  79042. newYaw = this._minYaw;
  79043. }
  79044. }
  79045. }
  79046. if (this._slerping && this._yawRange > Math.PI) {
  79047. //are we going to be crossing into the min/max region?
  79048. var boneFwd = BoneLookController._tmpVecs[8];
  79049. boneFwd.copyFrom(BABYLON.Axis.Z);
  79050. if (this._transformYawPitch) {
  79051. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  79052. }
  79053. var boneRotMat = BoneLookController._tmpMats[4];
  79054. this._boneQuat.toRotationMatrix(boneRotMat);
  79055. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  79056. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  79057. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  79058. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  79059. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  79060. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  79061. if (angBtwTar > angBtwMidYaw) {
  79062. if (xzlen == null) {
  79063. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  79064. }
  79065. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  79066. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  79067. if (angBtwMin < angBtwMax) {
  79068. newYaw = boneYaw + Math.PI * .75;
  79069. localTarget.z = Math.cos(newYaw) * xzlen;
  79070. localTarget.x = Math.sin(newYaw) * xzlen;
  79071. }
  79072. else {
  79073. newYaw = boneYaw - Math.PI * .75;
  79074. localTarget.z = Math.cos(newYaw) * xzlen;
  79075. localTarget.x = Math.sin(newYaw) * xzlen;
  79076. }
  79077. }
  79078. }
  79079. if (yaw != newYaw) {
  79080. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  79081. localTarget.addInPlace(bonePos);
  79082. target = localTarget;
  79083. }
  79084. }
  79085. }
  79086. var zaxis = BoneLookController._tmpVecs[5];
  79087. var xaxis = BoneLookController._tmpVecs[6];
  79088. var yaxis = BoneLookController._tmpVecs[7];
  79089. var _tmpQuat = BoneLookController._tmpQuat;
  79090. target.subtractToRef(bonePos, zaxis);
  79091. zaxis.normalize();
  79092. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  79093. xaxis.normalize();
  79094. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  79095. yaxis.normalize();
  79096. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  79097. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  79098. return;
  79099. }
  79100. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  79101. return;
  79102. }
  79103. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  79104. return;
  79105. }
  79106. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  79107. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  79108. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  79109. }
  79110. if (this.slerpAmount < 1) {
  79111. if (!this._slerping) {
  79112. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  79113. }
  79114. if (this._transformYawPitch) {
  79115. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79116. }
  79117. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  79118. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  79119. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  79120. this._slerping = true;
  79121. }
  79122. else {
  79123. if (this._transformYawPitch) {
  79124. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  79125. }
  79126. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  79127. this._slerping = false;
  79128. }
  79129. };
  79130. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  79131. var angDiff = ang2 - ang1;
  79132. angDiff %= Math.PI * 2;
  79133. if (angDiff > Math.PI) {
  79134. angDiff -= Math.PI * 2;
  79135. }
  79136. else if (angDiff < -Math.PI) {
  79137. angDiff += Math.PI * 2;
  79138. }
  79139. return angDiff;
  79140. };
  79141. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  79142. ang1 %= (2 * Math.PI);
  79143. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79144. ang2 %= (2 * Math.PI);
  79145. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79146. var ab = 0;
  79147. if (ang1 < ang2) {
  79148. ab = ang2 - ang1;
  79149. }
  79150. else {
  79151. ab = ang1 - ang2;
  79152. }
  79153. if (ab > Math.PI) {
  79154. ab = Math.PI * 2 - ab;
  79155. }
  79156. return ab;
  79157. };
  79158. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  79159. ang %= (2 * Math.PI);
  79160. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  79161. ang1 %= (2 * Math.PI);
  79162. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  79163. ang2 %= (2 * Math.PI);
  79164. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  79165. if (ang1 < ang2) {
  79166. if (ang > ang1 && ang < ang2) {
  79167. return true;
  79168. }
  79169. }
  79170. else {
  79171. if (ang > ang2 && ang < ang1) {
  79172. return true;
  79173. }
  79174. }
  79175. return false;
  79176. };
  79177. 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()];
  79178. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  79179. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  79180. return BoneLookController;
  79181. }());
  79182. BABYLON.BoneLookController = BoneLookController;
  79183. })(BABYLON || (BABYLON = {}));
  79184. //# sourceMappingURL=babylon.boneLookController.js.map
  79185. var BABYLON;
  79186. (function (BABYLON) {
  79187. /**
  79188. * Class used to handle skinning animations
  79189. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79190. */
  79191. var Skeleton = /** @class */ (function () {
  79192. /**
  79193. * Creates a new skeleton
  79194. * @param name defines the skeleton name
  79195. * @param id defines the skeleton Id
  79196. * @param scene defines the hosting scene
  79197. */
  79198. function Skeleton(
  79199. /** defines the skeleton name */
  79200. name,
  79201. /** defines the skeleton Id */
  79202. id, scene) {
  79203. this.name = name;
  79204. this.id = id;
  79205. /**
  79206. * Gets the list of child bones
  79207. */
  79208. this.bones = new Array();
  79209. /**
  79210. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  79211. */
  79212. this.needInitialSkinMatrix = false;
  79213. this._isDirty = true;
  79214. this._meshesWithPoseMatrix = new Array();
  79215. this._identity = BABYLON.Matrix.Identity();
  79216. this._ranges = {};
  79217. this._lastAbsoluteTransformsUpdateId = -1;
  79218. /**
  79219. * Specifies if the skeleton should be serialized
  79220. */
  79221. this.doNotSerialize = false;
  79222. this._animationPropertiesOverride = null;
  79223. // Events
  79224. /**
  79225. * An observable triggered before computing the skeleton's matrices
  79226. */
  79227. this.onBeforeComputeObservable = new BABYLON.Observable();
  79228. this.bones = [];
  79229. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  79230. scene.skeletons.push(this);
  79231. //make sure it will recalculate the matrix next time prepare is called.
  79232. this._isDirty = true;
  79233. }
  79234. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  79235. /**
  79236. * Gets or sets the animation properties override
  79237. */
  79238. get: function () {
  79239. if (!this._animationPropertiesOverride) {
  79240. return this._scene.animationPropertiesOverride;
  79241. }
  79242. return this._animationPropertiesOverride;
  79243. },
  79244. set: function (value) {
  79245. this._animationPropertiesOverride = value;
  79246. },
  79247. enumerable: true,
  79248. configurable: true
  79249. });
  79250. // Members
  79251. /**
  79252. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  79253. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  79254. * @returns a Float32Array containing matrices data
  79255. */
  79256. Skeleton.prototype.getTransformMatrices = function (mesh) {
  79257. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  79258. return mesh._bonesTransformMatrices;
  79259. }
  79260. if (!this._transformMatrices) {
  79261. this.prepare();
  79262. }
  79263. return this._transformMatrices;
  79264. };
  79265. /**
  79266. * Gets the current hosting scene
  79267. * @returns a scene object
  79268. */
  79269. Skeleton.prototype.getScene = function () {
  79270. return this._scene;
  79271. };
  79272. // Methods
  79273. /**
  79274. * Gets a string representing the current skeleton data
  79275. * @param fullDetails defines a boolean indicating if we want a verbose version
  79276. * @returns a string representing the current skeleton data
  79277. */
  79278. Skeleton.prototype.toString = function (fullDetails) {
  79279. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  79280. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  79281. if (fullDetails) {
  79282. ret += ", Ranges: {";
  79283. var first = true;
  79284. for (var name_1 in this._ranges) {
  79285. if (first) {
  79286. ret += ", ";
  79287. first = false;
  79288. }
  79289. ret += name_1;
  79290. }
  79291. ret += "}";
  79292. }
  79293. return ret;
  79294. };
  79295. /**
  79296. * Get bone's index searching by name
  79297. * @param name defines bone's name to search for
  79298. * @return the indice of the bone. Returns -1 if not found
  79299. */
  79300. Skeleton.prototype.getBoneIndexByName = function (name) {
  79301. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  79302. if (this.bones[boneIndex].name === name) {
  79303. return boneIndex;
  79304. }
  79305. }
  79306. return -1;
  79307. };
  79308. /**
  79309. * Creater a new animation range
  79310. * @param name defines the name of the range
  79311. * @param from defines the start key
  79312. * @param to defines the end key
  79313. */
  79314. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  79315. // check name not already in use
  79316. if (!this._ranges[name]) {
  79317. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  79318. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79319. if (this.bones[i].animations[0]) {
  79320. this.bones[i].animations[0].createRange(name, from, to);
  79321. }
  79322. }
  79323. }
  79324. };
  79325. /**
  79326. * Delete a specific animation range
  79327. * @param name defines the name of the range
  79328. * @param deleteFrames defines if frames must be removed as well
  79329. */
  79330. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  79331. if (deleteFrames === void 0) { deleteFrames = true; }
  79332. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79333. if (this.bones[i].animations[0]) {
  79334. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  79335. }
  79336. }
  79337. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  79338. };
  79339. /**
  79340. * Gets a specific animation range
  79341. * @param name defines the name of the range to look for
  79342. * @returns the requested animation range or null if not found
  79343. */
  79344. Skeleton.prototype.getAnimationRange = function (name) {
  79345. return this._ranges[name];
  79346. };
  79347. /**
  79348. * Gets the list of all animation ranges defined on this skeleton
  79349. * @returns an array
  79350. */
  79351. Skeleton.prototype.getAnimationRanges = function () {
  79352. var animationRanges = [];
  79353. var name;
  79354. var i = 0;
  79355. for (name in this._ranges) {
  79356. animationRanges[i] = this._ranges[name];
  79357. i++;
  79358. }
  79359. return animationRanges;
  79360. };
  79361. /**
  79362. * Copy animation range from a source skeleton.
  79363. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  79364. * @param source defines the source skeleton
  79365. * @param name defines the name of the range to copy
  79366. * @param rescaleAsRequired defines if rescaling must be applied if required
  79367. * @returns true if operation was successful
  79368. */
  79369. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  79370. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79371. if (this._ranges[name] || !source.getAnimationRange(name)) {
  79372. return false;
  79373. }
  79374. var ret = true;
  79375. var frameOffset = this._getHighestAnimationFrame() + 1;
  79376. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  79377. var boneDict = {};
  79378. var sourceBones = source.bones;
  79379. var nBones;
  79380. var i;
  79381. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  79382. boneDict[sourceBones[i].name] = sourceBones[i];
  79383. }
  79384. if (this.bones.length !== sourceBones.length) {
  79385. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  79386. ret = false;
  79387. }
  79388. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  79389. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  79390. var boneName = this.bones[i].name;
  79391. var sourceBone = boneDict[boneName];
  79392. if (sourceBone) {
  79393. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  79394. }
  79395. else {
  79396. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  79397. ret = false;
  79398. }
  79399. }
  79400. // do not call createAnimationRange(), since it also is done to bones, which was already done
  79401. var range = source.getAnimationRange(name);
  79402. if (range) {
  79403. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  79404. }
  79405. return ret;
  79406. };
  79407. /**
  79408. * Forces the skeleton to go to rest pose
  79409. */
  79410. Skeleton.prototype.returnToRest = function () {
  79411. for (var index = 0; index < this.bones.length; index++) {
  79412. this.bones[index].returnToRest();
  79413. }
  79414. };
  79415. Skeleton.prototype._getHighestAnimationFrame = function () {
  79416. var ret = 0;
  79417. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  79418. if (this.bones[i].animations[0]) {
  79419. var highest = this.bones[i].animations[0].getHighestFrame();
  79420. if (ret < highest) {
  79421. ret = highest;
  79422. }
  79423. }
  79424. }
  79425. return ret;
  79426. };
  79427. /**
  79428. * Begin a specific animation range
  79429. * @param name defines the name of the range to start
  79430. * @param loop defines if looping must be turned on (false by default)
  79431. * @param speedRatio defines the speed ratio to apply (1 by default)
  79432. * @param onAnimationEnd defines a callback which will be called when animation will end
  79433. * @returns a new animatable
  79434. */
  79435. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  79436. var range = this.getAnimationRange(name);
  79437. if (!range) {
  79438. return null;
  79439. }
  79440. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  79441. };
  79442. /** @hidden */
  79443. Skeleton.prototype._markAsDirty = function () {
  79444. this._isDirty = true;
  79445. };
  79446. /** @hidden */
  79447. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  79448. this._meshesWithPoseMatrix.push(mesh);
  79449. };
  79450. /** @hidden */
  79451. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  79452. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  79453. if (index > -1) {
  79454. this._meshesWithPoseMatrix.splice(index, 1);
  79455. }
  79456. };
  79457. /** @hidden */
  79458. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  79459. this.onBeforeComputeObservable.notifyObservers(this);
  79460. for (var index = 0; index < this.bones.length; index++) {
  79461. var bone = this.bones[index];
  79462. var parentBone = bone.getParent();
  79463. if (parentBone) {
  79464. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  79465. }
  79466. else {
  79467. if (initialSkinMatrix) {
  79468. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  79469. }
  79470. else {
  79471. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  79472. }
  79473. }
  79474. if (bone._index !== -1) {
  79475. var mappedIndex = bone._index === null ? index : bone._index;
  79476. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  79477. }
  79478. }
  79479. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  79480. };
  79481. /**
  79482. * Build all resources required to render a skeleton
  79483. */
  79484. Skeleton.prototype.prepare = function () {
  79485. if (!this._isDirty) {
  79486. return;
  79487. }
  79488. if (this.needInitialSkinMatrix) {
  79489. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  79490. var mesh = this._meshesWithPoseMatrix[index];
  79491. var poseMatrix = mesh.getPoseMatrix();
  79492. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  79493. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79494. }
  79495. if (this._synchronizedWithMesh !== mesh) {
  79496. this._synchronizedWithMesh = mesh;
  79497. // Prepare bones
  79498. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  79499. var bone = this.bones[boneIndex];
  79500. if (!bone.getParent()) {
  79501. var matrix = bone.getBaseMatrix();
  79502. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  79503. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  79504. }
  79505. }
  79506. }
  79507. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  79508. }
  79509. }
  79510. else {
  79511. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  79512. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  79513. }
  79514. this._computeTransformMatrices(this._transformMatrices, null);
  79515. }
  79516. this._isDirty = false;
  79517. this._scene._activeBones.addCount(this.bones.length, false);
  79518. };
  79519. /**
  79520. * Gets the list of animatables currently running for this skeleton
  79521. * @returns an array of animatables
  79522. */
  79523. Skeleton.prototype.getAnimatables = function () {
  79524. if (!this._animatables || this._animatables.length !== this.bones.length) {
  79525. this._animatables = [];
  79526. for (var index = 0; index < this.bones.length; index++) {
  79527. this._animatables.push(this.bones[index]);
  79528. }
  79529. }
  79530. return this._animatables;
  79531. };
  79532. /**
  79533. * Clone the current skeleton
  79534. * @param name defines the name of the new skeleton
  79535. * @param id defines the id of the enw skeleton
  79536. * @returns the new skeleton
  79537. */
  79538. Skeleton.prototype.clone = function (name, id) {
  79539. var result = new Skeleton(name, id || name, this._scene);
  79540. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79541. for (var index = 0; index < this.bones.length; index++) {
  79542. var source = this.bones[index];
  79543. var parentBone = null;
  79544. var parent_1 = source.getParent();
  79545. if (parent_1) {
  79546. var parentIndex = this.bones.indexOf(parent_1);
  79547. parentBone = result.bones[parentIndex];
  79548. }
  79549. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  79550. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  79551. }
  79552. if (this._ranges) {
  79553. result._ranges = {};
  79554. for (var rangeName in this._ranges) {
  79555. var range = this._ranges[rangeName];
  79556. if (range) {
  79557. result._ranges[rangeName] = range.clone();
  79558. }
  79559. }
  79560. }
  79561. this._isDirty = true;
  79562. return result;
  79563. };
  79564. /**
  79565. * Enable animation blending for this skeleton
  79566. * @param blendingSpeed defines the blending speed to apply
  79567. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  79568. */
  79569. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  79570. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  79571. this.bones.forEach(function (bone) {
  79572. bone.animations.forEach(function (animation) {
  79573. animation.enableBlending = true;
  79574. animation.blendingSpeed = blendingSpeed;
  79575. });
  79576. });
  79577. };
  79578. /**
  79579. * Releases all resources associated with the current skeleton
  79580. */
  79581. Skeleton.prototype.dispose = function () {
  79582. this._meshesWithPoseMatrix = [];
  79583. // Animations
  79584. this.getScene().stopAnimation(this);
  79585. // Remove from scene
  79586. this.getScene().removeSkeleton(this);
  79587. };
  79588. /**
  79589. * Serialize the skeleton in a JSON object
  79590. * @returns a JSON object
  79591. */
  79592. Skeleton.prototype.serialize = function () {
  79593. var serializationObject = {};
  79594. serializationObject.name = this.name;
  79595. serializationObject.id = this.id;
  79596. if (this.dimensionsAtRest) {
  79597. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  79598. }
  79599. serializationObject.bones = [];
  79600. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  79601. for (var index = 0; index < this.bones.length; index++) {
  79602. var bone = this.bones[index];
  79603. var parent_2 = bone.getParent();
  79604. var serializedBone = {
  79605. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  79606. name: bone.name,
  79607. matrix: bone.getBaseMatrix().toArray(),
  79608. rest: bone.getRestPose().toArray()
  79609. };
  79610. serializationObject.bones.push(serializedBone);
  79611. if (bone.length) {
  79612. serializedBone.length = bone.length;
  79613. }
  79614. if (bone.metadata) {
  79615. serializedBone.metadata = bone.metadata;
  79616. }
  79617. if (bone.animations && bone.animations.length > 0) {
  79618. serializedBone.animation = bone.animations[0].serialize();
  79619. }
  79620. serializationObject.ranges = [];
  79621. for (var name in this._ranges) {
  79622. var source = this._ranges[name];
  79623. if (!source) {
  79624. continue;
  79625. }
  79626. var range = {};
  79627. range.name = name;
  79628. range.from = source.from;
  79629. range.to = source.to;
  79630. serializationObject.ranges.push(range);
  79631. }
  79632. }
  79633. return serializationObject;
  79634. };
  79635. /**
  79636. * Creates a new skeleton from serialized data
  79637. * @param parsedSkeleton defines the serialized data
  79638. * @param scene defines the hosting scene
  79639. * @returns a new skeleton
  79640. */
  79641. Skeleton.Parse = function (parsedSkeleton, scene) {
  79642. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  79643. if (parsedSkeleton.dimensionsAtRest) {
  79644. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  79645. }
  79646. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  79647. var index;
  79648. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  79649. var parsedBone = parsedSkeleton.bones[index];
  79650. var parentBone = null;
  79651. if (parsedBone.parentBoneIndex > -1) {
  79652. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  79653. }
  79654. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  79655. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  79656. if (parsedBone.length) {
  79657. bone.length = parsedBone.length;
  79658. }
  79659. if (parsedBone.metadata) {
  79660. bone.metadata = parsedBone.metadata;
  79661. }
  79662. if (parsedBone.animation) {
  79663. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  79664. }
  79665. }
  79666. // placed after bones, so createAnimationRange can cascade down
  79667. if (parsedSkeleton.ranges) {
  79668. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  79669. var data = parsedSkeleton.ranges[index];
  79670. skeleton.createAnimationRange(data.name, data.from, data.to);
  79671. }
  79672. }
  79673. return skeleton;
  79674. };
  79675. /**
  79676. * Compute all node absolute transforms
  79677. * @param forceUpdate defines if computation must be done even if cache is up to date
  79678. */
  79679. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  79680. if (forceUpdate === void 0) { forceUpdate = false; }
  79681. var renderId = this._scene.getRenderId();
  79682. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  79683. this.bones[0].computeAbsoluteTransforms();
  79684. this._lastAbsoluteTransformsUpdateId = renderId;
  79685. }
  79686. };
  79687. /**
  79688. * Gets the root pose matrix
  79689. * @returns a matrix
  79690. */
  79691. Skeleton.prototype.getPoseMatrix = function () {
  79692. var poseMatrix = null;
  79693. if (this._meshesWithPoseMatrix.length > 0) {
  79694. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  79695. }
  79696. return poseMatrix;
  79697. };
  79698. /**
  79699. * Sorts bones per internal index
  79700. */
  79701. Skeleton.prototype.sortBones = function () {
  79702. var bones = new Array();
  79703. var visited = new Array(this.bones.length);
  79704. for (var index = 0; index < this.bones.length; index++) {
  79705. this._sortBones(index, bones, visited);
  79706. }
  79707. this.bones = bones;
  79708. };
  79709. Skeleton.prototype._sortBones = function (index, bones, visited) {
  79710. if (visited[index]) {
  79711. return;
  79712. }
  79713. visited[index] = true;
  79714. var bone = this.bones[index];
  79715. if (bone._index === undefined) {
  79716. bone._index = index;
  79717. }
  79718. var parentBone = bone.getParent();
  79719. if (parentBone) {
  79720. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  79721. }
  79722. bones.push(bone);
  79723. };
  79724. return Skeleton;
  79725. }());
  79726. BABYLON.Skeleton = Skeleton;
  79727. })(BABYLON || (BABYLON = {}));
  79728. //# sourceMappingURL=babylon.skeleton.js.map
  79729. var BABYLON;
  79730. (function (BABYLON) {
  79731. var SphericalPolynomial = /** @class */ (function () {
  79732. function SphericalPolynomial() {
  79733. this.x = BABYLON.Vector3.Zero();
  79734. this.y = BABYLON.Vector3.Zero();
  79735. this.z = BABYLON.Vector3.Zero();
  79736. this.xx = BABYLON.Vector3.Zero();
  79737. this.yy = BABYLON.Vector3.Zero();
  79738. this.zz = BABYLON.Vector3.Zero();
  79739. this.xy = BABYLON.Vector3.Zero();
  79740. this.yz = BABYLON.Vector3.Zero();
  79741. this.zx = BABYLON.Vector3.Zero();
  79742. }
  79743. SphericalPolynomial.prototype.addAmbient = function (color) {
  79744. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79745. this.xx = this.xx.add(colorVector);
  79746. this.yy = this.yy.add(colorVector);
  79747. this.zz = this.zz.add(colorVector);
  79748. };
  79749. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  79750. var result = new SphericalPolynomial();
  79751. result.x = harmonics.L11.scale(1.02333);
  79752. result.y = harmonics.L1_1.scale(1.02333);
  79753. result.z = harmonics.L10.scale(1.02333);
  79754. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  79755. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  79756. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  79757. result.yz = harmonics.L2_1.scale(0.858086);
  79758. result.zx = harmonics.L21.scale(0.858086);
  79759. result.xy = harmonics.L2_2.scale(0.858086);
  79760. result.scale(1.0 / Math.PI);
  79761. return result;
  79762. };
  79763. SphericalPolynomial.prototype.scale = function (scale) {
  79764. this.x = this.x.scale(scale);
  79765. this.y = this.y.scale(scale);
  79766. this.z = this.z.scale(scale);
  79767. this.xx = this.xx.scale(scale);
  79768. this.yy = this.yy.scale(scale);
  79769. this.zz = this.zz.scale(scale);
  79770. this.yz = this.yz.scale(scale);
  79771. this.zx = this.zx.scale(scale);
  79772. this.xy = this.xy.scale(scale);
  79773. };
  79774. return SphericalPolynomial;
  79775. }());
  79776. BABYLON.SphericalPolynomial = SphericalPolynomial;
  79777. var SphericalHarmonics = /** @class */ (function () {
  79778. function SphericalHarmonics() {
  79779. this.L00 = BABYLON.Vector3.Zero();
  79780. this.L1_1 = BABYLON.Vector3.Zero();
  79781. this.L10 = BABYLON.Vector3.Zero();
  79782. this.L11 = BABYLON.Vector3.Zero();
  79783. this.L2_2 = BABYLON.Vector3.Zero();
  79784. this.L2_1 = BABYLON.Vector3.Zero();
  79785. this.L20 = BABYLON.Vector3.Zero();
  79786. this.L21 = BABYLON.Vector3.Zero();
  79787. this.L22 = BABYLON.Vector3.Zero();
  79788. }
  79789. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  79790. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  79791. var c = colorVector.scale(deltaSolidAngle);
  79792. this.L00 = this.L00.add(c.scale(0.282095));
  79793. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  79794. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  79795. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  79796. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  79797. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  79798. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  79799. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  79800. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  79801. };
  79802. SphericalHarmonics.prototype.scale = function (scale) {
  79803. this.L00 = this.L00.scale(scale);
  79804. this.L1_1 = this.L1_1.scale(scale);
  79805. this.L10 = this.L10.scale(scale);
  79806. this.L11 = this.L11.scale(scale);
  79807. this.L2_2 = this.L2_2.scale(scale);
  79808. this.L2_1 = this.L2_1.scale(scale);
  79809. this.L20 = this.L20.scale(scale);
  79810. this.L21 = this.L21.scale(scale);
  79811. this.L22 = this.L22.scale(scale);
  79812. };
  79813. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  79814. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  79815. //
  79816. // E_lm = A_l * L_lm
  79817. //
  79818. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  79819. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  79820. // the scaling factors are given in equation 9.
  79821. // Constant (Band 0)
  79822. this.L00 = this.L00.scale(3.141593);
  79823. // Linear (Band 1)
  79824. this.L1_1 = this.L1_1.scale(2.094395);
  79825. this.L10 = this.L10.scale(2.094395);
  79826. this.L11 = this.L11.scale(2.094395);
  79827. // Quadratic (Band 2)
  79828. this.L2_2 = this.L2_2.scale(0.785398);
  79829. this.L2_1 = this.L2_1.scale(0.785398);
  79830. this.L20 = this.L20.scale(0.785398);
  79831. this.L21 = this.L21.scale(0.785398);
  79832. this.L22 = this.L22.scale(0.785398);
  79833. };
  79834. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  79835. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  79836. // L = (1/pi) * E * rho
  79837. //
  79838. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  79839. this.scale(1.0 / Math.PI);
  79840. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  79841. // (The pixel shader must apply albedo after texture fetches, etc).
  79842. };
  79843. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  79844. var result = new SphericalHarmonics();
  79845. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  79846. result.L1_1 = polynomial.y.scale(0.977204);
  79847. result.L10 = polynomial.z.scale(0.977204);
  79848. result.L11 = polynomial.x.scale(0.977204);
  79849. result.L2_2 = polynomial.xy.scale(1.16538);
  79850. result.L2_1 = polynomial.yz.scale(1.16538);
  79851. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  79852. result.L21 = polynomial.zx.scale(1.16538);
  79853. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  79854. result.scale(Math.PI);
  79855. return result;
  79856. };
  79857. return SphericalHarmonics;
  79858. }());
  79859. BABYLON.SphericalHarmonics = SphericalHarmonics;
  79860. })(BABYLON || (BABYLON = {}));
  79861. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  79862. var BABYLON;
  79863. (function (BABYLON) {
  79864. var FileFaceOrientation = /** @class */ (function () {
  79865. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  79866. this.name = name;
  79867. this.worldAxisForNormal = worldAxisForNormal;
  79868. this.worldAxisForFileX = worldAxisForFileX;
  79869. this.worldAxisForFileY = worldAxisForFileY;
  79870. }
  79871. return FileFaceOrientation;
  79872. }());
  79873. ;
  79874. /**
  79875. * Helper class dealing with the extraction of spherical polynomial dataArray
  79876. * from a cube map.
  79877. */
  79878. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  79879. function CubeMapToSphericalPolynomialTools() {
  79880. }
  79881. /**
  79882. * Converts a texture to the according Spherical Polynomial data.
  79883. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79884. *
  79885. * @param texture The texture to extract the information from.
  79886. * @return The Spherical Polynomial data.
  79887. */
  79888. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  79889. if (!texture.isCube) {
  79890. // Only supports cube Textures currently.
  79891. return null;
  79892. }
  79893. var size = texture.getSize().width;
  79894. var right = texture.readPixels(0);
  79895. var left = texture.readPixels(1);
  79896. var up;
  79897. var down;
  79898. if (texture.isRenderTarget) {
  79899. up = texture.readPixels(3);
  79900. down = texture.readPixels(2);
  79901. }
  79902. else {
  79903. up = texture.readPixels(2);
  79904. down = texture.readPixels(3);
  79905. }
  79906. var front = texture.readPixels(4);
  79907. var back = texture.readPixels(5);
  79908. var gammaSpace = texture.gammaSpace;
  79909. // Always read as RGBA.
  79910. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  79911. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  79912. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79913. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  79914. }
  79915. var cubeInfo = {
  79916. size: size,
  79917. right: right,
  79918. left: left,
  79919. up: up,
  79920. down: down,
  79921. front: front,
  79922. back: back,
  79923. format: format,
  79924. type: type,
  79925. gammaSpace: gammaSpace,
  79926. };
  79927. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  79928. };
  79929. /**
  79930. * Converts a cubemap to the according Spherical Polynomial data.
  79931. * This extracts the first 3 orders only as they are the only one used in the lighting.
  79932. *
  79933. * @param cubeInfo The Cube map to extract the information from.
  79934. * @return The Spherical Polynomial data.
  79935. */
  79936. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  79937. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  79938. var totalSolidAngle = 0.0;
  79939. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  79940. var du = 2.0 / cubeInfo.size;
  79941. var dv = du;
  79942. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  79943. var minUV = du * 0.5 - 1.0;
  79944. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  79945. var fileFace = this.FileFaces[faceIndex];
  79946. var dataArray = cubeInfo[fileFace.name];
  79947. var v = minUV;
  79948. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  79949. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  79950. // Because SP is still linear, so summation is fine in that basis.
  79951. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  79952. for (var y = 0; y < cubeInfo.size; y++) {
  79953. var u = minUV;
  79954. for (var x = 0; x < cubeInfo.size; x++) {
  79955. // World direction (not normalised)
  79956. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  79957. worldDirection.normalize();
  79958. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  79959. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  79960. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  79961. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  79962. // Handle Integer types.
  79963. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  79964. r /= 255;
  79965. g /= 255;
  79966. b /= 255;
  79967. }
  79968. // Handle Gamma space textures.
  79969. if (cubeInfo.gammaSpace) {
  79970. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  79971. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  79972. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  79973. }
  79974. var color = new BABYLON.Color3(r, g, b);
  79975. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  79976. totalSolidAngle += deltaSolidAngle;
  79977. u += du;
  79978. }
  79979. v += dv;
  79980. }
  79981. }
  79982. // Solid angle for entire sphere is 4*pi
  79983. var sphereSolidAngle = 4.0 * Math.PI;
  79984. // Adjust the solid angle to allow for how many faces we processed.
  79985. var facesProcessed = 6.0;
  79986. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  79987. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  79988. // This is needed because the numerical integration over the cube uses a
  79989. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  79990. // and also to compensate for accumulative error due to float precision in the summation.
  79991. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  79992. sphericalHarmonics.scale(correctionFactor);
  79993. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  79994. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  79995. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  79996. };
  79997. CubeMapToSphericalPolynomialTools.FileFaces = [
  79998. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  79999. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  80000. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  80001. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  80002. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  80003. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  80004. ];
  80005. return CubeMapToSphericalPolynomialTools;
  80006. }());
  80007. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  80008. })(BABYLON || (BABYLON = {}));
  80009. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  80010. var BABYLON;
  80011. (function (BABYLON) {
  80012. /**
  80013. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  80014. */
  80015. var PanoramaToCubeMapTools = /** @class */ (function () {
  80016. function PanoramaToCubeMapTools() {
  80017. }
  80018. /**
  80019. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  80020. *
  80021. * @param float32Array The source data.
  80022. * @param inputWidth The width of the input panorama.
  80023. * @param inputhHeight The height of the input panorama.
  80024. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  80025. * @return The cubemap data
  80026. */
  80027. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  80028. if (!float32Array) {
  80029. throw "ConvertPanoramaToCubemap: input cannot be null";
  80030. }
  80031. if (float32Array.length != inputWidth * inputHeight * 3) {
  80032. throw "ConvertPanoramaToCubemap: input size is wrong";
  80033. }
  80034. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  80035. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  80036. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  80037. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  80038. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  80039. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  80040. return {
  80041. front: textureFront,
  80042. back: textureBack,
  80043. left: textureLeft,
  80044. right: textureRight,
  80045. up: textureUp,
  80046. down: textureDown,
  80047. size: size,
  80048. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  80049. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  80050. gammaSpace: false,
  80051. };
  80052. };
  80053. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  80054. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  80055. var textureArray = new Float32Array(buffer);
  80056. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  80057. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  80058. var dy = 1 / texSize;
  80059. var fy = 0;
  80060. for (var y = 0; y < texSize; y++) {
  80061. var xv1 = faceData[0];
  80062. var xv2 = faceData[2];
  80063. for (var x = 0; x < texSize; x++) {
  80064. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  80065. v.normalize();
  80066. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  80067. // 3 channels per pixels
  80068. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  80069. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  80070. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  80071. xv1 = xv1.add(rotDX1);
  80072. xv2 = xv2.add(rotDX2);
  80073. }
  80074. fy += dy;
  80075. }
  80076. return textureArray;
  80077. };
  80078. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  80079. var theta = Math.atan2(vDir.z, vDir.x);
  80080. var phi = Math.acos(vDir.y);
  80081. while (theta < -Math.PI)
  80082. theta += 2 * Math.PI;
  80083. while (theta > Math.PI)
  80084. theta -= 2 * Math.PI;
  80085. var dx = theta / Math.PI;
  80086. var dy = phi / Math.PI;
  80087. // recenter.
  80088. dx = dx * 0.5 + 0.5;
  80089. var px = Math.round(dx * inputWidth);
  80090. if (px < 0)
  80091. px = 0;
  80092. else if (px >= inputWidth)
  80093. px = inputWidth - 1;
  80094. var py = Math.round(dy * inputHeight);
  80095. if (py < 0)
  80096. py = 0;
  80097. else if (py >= inputHeight)
  80098. py = inputHeight - 1;
  80099. var inputY = (inputHeight - py - 1);
  80100. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  80101. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  80102. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  80103. return {
  80104. r: r,
  80105. g: g,
  80106. b: b
  80107. };
  80108. };
  80109. PanoramaToCubeMapTools.FACE_FRONT = [
  80110. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80111. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80112. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80113. new BABYLON.Vector3(1.0, 1.0, -1.0)
  80114. ];
  80115. PanoramaToCubeMapTools.FACE_BACK = [
  80116. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80117. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80118. new BABYLON.Vector3(1.0, 1.0, 1.0),
  80119. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  80120. ];
  80121. PanoramaToCubeMapTools.FACE_RIGHT = [
  80122. new BABYLON.Vector3(1.0, -1.0, -1.0),
  80123. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80124. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80125. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80126. ];
  80127. PanoramaToCubeMapTools.FACE_LEFT = [
  80128. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80129. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80130. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80131. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  80132. ];
  80133. PanoramaToCubeMapTools.FACE_DOWN = [
  80134. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  80135. new BABYLON.Vector3(1.0, 1.0, -1.0),
  80136. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  80137. new BABYLON.Vector3(1.0, 1.0, 1.0)
  80138. ];
  80139. PanoramaToCubeMapTools.FACE_UP = [
  80140. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  80141. new BABYLON.Vector3(1.0, -1.0, 1.0),
  80142. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  80143. new BABYLON.Vector3(1.0, -1.0, -1.0)
  80144. ];
  80145. return PanoramaToCubeMapTools;
  80146. }());
  80147. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  80148. })(BABYLON || (BABYLON = {}));
  80149. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  80150. var BABYLON;
  80151. (function (BABYLON) {
  80152. ;
  80153. /**
  80154. * This groups tools to convert HDR texture to native colors array.
  80155. */
  80156. var HDRTools = /** @class */ (function () {
  80157. function HDRTools() {
  80158. }
  80159. HDRTools.Ldexp = function (mantissa, exponent) {
  80160. if (exponent > 1023) {
  80161. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  80162. }
  80163. if (exponent < -1074) {
  80164. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  80165. }
  80166. return mantissa * Math.pow(2, exponent);
  80167. };
  80168. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  80169. if (exponent > 0) { /*nonzero pixel*/
  80170. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  80171. float32array[index + 0] = red * exponent;
  80172. float32array[index + 1] = green * exponent;
  80173. float32array[index + 2] = blue * exponent;
  80174. }
  80175. else {
  80176. float32array[index + 0] = 0;
  80177. float32array[index + 1] = 0;
  80178. float32array[index + 2] = 0;
  80179. }
  80180. };
  80181. HDRTools.readStringLine = function (uint8array, startIndex) {
  80182. var line = "";
  80183. var character = "";
  80184. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  80185. character = String.fromCharCode(uint8array[i]);
  80186. if (character == "\n") {
  80187. break;
  80188. }
  80189. line += character;
  80190. }
  80191. return line;
  80192. };
  80193. /**
  80194. * Reads header information from an RGBE texture stored in a native array.
  80195. * More information on this format are available here:
  80196. * https://en.wikipedia.org/wiki/RGBE_image_format
  80197. *
  80198. * @param uint8array The binary file stored in native array.
  80199. * @return The header information.
  80200. */
  80201. HDRTools.RGBE_ReadHeader = function (uint8array) {
  80202. var height = 0;
  80203. var width = 0;
  80204. var line = this.readStringLine(uint8array, 0);
  80205. if (line[0] != '#' || line[1] != '?') {
  80206. throw "Bad HDR Format.";
  80207. }
  80208. var endOfHeader = false;
  80209. var findFormat = false;
  80210. var lineIndex = 0;
  80211. do {
  80212. lineIndex += (line.length + 1);
  80213. line = this.readStringLine(uint8array, lineIndex);
  80214. if (line == "FORMAT=32-bit_rle_rgbe") {
  80215. findFormat = true;
  80216. }
  80217. else if (line.length == 0) {
  80218. endOfHeader = true;
  80219. }
  80220. } while (!endOfHeader);
  80221. if (!findFormat) {
  80222. throw "HDR Bad header format, unsupported FORMAT";
  80223. }
  80224. lineIndex += (line.length + 1);
  80225. line = this.readStringLine(uint8array, lineIndex);
  80226. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  80227. var match = sizeRegexp.exec(line);
  80228. // TODO. Support +Y and -X if needed.
  80229. if (!match || match.length < 3) {
  80230. throw "HDR Bad header format, no size";
  80231. }
  80232. width = parseInt(match[2]);
  80233. height = parseInt(match[1]);
  80234. if (width < 8 || width > 0x7fff) {
  80235. throw "HDR Bad header format, unsupported size";
  80236. }
  80237. lineIndex += (line.length + 1);
  80238. return {
  80239. height: height,
  80240. width: width,
  80241. dataPosition: lineIndex
  80242. };
  80243. };
  80244. /**
  80245. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  80246. * This RGBE texture needs to store the information as a panorama.
  80247. *
  80248. * More information on this format are available here:
  80249. * https://en.wikipedia.org/wiki/RGBE_image_format
  80250. *
  80251. * @param buffer The binary file stored in an array buffer.
  80252. * @param size The expected size of the extracted cubemap.
  80253. * @return The Cube Map information.
  80254. */
  80255. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  80256. var uint8array = new Uint8Array(buffer);
  80257. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  80258. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80259. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  80260. return cubeMapData;
  80261. };
  80262. /**
  80263. * Returns the pixels data extracted from an RGBE texture.
  80264. * This pixels will be stored left to right up to down in the R G B order in one array.
  80265. *
  80266. * More information on this format are available here:
  80267. * https://en.wikipedia.org/wiki/RGBE_image_format
  80268. *
  80269. * @param uint8array The binary file stored in an array buffer.
  80270. * @param hdrInfo The header information of the file.
  80271. * @return The pixels data in RGB right to left up to down order.
  80272. */
  80273. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  80274. // Keep for multi format supports.
  80275. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  80276. };
  80277. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  80278. var num_scanlines = hdrInfo.height;
  80279. var scanline_width = hdrInfo.width;
  80280. var a, b, c, d, count;
  80281. var dataIndex = hdrInfo.dataPosition;
  80282. var index = 0, endIndex = 0, i = 0;
  80283. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  80284. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  80285. // 3 channels of 4 bytes per pixel in float.
  80286. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  80287. var resultArray = new Float32Array(resultBuffer);
  80288. // read in each successive scanline
  80289. while (num_scanlines > 0) {
  80290. a = uint8array[dataIndex++];
  80291. b = uint8array[dataIndex++];
  80292. c = uint8array[dataIndex++];
  80293. d = uint8array[dataIndex++];
  80294. if (a != 2 || b != 2 || (c & 0x80)) {
  80295. // this file is not run length encoded
  80296. throw "HDR Bad header format, not RLE";
  80297. }
  80298. if (((c << 8) | d) != scanline_width) {
  80299. throw "HDR Bad header format, wrong scan line width";
  80300. }
  80301. index = 0;
  80302. // read each of the four channels for the scanline into the buffer
  80303. for (i = 0; i < 4; i++) {
  80304. endIndex = (i + 1) * scanline_width;
  80305. while (index < endIndex) {
  80306. a = uint8array[dataIndex++];
  80307. b = uint8array[dataIndex++];
  80308. if (a > 128) {
  80309. // a run of the same value
  80310. count = a - 128;
  80311. if ((count == 0) || (count > endIndex - index)) {
  80312. throw "HDR Bad Format, bad scanline data (run)";
  80313. }
  80314. while (count-- > 0) {
  80315. scanLineArray[index++] = b;
  80316. }
  80317. }
  80318. else {
  80319. // a non-run
  80320. count = a;
  80321. if ((count == 0) || (count > endIndex - index)) {
  80322. throw "HDR Bad Format, bad scanline data (non-run)";
  80323. }
  80324. scanLineArray[index++] = b;
  80325. if (--count > 0) {
  80326. for (var j = 0; j < count; j++) {
  80327. scanLineArray[index++] = uint8array[dataIndex++];
  80328. }
  80329. }
  80330. }
  80331. }
  80332. }
  80333. // now convert data from buffer into floats
  80334. for (i = 0; i < scanline_width; i++) {
  80335. a = scanLineArray[i];
  80336. b = scanLineArray[i + scanline_width];
  80337. c = scanLineArray[i + 2 * scanline_width];
  80338. d = scanLineArray[i + 3 * scanline_width];
  80339. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  80340. }
  80341. num_scanlines--;
  80342. }
  80343. return resultArray;
  80344. };
  80345. return HDRTools;
  80346. }());
  80347. BABYLON.HDRTools = HDRTools;
  80348. })(BABYLON || (BABYLON = {}));
  80349. //# sourceMappingURL=babylon.hdr.js.map
  80350. var BABYLON;
  80351. (function (BABYLON) {
  80352. /**
  80353. * This represents a texture coming from an HDR input.
  80354. *
  80355. * The only supported format is currently panorama picture stored in RGBE format.
  80356. * Example of such files can be found on HDRLib: http://hdrlib.com/
  80357. */
  80358. var HDRCubeTexture = /** @class */ (function (_super) {
  80359. __extends(HDRCubeTexture, _super);
  80360. /**
  80361. * Instantiates an HDRTexture from the following parameters.
  80362. *
  80363. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  80364. * @param scene The scene the texture will be used in
  80365. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  80366. * @param noMipmap Forces to not generate the mipmap if true
  80367. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  80368. * @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)
  80369. * @param reserved Reserved flag for internal use.
  80370. */
  80371. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  80372. if (noMipmap === void 0) { noMipmap = false; }
  80373. if (generateHarmonics === void 0) { generateHarmonics = true; }
  80374. if (gammaSpace === void 0) { gammaSpace = false; }
  80375. if (reserved === void 0) { reserved = false; }
  80376. if (onLoad === void 0) { onLoad = null; }
  80377. if (onError === void 0) { onError = null; }
  80378. var _this = _super.call(this, scene) || this;
  80379. _this._generateHarmonics = true;
  80380. _this._onLoad = null;
  80381. _this._onError = null;
  80382. /**
  80383. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  80384. */
  80385. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  80386. _this._isBlocking = true;
  80387. _this._rotationY = 0;
  80388. /**
  80389. * Gets or sets the center of the bounding box associated with the cube texture
  80390. * It must define where the camera used to render the texture was set
  80391. */
  80392. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  80393. if (!url) {
  80394. return _this;
  80395. }
  80396. _this.name = url;
  80397. _this.url = url;
  80398. _this.hasAlpha = false;
  80399. _this.isCube = true;
  80400. _this._textureMatrix = BABYLON.Matrix.Identity();
  80401. _this._onLoad = onLoad;
  80402. _this._onError = onError;
  80403. _this.gammaSpace = gammaSpace;
  80404. _this._noMipmap = noMipmap;
  80405. _this._size = size;
  80406. _this._texture = _this._getFromCache(url, _this._noMipmap);
  80407. if (!_this._texture) {
  80408. if (!scene.useDelayedTextureLoading) {
  80409. _this.loadTexture();
  80410. }
  80411. else {
  80412. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  80413. }
  80414. }
  80415. return _this;
  80416. }
  80417. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  80418. /**
  80419. * Gets wether or not the texture is blocking during loading.
  80420. */
  80421. get: function () {
  80422. return this._isBlocking;
  80423. },
  80424. /**
  80425. * Sets wether or not the texture is blocking during loading.
  80426. */
  80427. set: function (value) {
  80428. this._isBlocking = value;
  80429. },
  80430. enumerable: true,
  80431. configurable: true
  80432. });
  80433. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  80434. /**
  80435. * Gets texture matrix rotation angle around Y axis radians.
  80436. */
  80437. get: function () {
  80438. return this._rotationY;
  80439. },
  80440. /**
  80441. * Sets texture matrix rotation angle around Y axis in radians.
  80442. */
  80443. set: function (value) {
  80444. this._rotationY = value;
  80445. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  80446. },
  80447. enumerable: true,
  80448. configurable: true
  80449. });
  80450. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  80451. get: function () {
  80452. return this._boundingBoxSize;
  80453. },
  80454. /**
  80455. * Gets or sets the size of the bounding box associated with the cube texture
  80456. * When defined, the cubemap will switch to local mode
  80457. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  80458. * @example https://www.babylonjs-playground.com/#RNASML
  80459. */
  80460. set: function (value) {
  80461. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  80462. return;
  80463. }
  80464. this._boundingBoxSize = value;
  80465. var scene = this.getScene();
  80466. if (scene) {
  80467. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  80468. }
  80469. },
  80470. enumerable: true,
  80471. configurable: true
  80472. });
  80473. /**
  80474. * Occurs when the file is raw .hdr file.
  80475. */
  80476. HDRCubeTexture.prototype.loadTexture = function () {
  80477. var _this = this;
  80478. var callback = function (buffer) {
  80479. var scene = _this.getScene();
  80480. if (!scene) {
  80481. return null;
  80482. }
  80483. // Extract the raw linear data.
  80484. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  80485. // Generate harmonics if needed.
  80486. if (_this._generateHarmonics) {
  80487. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  80488. _this.sphericalPolynomial = sphericalPolynomial;
  80489. }
  80490. var results = [];
  80491. var byteArray = null;
  80492. // Push each faces.
  80493. for (var j = 0; j < 6; j++) {
  80494. // Create uintarray fallback.
  80495. if (!scene.getEngine().getCaps().textureFloat) {
  80496. // 3 channels of 1 bytes per pixel in bytes.
  80497. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  80498. byteArray = new Uint8Array(byteBuffer);
  80499. }
  80500. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  80501. // If special cases.
  80502. if (_this.gammaSpace || byteArray) {
  80503. for (var i = 0; i < _this._size * _this._size; i++) {
  80504. // Put in gamma space if requested.
  80505. if (_this.gammaSpace) {
  80506. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  80507. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  80508. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  80509. }
  80510. // Convert to int texture for fallback.
  80511. if (byteArray) {
  80512. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  80513. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  80514. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  80515. // May use luminance instead if the result is not accurate.
  80516. var max = Math.max(Math.max(r, g), b);
  80517. if (max > 255) {
  80518. var scale = 255 / max;
  80519. r *= scale;
  80520. g *= scale;
  80521. b *= scale;
  80522. }
  80523. byteArray[(i * 3) + 0] = r;
  80524. byteArray[(i * 3) + 1] = g;
  80525. byteArray[(i * 3) + 2] = b;
  80526. }
  80527. }
  80528. }
  80529. if (byteArray) {
  80530. results.push(byteArray);
  80531. }
  80532. else {
  80533. results.push(dataFace);
  80534. }
  80535. }
  80536. return results;
  80537. };
  80538. var scene = this.getScene();
  80539. if (scene) {
  80540. 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);
  80541. }
  80542. };
  80543. HDRCubeTexture.prototype.clone = function () {
  80544. var scene = this.getScene();
  80545. if (!scene) {
  80546. return this;
  80547. }
  80548. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  80549. // Base texture
  80550. newTexture.level = this.level;
  80551. newTexture.wrapU = this.wrapU;
  80552. newTexture.wrapV = this.wrapV;
  80553. newTexture.coordinatesIndex = this.coordinatesIndex;
  80554. newTexture.coordinatesMode = this.coordinatesMode;
  80555. return newTexture;
  80556. };
  80557. // Methods
  80558. HDRCubeTexture.prototype.delayLoad = function () {
  80559. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  80560. return;
  80561. }
  80562. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  80563. this._texture = this._getFromCache(this.url, this._noMipmap);
  80564. if (!this._texture) {
  80565. this.loadTexture();
  80566. }
  80567. };
  80568. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  80569. return this._textureMatrix;
  80570. };
  80571. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  80572. this._textureMatrix = value;
  80573. };
  80574. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  80575. var texture = null;
  80576. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  80577. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  80578. texture.name = parsedTexture.name;
  80579. texture.hasAlpha = parsedTexture.hasAlpha;
  80580. texture.level = parsedTexture.level;
  80581. texture.coordinatesMode = parsedTexture.coordinatesMode;
  80582. texture.isBlocking = parsedTexture.isBlocking;
  80583. }
  80584. if (texture) {
  80585. if (parsedTexture.boundingBoxPosition) {
  80586. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  80587. }
  80588. if (parsedTexture.boundingBoxSize) {
  80589. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  80590. }
  80591. if (parsedTexture.rotationY) {
  80592. texture.rotationY = parsedTexture.rotationY;
  80593. }
  80594. }
  80595. return texture;
  80596. };
  80597. HDRCubeTexture.prototype.serialize = function () {
  80598. if (!this.name) {
  80599. return null;
  80600. }
  80601. var serializationObject = {};
  80602. serializationObject.name = this.name;
  80603. serializationObject.hasAlpha = this.hasAlpha;
  80604. serializationObject.isCube = true;
  80605. serializationObject.level = this.level;
  80606. serializationObject.size = this._size;
  80607. serializationObject.coordinatesMode = this.coordinatesMode;
  80608. serializationObject.useInGammaSpace = this.gammaSpace;
  80609. serializationObject.generateHarmonics = this._generateHarmonics;
  80610. serializationObject.customType = "BABYLON.HDRCubeTexture";
  80611. serializationObject.noMipmap = this._noMipmap;
  80612. serializationObject.isBlocking = this._isBlocking;
  80613. serializationObject.rotationY = this._rotationY;
  80614. return serializationObject;
  80615. };
  80616. HDRCubeTexture._facesMapping = [
  80617. "right",
  80618. "left",
  80619. "up",
  80620. "down",
  80621. "front",
  80622. "back"
  80623. ];
  80624. return HDRCubeTexture;
  80625. }(BABYLON.BaseTexture));
  80626. BABYLON.HDRCubeTexture = HDRCubeTexture;
  80627. })(BABYLON || (BABYLON = {}));
  80628. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  80629. var BABYLON;
  80630. (function (BABYLON) {
  80631. var IndexedVector2 = /** @class */ (function (_super) {
  80632. __extends(IndexedVector2, _super);
  80633. function IndexedVector2(original, index) {
  80634. var _this = _super.call(this, original.x, original.y) || this;
  80635. _this.index = index;
  80636. return _this;
  80637. }
  80638. return IndexedVector2;
  80639. }(BABYLON.Vector2));
  80640. var PolygonPoints = /** @class */ (function () {
  80641. function PolygonPoints() {
  80642. this.elements = new Array();
  80643. }
  80644. PolygonPoints.prototype.add = function (originalPoints) {
  80645. var _this = this;
  80646. var result = new Array();
  80647. originalPoints.forEach(function (point) {
  80648. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  80649. var newPoint = new IndexedVector2(point, _this.elements.length);
  80650. result.push(newPoint);
  80651. _this.elements.push(newPoint);
  80652. }
  80653. });
  80654. return result;
  80655. };
  80656. PolygonPoints.prototype.computeBounds = function () {
  80657. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80658. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  80659. this.elements.forEach(function (point) {
  80660. // x
  80661. if (point.x < lmin.x) {
  80662. lmin.x = point.x;
  80663. }
  80664. else if (point.x > lmax.x) {
  80665. lmax.x = point.x;
  80666. }
  80667. // y
  80668. if (point.y < lmin.y) {
  80669. lmin.y = point.y;
  80670. }
  80671. else if (point.y > lmax.y) {
  80672. lmax.y = point.y;
  80673. }
  80674. });
  80675. return {
  80676. min: lmin,
  80677. max: lmax,
  80678. width: lmax.x - lmin.x,
  80679. height: lmax.y - lmin.y
  80680. };
  80681. };
  80682. return PolygonPoints;
  80683. }());
  80684. var Polygon = /** @class */ (function () {
  80685. function Polygon() {
  80686. }
  80687. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  80688. return [
  80689. new BABYLON.Vector2(xmin, ymin),
  80690. new BABYLON.Vector2(xmax, ymin),
  80691. new BABYLON.Vector2(xmax, ymax),
  80692. new BABYLON.Vector2(xmin, ymax)
  80693. ];
  80694. };
  80695. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  80696. if (cx === void 0) { cx = 0; }
  80697. if (cy === void 0) { cy = 0; }
  80698. if (numberOfSides === void 0) { numberOfSides = 32; }
  80699. var result = new Array();
  80700. var angle = 0;
  80701. var increment = (Math.PI * 2) / numberOfSides;
  80702. for (var i = 0; i < numberOfSides; i++) {
  80703. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  80704. angle -= increment;
  80705. }
  80706. return result;
  80707. };
  80708. Polygon.Parse = function (input) {
  80709. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  80710. var i, result = [];
  80711. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  80712. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  80713. }
  80714. return result;
  80715. };
  80716. Polygon.StartingAt = function (x, y) {
  80717. return BABYLON.Path2.StartingAt(x, y);
  80718. };
  80719. return Polygon;
  80720. }());
  80721. BABYLON.Polygon = Polygon;
  80722. var PolygonMeshBuilder = /** @class */ (function () {
  80723. function PolygonMeshBuilder(name, contours, scene) {
  80724. this._points = new PolygonPoints();
  80725. this._outlinepoints = new PolygonPoints();
  80726. this._holes = new Array();
  80727. this._epoints = new Array();
  80728. this._eholes = new Array();
  80729. this._name = name;
  80730. this._scene = scene;
  80731. var points;
  80732. if (contours instanceof BABYLON.Path2) {
  80733. points = contours.getPoints();
  80734. }
  80735. else {
  80736. points = contours;
  80737. }
  80738. this._addToepoint(points);
  80739. this._points.add(points);
  80740. this._outlinepoints.add(points);
  80741. if (typeof earcut === 'undefined') {
  80742. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  80743. }
  80744. }
  80745. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  80746. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  80747. var p = points_1[_i];
  80748. this._epoints.push(p.x, p.y);
  80749. }
  80750. };
  80751. PolygonMeshBuilder.prototype.addHole = function (hole) {
  80752. this._points.add(hole);
  80753. var holepoints = new PolygonPoints();
  80754. holepoints.add(hole);
  80755. this._holes.push(holepoints);
  80756. this._eholes.push(this._epoints.length / 2);
  80757. this._addToepoint(hole);
  80758. return this;
  80759. };
  80760. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  80761. var _this = this;
  80762. if (updatable === void 0) { updatable = false; }
  80763. if (depth === void 0) { depth = 0; }
  80764. var result = new BABYLON.Mesh(this._name, this._scene);
  80765. var normals = new Array();
  80766. var positions = new Array();
  80767. var uvs = new Array();
  80768. var bounds = this._points.computeBounds();
  80769. this._points.elements.forEach(function (p) {
  80770. normals.push(0, 1.0, 0);
  80771. positions.push(p.x, 0, p.y);
  80772. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  80773. });
  80774. var indices = new Array();
  80775. var res = earcut(this._epoints, this._eholes, 2);
  80776. for (var i = 0; i < res.length; i++) {
  80777. indices.push(res[i]);
  80778. }
  80779. if (depth > 0) {
  80780. var positionscount = (positions.length / 3); //get the current pointcount
  80781. this._points.elements.forEach(function (p) {
  80782. normals.push(0, -1.0, 0);
  80783. positions.push(p.x, -depth, p.y);
  80784. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  80785. });
  80786. var totalCount = indices.length;
  80787. for (var i = 0; i < totalCount; i += 3) {
  80788. var i0 = indices[i + 0];
  80789. var i1 = indices[i + 1];
  80790. var i2 = indices[i + 2];
  80791. indices.push(i2 + positionscount);
  80792. indices.push(i1 + positionscount);
  80793. indices.push(i0 + positionscount);
  80794. }
  80795. //Add the sides
  80796. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  80797. this._holes.forEach(function (hole) {
  80798. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  80799. });
  80800. }
  80801. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  80802. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  80803. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  80804. result.setIndices(indices);
  80805. return result;
  80806. };
  80807. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  80808. var StartIndex = positions.length / 3;
  80809. var ulength = 0;
  80810. for (var i = 0; i < points.elements.length; i++) {
  80811. var p = points.elements[i];
  80812. var p1;
  80813. if ((i + 1) > points.elements.length - 1) {
  80814. p1 = points.elements[0];
  80815. }
  80816. else {
  80817. p1 = points.elements[i + 1];
  80818. }
  80819. positions.push(p.x, 0, p.y);
  80820. positions.push(p.x, -depth, p.y);
  80821. positions.push(p1.x, 0, p1.y);
  80822. positions.push(p1.x, -depth, p1.y);
  80823. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  80824. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  80825. var v3 = v2.subtract(v1);
  80826. var v4 = new BABYLON.Vector3(0, 1, 0);
  80827. var vn = BABYLON.Vector3.Cross(v3, v4);
  80828. vn = vn.normalize();
  80829. uvs.push(ulength / bounds.width, 0);
  80830. uvs.push(ulength / bounds.width, 1);
  80831. ulength += v3.length();
  80832. uvs.push((ulength / bounds.width), 0);
  80833. uvs.push((ulength / bounds.width), 1);
  80834. if (!flip) {
  80835. normals.push(-vn.x, -vn.y, -vn.z);
  80836. normals.push(-vn.x, -vn.y, -vn.z);
  80837. normals.push(-vn.x, -vn.y, -vn.z);
  80838. normals.push(-vn.x, -vn.y, -vn.z);
  80839. indices.push(StartIndex);
  80840. indices.push(StartIndex + 1);
  80841. indices.push(StartIndex + 2);
  80842. indices.push(StartIndex + 1);
  80843. indices.push(StartIndex + 3);
  80844. indices.push(StartIndex + 2);
  80845. }
  80846. else {
  80847. normals.push(vn.x, vn.y, vn.z);
  80848. normals.push(vn.x, vn.y, vn.z);
  80849. normals.push(vn.x, vn.y, vn.z);
  80850. normals.push(vn.x, vn.y, vn.z);
  80851. indices.push(StartIndex);
  80852. indices.push(StartIndex + 2);
  80853. indices.push(StartIndex + 1);
  80854. indices.push(StartIndex + 1);
  80855. indices.push(StartIndex + 2);
  80856. indices.push(StartIndex + 3);
  80857. }
  80858. StartIndex += 4;
  80859. }
  80860. ;
  80861. };
  80862. return PolygonMeshBuilder;
  80863. }());
  80864. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  80865. })(BABYLON || (BABYLON = {}));
  80866. //# sourceMappingURL=babylon.polygonMesh.js.map
  80867. var BABYLON;
  80868. (function (BABYLON) {
  80869. // Unique ID when we import meshes from Babylon to CSG
  80870. var currentCSGMeshId = 0;
  80871. // # class Vertex
  80872. // Represents a vertex of a polygon. Use your own vertex class instead of this
  80873. // one to provide additional features like texture coordinates and vertex
  80874. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  80875. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  80876. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  80877. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  80878. // is not used anywhere else.
  80879. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  80880. var Vertex = /** @class */ (function () {
  80881. function Vertex(pos, normal, uv) {
  80882. this.pos = pos;
  80883. this.normal = normal;
  80884. this.uv = uv;
  80885. }
  80886. Vertex.prototype.clone = function () {
  80887. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  80888. };
  80889. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  80890. // orientation of a polygon is flipped.
  80891. Vertex.prototype.flip = function () {
  80892. this.normal = this.normal.scale(-1);
  80893. };
  80894. // Create a new vertex between this vertex and `other` by linearly
  80895. // interpolating all properties using a parameter of `t`. Subclasses should
  80896. // override this to interpolate additional properties.
  80897. Vertex.prototype.interpolate = function (other, t) {
  80898. 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));
  80899. };
  80900. return Vertex;
  80901. }());
  80902. // # class Plane
  80903. // Represents a plane in 3D space.
  80904. var Plane = /** @class */ (function () {
  80905. function Plane(normal, w) {
  80906. this.normal = normal;
  80907. this.w = w;
  80908. }
  80909. Plane.FromPoints = function (a, b, c) {
  80910. var v0 = c.subtract(a);
  80911. var v1 = b.subtract(a);
  80912. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  80913. return null;
  80914. }
  80915. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  80916. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  80917. };
  80918. Plane.prototype.clone = function () {
  80919. return new Plane(this.normal.clone(), this.w);
  80920. };
  80921. Plane.prototype.flip = function () {
  80922. this.normal.scaleInPlace(-1);
  80923. this.w = -this.w;
  80924. };
  80925. // Split `polygon` by this plane if needed, then put the polygon or polygon
  80926. // fragments in the appropriate lists. Coplanar polygons go into either
  80927. // `coplanarFront` or `coplanarBack` depending on their orientation with
  80928. // respect to this plane. Polygons in front or in back of this plane go into
  80929. // either `front` or `back`.
  80930. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  80931. var COPLANAR = 0;
  80932. var FRONT = 1;
  80933. var BACK = 2;
  80934. var SPANNING = 3;
  80935. // Classify each point as well as the entire polygon into one of the above
  80936. // four classes.
  80937. var polygonType = 0;
  80938. var types = [];
  80939. var i;
  80940. var t;
  80941. for (i = 0; i < polygon.vertices.length; i++) {
  80942. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  80943. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  80944. polygonType |= type;
  80945. types.push(type);
  80946. }
  80947. // Put the polygon in the correct list, splitting it when necessary.
  80948. switch (polygonType) {
  80949. case COPLANAR:
  80950. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  80951. break;
  80952. case FRONT:
  80953. front.push(polygon);
  80954. break;
  80955. case BACK:
  80956. back.push(polygon);
  80957. break;
  80958. case SPANNING:
  80959. var f = [], b = [];
  80960. for (i = 0; i < polygon.vertices.length; i++) {
  80961. var j = (i + 1) % polygon.vertices.length;
  80962. var ti = types[i], tj = types[j];
  80963. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  80964. if (ti !== BACK)
  80965. f.push(vi);
  80966. if (ti !== FRONT)
  80967. b.push(ti !== BACK ? vi.clone() : vi);
  80968. if ((ti | tj) === SPANNING) {
  80969. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  80970. var v = vi.interpolate(vj, t);
  80971. f.push(v);
  80972. b.push(v.clone());
  80973. }
  80974. }
  80975. var poly;
  80976. if (f.length >= 3) {
  80977. poly = new Polygon(f, polygon.shared);
  80978. if (poly.plane)
  80979. front.push(poly);
  80980. }
  80981. if (b.length >= 3) {
  80982. poly = new Polygon(b, polygon.shared);
  80983. if (poly.plane)
  80984. back.push(poly);
  80985. }
  80986. break;
  80987. }
  80988. };
  80989. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  80990. // point is on the plane.
  80991. Plane.EPSILON = 1e-5;
  80992. return Plane;
  80993. }());
  80994. // # class Polygon
  80995. // Represents a convex polygon. The vertices used to initialize a polygon must
  80996. // be coplanar and form a convex loop.
  80997. //
  80998. // Each convex polygon has a `shared` property, which is shared between all
  80999. // polygons that are clones of each other or were split from the same polygon.
  81000. // This can be used to define per-polygon properties (such as surface color).
  81001. var Polygon = /** @class */ (function () {
  81002. function Polygon(vertices, shared) {
  81003. this.vertices = vertices;
  81004. this.shared = shared;
  81005. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  81006. }
  81007. Polygon.prototype.clone = function () {
  81008. var vertices = this.vertices.map(function (v) { return v.clone(); });
  81009. return new Polygon(vertices, this.shared);
  81010. };
  81011. Polygon.prototype.flip = function () {
  81012. this.vertices.reverse().map(function (v) { v.flip(); });
  81013. this.plane.flip();
  81014. };
  81015. return Polygon;
  81016. }());
  81017. // # class Node
  81018. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  81019. // by picking a polygon to split along. That polygon (and all other coplanar
  81020. // polygons) are added directly to that node and the other polygons are added to
  81021. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  81022. // no distinction between internal and leaf nodes.
  81023. var Node = /** @class */ (function () {
  81024. function Node(polygons) {
  81025. this.plane = null;
  81026. this.front = null;
  81027. this.back = null;
  81028. this.polygons = new Array();
  81029. if (polygons) {
  81030. this.build(polygons);
  81031. }
  81032. }
  81033. Node.prototype.clone = function () {
  81034. var node = new Node();
  81035. node.plane = this.plane && this.plane.clone();
  81036. node.front = this.front && this.front.clone();
  81037. node.back = this.back && this.back.clone();
  81038. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  81039. return node;
  81040. };
  81041. // Convert solid space to empty space and empty space to solid space.
  81042. Node.prototype.invert = function () {
  81043. for (var i = 0; i < this.polygons.length; i++) {
  81044. this.polygons[i].flip();
  81045. }
  81046. if (this.plane) {
  81047. this.plane.flip();
  81048. }
  81049. if (this.front) {
  81050. this.front.invert();
  81051. }
  81052. if (this.back) {
  81053. this.back.invert();
  81054. }
  81055. var temp = this.front;
  81056. this.front = this.back;
  81057. this.back = temp;
  81058. };
  81059. // Recursively remove all polygons in `polygons` that are inside this BSP
  81060. // tree.
  81061. Node.prototype.clipPolygons = function (polygons) {
  81062. if (!this.plane)
  81063. return polygons.slice();
  81064. var front = new Array(), back = new Array();
  81065. for (var i = 0; i < polygons.length; i++) {
  81066. this.plane.splitPolygon(polygons[i], front, back, front, back);
  81067. }
  81068. if (this.front) {
  81069. front = this.front.clipPolygons(front);
  81070. }
  81071. if (this.back) {
  81072. back = this.back.clipPolygons(back);
  81073. }
  81074. else {
  81075. back = [];
  81076. }
  81077. return front.concat(back);
  81078. };
  81079. // Remove all polygons in this BSP tree that are inside the other BSP tree
  81080. // `bsp`.
  81081. Node.prototype.clipTo = function (bsp) {
  81082. this.polygons = bsp.clipPolygons(this.polygons);
  81083. if (this.front)
  81084. this.front.clipTo(bsp);
  81085. if (this.back)
  81086. this.back.clipTo(bsp);
  81087. };
  81088. // Return a list of all polygons in this BSP tree.
  81089. Node.prototype.allPolygons = function () {
  81090. var polygons = this.polygons.slice();
  81091. if (this.front)
  81092. polygons = polygons.concat(this.front.allPolygons());
  81093. if (this.back)
  81094. polygons = polygons.concat(this.back.allPolygons());
  81095. return polygons;
  81096. };
  81097. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  81098. // new polygons are filtered down to the bottom of the tree and become new
  81099. // nodes there. Each set of polygons is partitioned using the first polygon
  81100. // (no heuristic is used to pick a good split).
  81101. Node.prototype.build = function (polygons) {
  81102. if (!polygons.length)
  81103. return;
  81104. if (!this.plane)
  81105. this.plane = polygons[0].plane.clone();
  81106. var front = new Array(), back = new Array();
  81107. for (var i = 0; i < polygons.length; i++) {
  81108. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  81109. }
  81110. if (front.length) {
  81111. if (!this.front)
  81112. this.front = new Node();
  81113. this.front.build(front);
  81114. }
  81115. if (back.length) {
  81116. if (!this.back)
  81117. this.back = new Node();
  81118. this.back.build(back);
  81119. }
  81120. };
  81121. return Node;
  81122. }());
  81123. var CSG = /** @class */ (function () {
  81124. function CSG() {
  81125. this.polygons = new Array();
  81126. }
  81127. // Convert BABYLON.Mesh to BABYLON.CSG
  81128. CSG.FromMesh = function (mesh) {
  81129. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  81130. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  81131. if (mesh instanceof BABYLON.Mesh) {
  81132. mesh.computeWorldMatrix(true);
  81133. matrix = mesh.getWorldMatrix();
  81134. meshPosition = mesh.position.clone();
  81135. meshRotation = mesh.rotation.clone();
  81136. if (mesh.rotationQuaternion) {
  81137. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  81138. }
  81139. meshScaling = mesh.scaling.clone();
  81140. }
  81141. else {
  81142. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  81143. }
  81144. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  81145. var subMeshes = mesh.subMeshes;
  81146. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  81147. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  81148. vertices = [];
  81149. for (var j = 0; j < 3; j++) {
  81150. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  81151. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  81152. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  81153. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  81154. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  81155. vertex = new Vertex(position, normal, uv);
  81156. vertices.push(vertex);
  81157. }
  81158. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  81159. // To handle the case of degenerated triangle
  81160. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  81161. if (polygon.plane)
  81162. polygons.push(polygon);
  81163. }
  81164. }
  81165. var csg = CSG.FromPolygons(polygons);
  81166. csg.matrix = matrix;
  81167. csg.position = meshPosition;
  81168. csg.rotation = meshRotation;
  81169. csg.scaling = meshScaling;
  81170. csg.rotationQuaternion = meshRotationQuaternion;
  81171. currentCSGMeshId++;
  81172. return csg;
  81173. };
  81174. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  81175. CSG.FromPolygons = function (polygons) {
  81176. var csg = new CSG();
  81177. csg.polygons = polygons;
  81178. return csg;
  81179. };
  81180. CSG.prototype.clone = function () {
  81181. var csg = new CSG();
  81182. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  81183. csg.copyTransformAttributes(this);
  81184. return csg;
  81185. };
  81186. CSG.prototype.union = function (csg) {
  81187. var a = new Node(this.clone().polygons);
  81188. var b = new Node(csg.clone().polygons);
  81189. a.clipTo(b);
  81190. b.clipTo(a);
  81191. b.invert();
  81192. b.clipTo(a);
  81193. b.invert();
  81194. a.build(b.allPolygons());
  81195. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81196. };
  81197. CSG.prototype.unionInPlace = function (csg) {
  81198. var a = new Node(this.polygons);
  81199. var b = new Node(csg.polygons);
  81200. a.clipTo(b);
  81201. b.clipTo(a);
  81202. b.invert();
  81203. b.clipTo(a);
  81204. b.invert();
  81205. a.build(b.allPolygons());
  81206. this.polygons = a.allPolygons();
  81207. };
  81208. CSG.prototype.subtract = function (csg) {
  81209. var a = new Node(this.clone().polygons);
  81210. var b = new Node(csg.clone().polygons);
  81211. a.invert();
  81212. a.clipTo(b);
  81213. b.clipTo(a);
  81214. b.invert();
  81215. b.clipTo(a);
  81216. b.invert();
  81217. a.build(b.allPolygons());
  81218. a.invert();
  81219. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81220. };
  81221. CSG.prototype.subtractInPlace = function (csg) {
  81222. var a = new Node(this.polygons);
  81223. var b = new Node(csg.polygons);
  81224. a.invert();
  81225. a.clipTo(b);
  81226. b.clipTo(a);
  81227. b.invert();
  81228. b.clipTo(a);
  81229. b.invert();
  81230. a.build(b.allPolygons());
  81231. a.invert();
  81232. this.polygons = a.allPolygons();
  81233. };
  81234. CSG.prototype.intersect = function (csg) {
  81235. var a = new Node(this.clone().polygons);
  81236. var b = new Node(csg.clone().polygons);
  81237. a.invert();
  81238. b.clipTo(a);
  81239. b.invert();
  81240. a.clipTo(b);
  81241. b.clipTo(a);
  81242. a.build(b.allPolygons());
  81243. a.invert();
  81244. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  81245. };
  81246. CSG.prototype.intersectInPlace = function (csg) {
  81247. var a = new Node(this.polygons);
  81248. var b = new Node(csg.polygons);
  81249. a.invert();
  81250. b.clipTo(a);
  81251. b.invert();
  81252. a.clipTo(b);
  81253. b.clipTo(a);
  81254. a.build(b.allPolygons());
  81255. a.invert();
  81256. this.polygons = a.allPolygons();
  81257. };
  81258. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  81259. // not modified.
  81260. CSG.prototype.inverse = function () {
  81261. var csg = this.clone();
  81262. csg.inverseInPlace();
  81263. return csg;
  81264. };
  81265. CSG.prototype.inverseInPlace = function () {
  81266. this.polygons.map(function (p) { p.flip(); });
  81267. };
  81268. // This is used to keep meshes transformations so they can be restored
  81269. // when we build back a Babylon Mesh
  81270. // NB : All CSG operations are performed in world coordinates
  81271. CSG.prototype.copyTransformAttributes = function (csg) {
  81272. this.matrix = csg.matrix;
  81273. this.position = csg.position;
  81274. this.rotation = csg.rotation;
  81275. this.scaling = csg.scaling;
  81276. this.rotationQuaternion = csg.rotationQuaternion;
  81277. return this;
  81278. };
  81279. // Build Raw mesh from CSG
  81280. // Coordinates here are in world space
  81281. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  81282. var matrix = this.matrix.clone();
  81283. matrix.invert();
  81284. 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;
  81285. if (keepSubMeshes) {
  81286. // Sort Polygons, since subMeshes are indices range
  81287. polygons.sort(function (a, b) {
  81288. if (a.shared.meshId === b.shared.meshId) {
  81289. return a.shared.subMeshId - b.shared.subMeshId;
  81290. }
  81291. else {
  81292. return a.shared.meshId - b.shared.meshId;
  81293. }
  81294. });
  81295. }
  81296. for (var i = 0, il = polygons.length; i < il; i++) {
  81297. polygon = polygons[i];
  81298. // Building SubMeshes
  81299. if (!subMesh_dict[polygon.shared.meshId]) {
  81300. subMesh_dict[polygon.shared.meshId] = {};
  81301. }
  81302. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  81303. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  81304. indexStart: +Infinity,
  81305. indexEnd: -Infinity,
  81306. materialIndex: polygon.shared.materialIndex
  81307. };
  81308. }
  81309. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  81310. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  81311. polygonIndices[0] = 0;
  81312. polygonIndices[1] = j - 1;
  81313. polygonIndices[2] = j;
  81314. for (var k = 0; k < 3; k++) {
  81315. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  81316. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  81317. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  81318. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  81319. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  81320. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  81321. // Check if 2 points can be merged
  81322. if (!(typeof vertex_idx !== 'undefined' &&
  81323. normals[vertex_idx * 3] === localNormal.x &&
  81324. normals[vertex_idx * 3 + 1] === localNormal.y &&
  81325. normals[vertex_idx * 3 + 2] === localNormal.z &&
  81326. uvs[vertex_idx * 2] === uv.x &&
  81327. uvs[vertex_idx * 2 + 1] === uv.y)) {
  81328. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  81329. uvs.push(uv.x, uv.y);
  81330. normals.push(normal.x, normal.y, normal.z);
  81331. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  81332. }
  81333. indices.push(vertex_idx);
  81334. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  81335. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  81336. currentIndex++;
  81337. }
  81338. }
  81339. }
  81340. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  81341. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  81342. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  81343. mesh.setIndices(indices, null);
  81344. if (keepSubMeshes) {
  81345. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  81346. var materialIndexOffset = 0, materialMaxIndex;
  81347. mesh.subMeshes = new Array();
  81348. for (var m in subMesh_dict) {
  81349. materialMaxIndex = -1;
  81350. for (var sm in subMesh_dict[m]) {
  81351. subMesh_obj = subMesh_dict[m][sm];
  81352. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  81353. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  81354. }
  81355. materialIndexOffset += ++materialMaxIndex;
  81356. }
  81357. }
  81358. return mesh;
  81359. };
  81360. // Build Mesh from CSG taking material and transforms into account
  81361. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  81362. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  81363. mesh.material = material;
  81364. mesh.position.copyFrom(this.position);
  81365. mesh.rotation.copyFrom(this.rotation);
  81366. if (this.rotationQuaternion) {
  81367. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  81368. }
  81369. mesh.scaling.copyFrom(this.scaling);
  81370. mesh.computeWorldMatrix(true);
  81371. return mesh;
  81372. };
  81373. return CSG;
  81374. }());
  81375. BABYLON.CSG = CSG;
  81376. })(BABYLON || (BABYLON = {}));
  81377. //# sourceMappingURL=babylon.csg.js.map
  81378. var BABYLON;
  81379. (function (BABYLON) {
  81380. var LensFlare = /** @class */ (function () {
  81381. function LensFlare(size, position, color, imgUrl, system) {
  81382. this.size = size;
  81383. this.position = position;
  81384. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  81385. this.color = color || new BABYLON.Color3(1, 1, 1);
  81386. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  81387. this._system = system;
  81388. system.lensFlares.push(this);
  81389. }
  81390. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  81391. return new LensFlare(size, position, color, imgUrl, system);
  81392. };
  81393. LensFlare.prototype.dispose = function () {
  81394. if (this.texture) {
  81395. this.texture.dispose();
  81396. }
  81397. // Remove from scene
  81398. var index = this._system.lensFlares.indexOf(this);
  81399. this._system.lensFlares.splice(index, 1);
  81400. };
  81401. ;
  81402. return LensFlare;
  81403. }());
  81404. BABYLON.LensFlare = LensFlare;
  81405. })(BABYLON || (BABYLON = {}));
  81406. //# sourceMappingURL=babylon.lensFlare.js.map
  81407. var BABYLON;
  81408. (function (BABYLON) {
  81409. var LensFlareSystem = /** @class */ (function () {
  81410. function LensFlareSystem(name, emitter, scene) {
  81411. this.name = name;
  81412. this.lensFlares = new Array();
  81413. this.borderLimit = 300;
  81414. this.viewportBorder = 0;
  81415. this.layerMask = 0x0FFFFFFF;
  81416. this._vertexBuffers = {};
  81417. this._isEnabled = true;
  81418. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81419. this._emitter = emitter;
  81420. this.id = name;
  81421. scene.lensFlareSystems.push(this);
  81422. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  81423. var engine = scene.getEngine();
  81424. // VBO
  81425. var vertices = [];
  81426. vertices.push(1, 1);
  81427. vertices.push(-1, 1);
  81428. vertices.push(-1, -1);
  81429. vertices.push(1, -1);
  81430. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  81431. // Indices
  81432. var indices = [];
  81433. indices.push(0);
  81434. indices.push(1);
  81435. indices.push(2);
  81436. indices.push(0);
  81437. indices.push(2);
  81438. indices.push(3);
  81439. this._indexBuffer = engine.createIndexBuffer(indices);
  81440. // Effects
  81441. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  81442. }
  81443. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  81444. get: function () {
  81445. return this._isEnabled;
  81446. },
  81447. set: function (value) {
  81448. this._isEnabled = value;
  81449. },
  81450. enumerable: true,
  81451. configurable: true
  81452. });
  81453. LensFlareSystem.prototype.getScene = function () {
  81454. return this._scene;
  81455. };
  81456. LensFlareSystem.prototype.getEmitter = function () {
  81457. return this._emitter;
  81458. };
  81459. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  81460. this._emitter = newEmitter;
  81461. };
  81462. LensFlareSystem.prototype.getEmitterPosition = function () {
  81463. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  81464. };
  81465. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  81466. var position = this.getEmitterPosition();
  81467. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  81468. this._positionX = position.x;
  81469. this._positionY = position.y;
  81470. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  81471. if (this.viewportBorder > 0) {
  81472. globalViewport.x -= this.viewportBorder;
  81473. globalViewport.y -= this.viewportBorder;
  81474. globalViewport.width += this.viewportBorder * 2;
  81475. globalViewport.height += this.viewportBorder * 2;
  81476. position.x += this.viewportBorder;
  81477. position.y += this.viewportBorder;
  81478. this._positionX += this.viewportBorder;
  81479. this._positionY += this.viewportBorder;
  81480. }
  81481. if (position.z > 0) {
  81482. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  81483. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  81484. return true;
  81485. }
  81486. return true;
  81487. }
  81488. return false;
  81489. };
  81490. LensFlareSystem.prototype._isVisible = function () {
  81491. if (!this._isEnabled || !this._scene.activeCamera) {
  81492. return false;
  81493. }
  81494. var emitterPosition = this.getEmitterPosition();
  81495. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  81496. var distance = direction.length();
  81497. direction.normalize();
  81498. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  81499. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  81500. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  81501. };
  81502. LensFlareSystem.prototype.render = function () {
  81503. if (!this._effect.isReady() || !this._scene.activeCamera)
  81504. return false;
  81505. var engine = this._scene.getEngine();
  81506. var viewport = this._scene.activeCamera.viewport;
  81507. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  81508. // Position
  81509. if (!this.computeEffectivePosition(globalViewport)) {
  81510. return false;
  81511. }
  81512. // Visibility
  81513. if (!this._isVisible()) {
  81514. return false;
  81515. }
  81516. // Intensity
  81517. var awayX;
  81518. var awayY;
  81519. if (this._positionX < this.borderLimit + globalViewport.x) {
  81520. awayX = this.borderLimit + globalViewport.x - this._positionX;
  81521. }
  81522. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  81523. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  81524. }
  81525. else {
  81526. awayX = 0;
  81527. }
  81528. if (this._positionY < this.borderLimit + globalViewport.y) {
  81529. awayY = this.borderLimit + globalViewport.y - this._positionY;
  81530. }
  81531. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  81532. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  81533. }
  81534. else {
  81535. awayY = 0;
  81536. }
  81537. var away = (awayX > awayY) ? awayX : awayY;
  81538. away -= this.viewportBorder;
  81539. if (away > this.borderLimit) {
  81540. away = this.borderLimit;
  81541. }
  81542. var intensity = 1.0 - (away / this.borderLimit);
  81543. if (intensity < 0) {
  81544. return false;
  81545. }
  81546. if (intensity > 1.0) {
  81547. intensity = 1.0;
  81548. }
  81549. if (this.viewportBorder > 0) {
  81550. globalViewport.x += this.viewportBorder;
  81551. globalViewport.y += this.viewportBorder;
  81552. globalViewport.width -= this.viewportBorder * 2;
  81553. globalViewport.height -= this.viewportBorder * 2;
  81554. this._positionX -= this.viewportBorder;
  81555. this._positionY -= this.viewportBorder;
  81556. }
  81557. // Position
  81558. var centerX = globalViewport.x + globalViewport.width / 2;
  81559. var centerY = globalViewport.y + globalViewport.height / 2;
  81560. var distX = centerX - this._positionX;
  81561. var distY = centerY - this._positionY;
  81562. // Effects
  81563. engine.enableEffect(this._effect);
  81564. engine.setState(false);
  81565. engine.setDepthBuffer(false);
  81566. // VBOs
  81567. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  81568. // Flares
  81569. for (var index = 0; index < this.lensFlares.length; index++) {
  81570. var flare = this.lensFlares[index];
  81571. engine.setAlphaMode(flare.alphaMode);
  81572. var x = centerX - (distX * flare.position);
  81573. var y = centerY - (distY * flare.position);
  81574. var cw = flare.size;
  81575. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  81576. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  81577. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  81578. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  81579. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  81580. // Texture
  81581. this._effect.setTexture("textureSampler", flare.texture);
  81582. // Color
  81583. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  81584. // Draw order
  81585. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  81586. }
  81587. engine.setDepthBuffer(true);
  81588. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  81589. return true;
  81590. };
  81591. LensFlareSystem.prototype.dispose = function () {
  81592. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  81593. if (vertexBuffer) {
  81594. vertexBuffer.dispose();
  81595. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  81596. }
  81597. if (this._indexBuffer) {
  81598. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  81599. this._indexBuffer = null;
  81600. }
  81601. while (this.lensFlares.length) {
  81602. this.lensFlares[0].dispose();
  81603. }
  81604. // Remove from scene
  81605. var index = this._scene.lensFlareSystems.indexOf(this);
  81606. this._scene.lensFlareSystems.splice(index, 1);
  81607. };
  81608. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  81609. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  81610. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  81611. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  81612. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  81613. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  81614. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  81615. var parsedFlare = parsedLensFlareSystem.flares[index];
  81616. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  81617. }
  81618. return lensFlareSystem;
  81619. };
  81620. LensFlareSystem.prototype.serialize = function () {
  81621. var serializationObject = {};
  81622. serializationObject.id = this.id;
  81623. serializationObject.name = this.name;
  81624. serializationObject.emitterId = this.getEmitter().id;
  81625. serializationObject.borderLimit = this.borderLimit;
  81626. serializationObject.flares = [];
  81627. for (var index = 0; index < this.lensFlares.length; index++) {
  81628. var flare = this.lensFlares[index];
  81629. serializationObject.flares.push({
  81630. size: flare.size,
  81631. position: flare.position,
  81632. color: flare.color.asArray(),
  81633. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  81634. });
  81635. }
  81636. return serializationObject;
  81637. };
  81638. return LensFlareSystem;
  81639. }());
  81640. BABYLON.LensFlareSystem = LensFlareSystem;
  81641. })(BABYLON || (BABYLON = {}));
  81642. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  81643. var BABYLON;
  81644. (function (BABYLON) {
  81645. /**
  81646. * This is a holder class for the physics joint created by the physics plugin.
  81647. * It holds a set of functions to control the underlying joint.
  81648. */
  81649. var PhysicsJoint = /** @class */ (function () {
  81650. function PhysicsJoint(type, jointData) {
  81651. this.type = type;
  81652. this.jointData = jointData;
  81653. jointData.nativeParams = jointData.nativeParams || {};
  81654. }
  81655. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  81656. get: function () {
  81657. return this._physicsJoint;
  81658. },
  81659. set: function (newJoint) {
  81660. if (this._physicsJoint) {
  81661. //remove from the wolrd
  81662. }
  81663. this._physicsJoint = newJoint;
  81664. },
  81665. enumerable: true,
  81666. configurable: true
  81667. });
  81668. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  81669. set: function (physicsPlugin) {
  81670. this._physicsPlugin = physicsPlugin;
  81671. },
  81672. enumerable: true,
  81673. configurable: true
  81674. });
  81675. /**
  81676. * Execute a function that is physics-plugin specific.
  81677. * @param {Function} func the function that will be executed.
  81678. * It accepts two parameters: the physics world and the physics joint.
  81679. */
  81680. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  81681. func(this._physicsPlugin.world, this._physicsJoint);
  81682. };
  81683. //TODO check if the native joints are the same
  81684. //Joint Types
  81685. PhysicsJoint.DistanceJoint = 0;
  81686. PhysicsJoint.HingeJoint = 1;
  81687. PhysicsJoint.BallAndSocketJoint = 2;
  81688. PhysicsJoint.WheelJoint = 3;
  81689. PhysicsJoint.SliderJoint = 4;
  81690. //OIMO
  81691. PhysicsJoint.PrismaticJoint = 5;
  81692. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  81693. PhysicsJoint.UniversalJoint = 6;
  81694. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  81695. //Cannon
  81696. //Similar to a Ball-Joint. Different in params
  81697. PhysicsJoint.PointToPointJoint = 8;
  81698. //Cannon only at the moment
  81699. PhysicsJoint.SpringJoint = 9;
  81700. PhysicsJoint.LockJoint = 10;
  81701. return PhysicsJoint;
  81702. }());
  81703. BABYLON.PhysicsJoint = PhysicsJoint;
  81704. /**
  81705. * A class representing a physics distance joint.
  81706. */
  81707. var DistanceJoint = /** @class */ (function (_super) {
  81708. __extends(DistanceJoint, _super);
  81709. function DistanceJoint(jointData) {
  81710. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  81711. }
  81712. /**
  81713. * Update the predefined distance.
  81714. */
  81715. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  81716. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  81717. };
  81718. return DistanceJoint;
  81719. }(PhysicsJoint));
  81720. BABYLON.DistanceJoint = DistanceJoint;
  81721. var MotorEnabledJoint = /** @class */ (function (_super) {
  81722. __extends(MotorEnabledJoint, _super);
  81723. function MotorEnabledJoint(type, jointData) {
  81724. return _super.call(this, type, jointData) || this;
  81725. }
  81726. /**
  81727. * Set the motor values.
  81728. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81729. * @param {number} force the force to apply
  81730. * @param {number} maxForce max force for this motor.
  81731. */
  81732. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  81733. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81734. };
  81735. /**
  81736. * Set the motor's limits.
  81737. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81738. */
  81739. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81740. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81741. };
  81742. return MotorEnabledJoint;
  81743. }(PhysicsJoint));
  81744. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  81745. /**
  81746. * This class represents a single hinge physics joint
  81747. */
  81748. var HingeJoint = /** @class */ (function (_super) {
  81749. __extends(HingeJoint, _super);
  81750. function HingeJoint(jointData) {
  81751. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  81752. }
  81753. /**
  81754. * Set the motor values.
  81755. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81756. * @param {number} force the force to apply
  81757. * @param {number} maxForce max force for this motor.
  81758. */
  81759. HingeJoint.prototype.setMotor = function (force, maxForce) {
  81760. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  81761. };
  81762. /**
  81763. * Set the motor's limits.
  81764. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81765. */
  81766. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  81767. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  81768. };
  81769. return HingeJoint;
  81770. }(MotorEnabledJoint));
  81771. BABYLON.HingeJoint = HingeJoint;
  81772. /**
  81773. * This class represents a dual hinge physics joint (same as wheel joint)
  81774. */
  81775. var Hinge2Joint = /** @class */ (function (_super) {
  81776. __extends(Hinge2Joint, _super);
  81777. function Hinge2Joint(jointData) {
  81778. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  81779. }
  81780. /**
  81781. * Set the motor values.
  81782. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81783. * @param {number} force the force to apply
  81784. * @param {number} maxForce max force for this motor.
  81785. * @param {motorIndex} the motor's index, 0 or 1.
  81786. */
  81787. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  81788. if (motorIndex === void 0) { motorIndex = 0; }
  81789. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  81790. };
  81791. /**
  81792. * Set the motor limits.
  81793. * Attention, this function is plugin specific. Engines won't react 100% the same.
  81794. * @param {number} upperLimit the upper limit
  81795. * @param {number} lowerLimit lower limit
  81796. * @param {motorIndex} the motor's index, 0 or 1.
  81797. */
  81798. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  81799. if (motorIndex === void 0) { motorIndex = 0; }
  81800. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  81801. };
  81802. return Hinge2Joint;
  81803. }(MotorEnabledJoint));
  81804. BABYLON.Hinge2Joint = Hinge2Joint;
  81805. })(BABYLON || (BABYLON = {}));
  81806. //# sourceMappingURL=babylon.physicsJoint.js.map
  81807. var BABYLON;
  81808. (function (BABYLON) {
  81809. var PhysicsImpostor = /** @class */ (function () {
  81810. function PhysicsImpostor(object, type, _options, _scene) {
  81811. if (_options === void 0) { _options = { mass: 0 }; }
  81812. var _this = this;
  81813. this.object = object;
  81814. this.type = type;
  81815. this._options = _options;
  81816. this._scene = _scene;
  81817. this._bodyUpdateRequired = false;
  81818. this._onBeforePhysicsStepCallbacks = new Array();
  81819. this._onAfterPhysicsStepCallbacks = new Array();
  81820. this._onPhysicsCollideCallbacks = [];
  81821. this._deltaPosition = BABYLON.Vector3.Zero();
  81822. this._isDisposed = false;
  81823. //temp variables for parent rotation calculations
  81824. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  81825. this._tmpQuat = new BABYLON.Quaternion();
  81826. this._tmpQuat2 = new BABYLON.Quaternion();
  81827. /**
  81828. * this function is executed by the physics engine.
  81829. */
  81830. this.beforeStep = function () {
  81831. if (!_this._physicsEngine) {
  81832. return;
  81833. }
  81834. _this.object.translate(_this._deltaPosition, -1);
  81835. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  81836. _this.object.computeWorldMatrix(false);
  81837. if (_this.object.parent && _this.object.rotationQuaternion) {
  81838. _this.getParentsRotation();
  81839. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  81840. }
  81841. else {
  81842. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  81843. }
  81844. if (!_this._options.disableBidirectionalTransformation) {
  81845. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  81846. }
  81847. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  81848. func(_this);
  81849. });
  81850. };
  81851. /**
  81852. * this function is executed by the physics engine.
  81853. */
  81854. this.afterStep = function () {
  81855. if (!_this._physicsEngine) {
  81856. return;
  81857. }
  81858. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  81859. func(_this);
  81860. });
  81861. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  81862. // object has now its world rotation. needs to be converted to local.
  81863. if (_this.object.parent && _this.object.rotationQuaternion) {
  81864. _this.getParentsRotation();
  81865. _this._tmpQuat.conjugateInPlace();
  81866. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  81867. }
  81868. // take the position set and make it the absolute position of this object.
  81869. _this.object.setAbsolutePosition(_this.object.position);
  81870. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  81871. _this.object.translate(_this._deltaPosition, 1);
  81872. };
  81873. /**
  81874. * Legacy collision detection event support
  81875. */
  81876. this.onCollideEvent = null;
  81877. //event and body object due to cannon's event-based architecture.
  81878. this.onCollide = function (e) {
  81879. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  81880. return;
  81881. }
  81882. if (!_this._physicsEngine) {
  81883. return;
  81884. }
  81885. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  81886. if (otherImpostor) {
  81887. // Legacy collision detection event support
  81888. if (_this.onCollideEvent) {
  81889. _this.onCollideEvent(_this, otherImpostor);
  81890. }
  81891. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  81892. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  81893. }).forEach(function (obj) {
  81894. obj.callback(_this, otherImpostor);
  81895. });
  81896. }
  81897. };
  81898. //sanity check!
  81899. if (!this.object) {
  81900. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  81901. return;
  81902. }
  81903. //legacy support for old syntax.
  81904. if (!this._scene && object.getScene) {
  81905. this._scene = object.getScene();
  81906. }
  81907. if (!this._scene) {
  81908. return;
  81909. }
  81910. this._physicsEngine = this._scene.getPhysicsEngine();
  81911. if (!this._physicsEngine) {
  81912. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  81913. }
  81914. else {
  81915. //set the object's quaternion, if not set
  81916. if (!this.object.rotationQuaternion) {
  81917. if (this.object.rotation) {
  81918. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  81919. }
  81920. else {
  81921. this.object.rotationQuaternion = new BABYLON.Quaternion();
  81922. }
  81923. }
  81924. //default options params
  81925. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  81926. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  81927. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  81928. this._joints = [];
  81929. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  81930. if (!this.object.parent || this._options.ignoreParent) {
  81931. this._init();
  81932. }
  81933. else if (this.object.parent.physicsImpostor) {
  81934. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  81935. }
  81936. }
  81937. }
  81938. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  81939. get: function () {
  81940. return this._isDisposed;
  81941. },
  81942. enumerable: true,
  81943. configurable: true
  81944. });
  81945. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  81946. get: function () {
  81947. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  81948. },
  81949. set: function (value) {
  81950. this.setMass(value);
  81951. },
  81952. enumerable: true,
  81953. configurable: true
  81954. });
  81955. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  81956. get: function () {
  81957. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  81958. },
  81959. set: function (value) {
  81960. if (!this._physicsEngine) {
  81961. return;
  81962. }
  81963. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  81964. },
  81965. enumerable: true,
  81966. configurable: true
  81967. });
  81968. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  81969. get: function () {
  81970. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  81971. },
  81972. set: function (value) {
  81973. if (!this._physicsEngine) {
  81974. return;
  81975. }
  81976. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  81977. },
  81978. enumerable: true,
  81979. configurable: true
  81980. });
  81981. /**
  81982. * This function will completly initialize this impostor.
  81983. * It will create a new body - but only if this mesh has no parent.
  81984. * If it has, this impostor will not be used other than to define the impostor
  81985. * of the child mesh.
  81986. */
  81987. PhysicsImpostor.prototype._init = function () {
  81988. if (!this._physicsEngine) {
  81989. return;
  81990. }
  81991. this._physicsEngine.removeImpostor(this);
  81992. this.physicsBody = null;
  81993. this._parent = this._parent || this._getPhysicsParent();
  81994. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  81995. this._physicsEngine.addImpostor(this);
  81996. }
  81997. };
  81998. PhysicsImpostor.prototype._getPhysicsParent = function () {
  81999. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  82000. var parentMesh = this.object.parent;
  82001. return parentMesh.physicsImpostor;
  82002. }
  82003. return null;
  82004. };
  82005. /**
  82006. * Should a new body be generated.
  82007. */
  82008. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  82009. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  82010. };
  82011. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  82012. this.forceUpdate();
  82013. };
  82014. /**
  82015. * Force a regeneration of this or the parent's impostor's body.
  82016. * Use under cautious - This will remove all joints already implemented.
  82017. */
  82018. PhysicsImpostor.prototype.forceUpdate = function () {
  82019. this._init();
  82020. if (this.parent && !this._options.ignoreParent) {
  82021. this.parent.forceUpdate();
  82022. }
  82023. };
  82024. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  82025. /*public get mesh(): AbstractMesh {
  82026. return this._mesh;
  82027. }*/
  82028. /**
  82029. * Gets the body that holds this impostor. Either its own, or its parent.
  82030. */
  82031. get: function () {
  82032. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  82033. },
  82034. /**
  82035. * Set the physics body. Used mainly by the physics engine/plugin
  82036. */
  82037. set: function (physicsBody) {
  82038. if (this._physicsBody && this._physicsEngine) {
  82039. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  82040. }
  82041. this._physicsBody = physicsBody;
  82042. this.resetUpdateFlags();
  82043. },
  82044. enumerable: true,
  82045. configurable: true
  82046. });
  82047. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  82048. get: function () {
  82049. return !this._options.ignoreParent && this._parent ? this._parent : null;
  82050. },
  82051. set: function (value) {
  82052. this._parent = value;
  82053. },
  82054. enumerable: true,
  82055. configurable: true
  82056. });
  82057. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  82058. this._bodyUpdateRequired = false;
  82059. };
  82060. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  82061. if (this.object.getBoundingInfo) {
  82062. var q = this.object.rotationQuaternion;
  82063. //reset rotation
  82064. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  82065. //calculate the world matrix with no rotation
  82066. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82067. var boundingInfo = this.object.getBoundingInfo();
  82068. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  82069. //bring back the rotation
  82070. this.object.rotationQuaternion = q;
  82071. //calculate the world matrix with the new rotation
  82072. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  82073. return size;
  82074. }
  82075. else {
  82076. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  82077. }
  82078. };
  82079. PhysicsImpostor.prototype.getObjectCenter = function () {
  82080. if (this.object.getBoundingInfo) {
  82081. var boundingInfo = this.object.getBoundingInfo();
  82082. return boundingInfo.boundingBox.centerWorld;
  82083. }
  82084. else {
  82085. return this.object.position;
  82086. }
  82087. };
  82088. /**
  82089. * Get a specific parametes from the options parameter.
  82090. */
  82091. PhysicsImpostor.prototype.getParam = function (paramName) {
  82092. return this._options[paramName];
  82093. };
  82094. /**
  82095. * Sets a specific parameter in the options given to the physics plugin
  82096. */
  82097. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  82098. this._options[paramName] = value;
  82099. this._bodyUpdateRequired = true;
  82100. };
  82101. /**
  82102. * Specifically change the body's mass option. Won't recreate the physics body object
  82103. */
  82104. PhysicsImpostor.prototype.setMass = function (mass) {
  82105. if (this.getParam("mass") !== mass) {
  82106. this.setParam("mass", mass);
  82107. }
  82108. if (this._physicsEngine) {
  82109. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  82110. }
  82111. };
  82112. PhysicsImpostor.prototype.getLinearVelocity = function () {
  82113. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  82114. };
  82115. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  82116. if (this._physicsEngine) {
  82117. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  82118. }
  82119. };
  82120. PhysicsImpostor.prototype.getAngularVelocity = function () {
  82121. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  82122. };
  82123. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  82124. if (this._physicsEngine) {
  82125. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  82126. }
  82127. };
  82128. /**
  82129. * Execute a function with the physics plugin native code.
  82130. * Provide a function the will have two variables - the world object and the physics body object.
  82131. */
  82132. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  82133. if (this._physicsEngine) {
  82134. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  82135. }
  82136. };
  82137. /**
  82138. * Register a function that will be executed before the physics world is stepping forward.
  82139. */
  82140. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  82141. this._onBeforePhysicsStepCallbacks.push(func);
  82142. };
  82143. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  82144. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  82145. if (index > -1) {
  82146. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  82147. }
  82148. else {
  82149. BABYLON.Tools.Warn("Function to remove was not found");
  82150. }
  82151. };
  82152. /**
  82153. * Register a function that will be executed after the physics step
  82154. */
  82155. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  82156. this._onAfterPhysicsStepCallbacks.push(func);
  82157. };
  82158. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  82159. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  82160. if (index > -1) {
  82161. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  82162. }
  82163. else {
  82164. BABYLON.Tools.Warn("Function to remove was not found");
  82165. }
  82166. };
  82167. /**
  82168. * register a function that will be executed when this impostor collides against a different body.
  82169. */
  82170. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  82171. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82172. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  82173. };
  82174. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  82175. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  82176. var index = this._onPhysicsCollideCallbacks.indexOf({ callback: func, otherImpostors: collidedAgainstList });
  82177. if (index > -1) {
  82178. this._onPhysicsCollideCallbacks.splice(index, 1);
  82179. }
  82180. else {
  82181. BABYLON.Tools.Warn("Function to remove was not found");
  82182. }
  82183. };
  82184. PhysicsImpostor.prototype.getParentsRotation = function () {
  82185. var parent = this.object.parent;
  82186. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  82187. while (parent) {
  82188. if (parent.rotationQuaternion) {
  82189. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  82190. }
  82191. else {
  82192. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  82193. }
  82194. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  82195. parent = parent.parent;
  82196. }
  82197. return this._tmpQuat;
  82198. };
  82199. /**
  82200. * Apply a force
  82201. */
  82202. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  82203. if (this._physicsEngine) {
  82204. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  82205. }
  82206. return this;
  82207. };
  82208. /**
  82209. * Apply an impulse
  82210. */
  82211. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  82212. if (this._physicsEngine) {
  82213. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  82214. }
  82215. return this;
  82216. };
  82217. /**
  82218. * A help function to create a joint.
  82219. */
  82220. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  82221. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  82222. this.addJoint(otherImpostor, joint);
  82223. return this;
  82224. };
  82225. /**
  82226. * Add a joint to this impostor with a different impostor.
  82227. */
  82228. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  82229. this._joints.push({
  82230. otherImpostor: otherImpostor,
  82231. joint: joint
  82232. });
  82233. if (this._physicsEngine) {
  82234. this._physicsEngine.addJoint(this, otherImpostor, joint);
  82235. }
  82236. return this;
  82237. };
  82238. /**
  82239. * Will keep this body still, in a sleep mode.
  82240. */
  82241. PhysicsImpostor.prototype.sleep = function () {
  82242. if (this._physicsEngine) {
  82243. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  82244. }
  82245. return this;
  82246. };
  82247. /**
  82248. * Wake the body up.
  82249. */
  82250. PhysicsImpostor.prototype.wakeUp = function () {
  82251. if (this._physicsEngine) {
  82252. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  82253. }
  82254. return this;
  82255. };
  82256. PhysicsImpostor.prototype.clone = function (newObject) {
  82257. if (!newObject)
  82258. return null;
  82259. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  82260. };
  82261. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  82262. var _this = this;
  82263. //no dispose if no physics engine is available.
  82264. if (!this._physicsEngine) {
  82265. return;
  82266. }
  82267. this._joints.forEach(function (j) {
  82268. if (_this._physicsEngine) {
  82269. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  82270. }
  82271. });
  82272. //dispose the physics body
  82273. this._physicsEngine.removeImpostor(this);
  82274. if (this.parent) {
  82275. this.parent.forceUpdate();
  82276. }
  82277. else {
  82278. /*this._object.getChildMeshes().forEach(function(mesh) {
  82279. if (mesh.physicsImpostor) {
  82280. if (disposeChildren) {
  82281. mesh.physicsImpostor.dispose();
  82282. mesh.physicsImpostor = null;
  82283. }
  82284. }
  82285. })*/
  82286. }
  82287. this._isDisposed = true;
  82288. };
  82289. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  82290. this._deltaPosition.copyFrom(position);
  82291. };
  82292. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  82293. if (!this._deltaRotation) {
  82294. this._deltaRotation = new BABYLON.Quaternion();
  82295. }
  82296. this._deltaRotation.copyFrom(rotation);
  82297. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  82298. };
  82299. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  82300. if (this._physicsEngine) {
  82301. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  82302. }
  82303. return this;
  82304. };
  82305. PhysicsImpostor.prototype.getRadius = function () {
  82306. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  82307. };
  82308. /**
  82309. * Sync a bone with this impostor
  82310. * @param bone The bone to sync to the impostor.
  82311. * @param boneMesh The mesh that the bone is influencing.
  82312. * @param jointPivot The pivot of the joint / bone in local space.
  82313. * @param distToJoint Optional distance from the impostor to the joint.
  82314. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82315. */
  82316. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  82317. var tempVec = PhysicsImpostor._tmpVecs[0];
  82318. var mesh = this.object;
  82319. if (mesh.rotationQuaternion) {
  82320. if (adjustRotation) {
  82321. var tempQuat = PhysicsImpostor._tmpQuat;
  82322. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  82323. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  82324. }
  82325. else {
  82326. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  82327. }
  82328. }
  82329. tempVec.x = 0;
  82330. tempVec.y = 0;
  82331. tempVec.z = 0;
  82332. if (jointPivot) {
  82333. tempVec.x = jointPivot.x;
  82334. tempVec.y = jointPivot.y;
  82335. tempVec.z = jointPivot.z;
  82336. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  82337. if (distToJoint === undefined || distToJoint === null) {
  82338. distToJoint = jointPivot.length();
  82339. }
  82340. tempVec.x *= distToJoint;
  82341. tempVec.y *= distToJoint;
  82342. tempVec.z *= distToJoint;
  82343. }
  82344. if (bone.getParent()) {
  82345. tempVec.addInPlace(mesh.getAbsolutePosition());
  82346. bone.setAbsolutePosition(tempVec, boneMesh);
  82347. }
  82348. else {
  82349. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  82350. boneMesh.position.x -= tempVec.x;
  82351. boneMesh.position.y -= tempVec.y;
  82352. boneMesh.position.z -= tempVec.z;
  82353. }
  82354. };
  82355. /**
  82356. * Sync impostor to a bone
  82357. * @param bone The bone that the impostor will be synced to.
  82358. * @param boneMesh The mesh that the bone is influencing.
  82359. * @param jointPivot The pivot of the joint / bone in local space.
  82360. * @param distToJoint Optional distance from the impostor to the joint.
  82361. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  82362. * @param boneAxis Optional vector3 axis the bone is aligned with
  82363. */
  82364. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  82365. var mesh = this.object;
  82366. if (mesh.rotationQuaternion) {
  82367. if (adjustRotation) {
  82368. var tempQuat = PhysicsImpostor._tmpQuat;
  82369. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  82370. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  82371. }
  82372. else {
  82373. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  82374. }
  82375. }
  82376. var pos = PhysicsImpostor._tmpVecs[0];
  82377. var boneDir = PhysicsImpostor._tmpVecs[1];
  82378. if (!boneAxis) {
  82379. boneAxis = PhysicsImpostor._tmpVecs[2];
  82380. boneAxis.x = 0;
  82381. boneAxis.y = 1;
  82382. boneAxis.z = 0;
  82383. }
  82384. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  82385. bone.getAbsolutePositionToRef(boneMesh, pos);
  82386. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  82387. distToJoint = jointPivot.length();
  82388. }
  82389. if (distToJoint !== undefined && distToJoint !== null) {
  82390. pos.x += boneDir.x * distToJoint;
  82391. pos.y += boneDir.y * distToJoint;
  82392. pos.z += boneDir.z * distToJoint;
  82393. }
  82394. mesh.setAbsolutePosition(pos);
  82395. };
  82396. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  82397. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  82398. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  82399. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  82400. //Impostor types
  82401. PhysicsImpostor.NoImpostor = 0;
  82402. PhysicsImpostor.SphereImpostor = 1;
  82403. PhysicsImpostor.BoxImpostor = 2;
  82404. PhysicsImpostor.PlaneImpostor = 3;
  82405. PhysicsImpostor.MeshImpostor = 4;
  82406. PhysicsImpostor.CylinderImpostor = 7;
  82407. PhysicsImpostor.ParticleImpostor = 8;
  82408. PhysicsImpostor.HeightmapImpostor = 9;
  82409. return PhysicsImpostor;
  82410. }());
  82411. BABYLON.PhysicsImpostor = PhysicsImpostor;
  82412. })(BABYLON || (BABYLON = {}));
  82413. //# sourceMappingURL=babylon.physicsImpostor.js.map
  82414. var BABYLON;
  82415. (function (BABYLON) {
  82416. var PhysicsEngine = /** @class */ (function () {
  82417. function PhysicsEngine(gravity, _physicsPlugin) {
  82418. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  82419. this._physicsPlugin = _physicsPlugin;
  82420. //new methods and parameters
  82421. this._impostors = [];
  82422. this._joints = [];
  82423. if (!this._physicsPlugin.isSupported()) {
  82424. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  82425. + "Please make sure it is included.");
  82426. }
  82427. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  82428. this.setGravity(gravity);
  82429. this.setTimeStep();
  82430. }
  82431. PhysicsEngine.prototype.setGravity = function (gravity) {
  82432. this.gravity = gravity;
  82433. this._physicsPlugin.setGravity(this.gravity);
  82434. };
  82435. /**
  82436. * Set the time step of the physics engine.
  82437. * default is 1/60.
  82438. * To slow it down, enter 1/600 for example.
  82439. * To speed it up, 1/30
  82440. * @param {number} newTimeStep the new timestep to apply to this world.
  82441. */
  82442. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  82443. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  82444. this._physicsPlugin.setTimeStep(newTimeStep);
  82445. };
  82446. /**
  82447. * Get the time step of the physics engine.
  82448. */
  82449. PhysicsEngine.prototype.getTimeStep = function () {
  82450. return this._physicsPlugin.getTimeStep();
  82451. };
  82452. PhysicsEngine.prototype.dispose = function () {
  82453. this._impostors.forEach(function (impostor) {
  82454. impostor.dispose();
  82455. });
  82456. this._physicsPlugin.dispose();
  82457. };
  82458. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  82459. return this._physicsPlugin.name;
  82460. };
  82461. /**
  82462. * Adding a new impostor for the impostor tracking.
  82463. * This will be done by the impostor itself.
  82464. * @param {PhysicsImpostor} impostor the impostor to add
  82465. */
  82466. PhysicsEngine.prototype.addImpostor = function (impostor) {
  82467. impostor.uniqueId = this._impostors.push(impostor);
  82468. //if no parent, generate the body
  82469. if (!impostor.parent) {
  82470. this._physicsPlugin.generatePhysicsBody(impostor);
  82471. }
  82472. };
  82473. /**
  82474. * Remove an impostor from the engine.
  82475. * This impostor and its mesh will not longer be updated by the physics engine.
  82476. * @param {PhysicsImpostor} impostor the impostor to remove
  82477. */
  82478. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  82479. var index = this._impostors.indexOf(impostor);
  82480. if (index > -1) {
  82481. var removed = this._impostors.splice(index, 1);
  82482. //Is it needed?
  82483. if (removed.length) {
  82484. //this will also remove it from the world.
  82485. removed[0].physicsBody = null;
  82486. }
  82487. }
  82488. };
  82489. /**
  82490. * Add a joint to the physics engine
  82491. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  82492. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  82493. * @param {PhysicsJoint} the joint that will connect both impostors.
  82494. */
  82495. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  82496. var impostorJoint = {
  82497. mainImpostor: mainImpostor,
  82498. connectedImpostor: connectedImpostor,
  82499. joint: joint
  82500. };
  82501. joint.physicsPlugin = this._physicsPlugin;
  82502. this._joints.push(impostorJoint);
  82503. this._physicsPlugin.generateJoint(impostorJoint);
  82504. };
  82505. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  82506. var matchingJoints = this._joints.filter(function (impostorJoint) {
  82507. return (impostorJoint.connectedImpostor === connectedImpostor
  82508. && impostorJoint.joint === joint
  82509. && impostorJoint.mainImpostor === mainImpostor);
  82510. });
  82511. if (matchingJoints.length) {
  82512. this._physicsPlugin.removeJoint(matchingJoints[0]);
  82513. //TODO remove it from the list as well
  82514. }
  82515. };
  82516. /**
  82517. * Called by the scene. no need to call it.
  82518. */
  82519. PhysicsEngine.prototype._step = function (delta) {
  82520. var _this = this;
  82521. //check if any mesh has no body / requires an update
  82522. this._impostors.forEach(function (impostor) {
  82523. if (impostor.isBodyInitRequired()) {
  82524. _this._physicsPlugin.generatePhysicsBody(impostor);
  82525. }
  82526. });
  82527. if (delta > 0.1) {
  82528. delta = 0.1;
  82529. }
  82530. else if (delta <= 0) {
  82531. delta = 1.0 / 60.0;
  82532. }
  82533. this._physicsPlugin.executeStep(delta, this._impostors);
  82534. };
  82535. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  82536. return this._physicsPlugin;
  82537. };
  82538. PhysicsEngine.prototype.getImpostors = function () {
  82539. return this._impostors;
  82540. };
  82541. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  82542. for (var i = 0; i < this._impostors.length; ++i) {
  82543. if (this._impostors[i].object === object) {
  82544. return this._impostors[i];
  82545. }
  82546. }
  82547. return null;
  82548. };
  82549. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  82550. for (var i = 0; i < this._impostors.length; ++i) {
  82551. if (this._impostors[i].physicsBody === body) {
  82552. return this._impostors[i];
  82553. }
  82554. }
  82555. return null;
  82556. };
  82557. // Statics
  82558. PhysicsEngine.Epsilon = 0.001;
  82559. return PhysicsEngine;
  82560. }());
  82561. BABYLON.PhysicsEngine = PhysicsEngine;
  82562. })(BABYLON || (BABYLON = {}));
  82563. //# sourceMappingURL=babylon.physicsEngine.js.map
  82564. var BABYLON;
  82565. (function (BABYLON) {
  82566. var PhysicsHelper = /** @class */ (function () {
  82567. function PhysicsHelper(scene) {
  82568. this._scene = scene;
  82569. this._physicsEngine = this._scene.getPhysicsEngine();
  82570. if (!this._physicsEngine) {
  82571. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  82572. }
  82573. }
  82574. /**
  82575. * @param {Vector3} origin the origin of the explosion
  82576. * @param {number} radius the explosion radius
  82577. * @param {number} strength the explosion strength
  82578. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82579. */
  82580. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  82581. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82582. if (!this._physicsEngine) {
  82583. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  82584. return null;
  82585. }
  82586. var impostors = this._physicsEngine.getImpostors();
  82587. if (impostors.length === 0) {
  82588. return null;
  82589. }
  82590. var event = new PhysicsRadialExplosionEvent(this._scene);
  82591. impostors.forEach(function (impostor) {
  82592. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82593. if (!impostorForceAndContactPoint) {
  82594. return;
  82595. }
  82596. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82597. });
  82598. event.dispose(false);
  82599. return event;
  82600. };
  82601. /**
  82602. * @param {Vector3} origin the origin of the explosion
  82603. * @param {number} radius the explosion radius
  82604. * @param {number} strength the explosion strength
  82605. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82606. */
  82607. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  82608. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82609. if (!this._physicsEngine) {
  82610. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82611. return null;
  82612. }
  82613. var impostors = this._physicsEngine.getImpostors();
  82614. if (impostors.length === 0) {
  82615. return null;
  82616. }
  82617. var event = new PhysicsRadialExplosionEvent(this._scene);
  82618. impostors.forEach(function (impostor) {
  82619. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  82620. if (!impostorForceAndContactPoint) {
  82621. return;
  82622. }
  82623. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82624. });
  82625. event.dispose(false);
  82626. return event;
  82627. };
  82628. /**
  82629. * @param {Vector3} origin the origin of the explosion
  82630. * @param {number} radius the explosion radius
  82631. * @param {number} strength the explosion strength
  82632. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  82633. */
  82634. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  82635. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82636. if (!this._physicsEngine) {
  82637. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82638. return null;
  82639. }
  82640. var impostors = this._physicsEngine.getImpostors();
  82641. if (impostors.length === 0) {
  82642. return null;
  82643. }
  82644. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  82645. event.dispose(false);
  82646. return event;
  82647. };
  82648. /**
  82649. * @param {Vector3} origin the origin of the updraft
  82650. * @param {number} radius the radius of the updraft
  82651. * @param {number} strength the strength of the updraft
  82652. * @param {number} height the height of the updraft
  82653. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  82654. */
  82655. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  82656. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  82657. if (!this._physicsEngine) {
  82658. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82659. return null;
  82660. }
  82661. if (this._physicsEngine.getImpostors().length === 0) {
  82662. return null;
  82663. }
  82664. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  82665. event.dispose(false);
  82666. return event;
  82667. };
  82668. /**
  82669. * @param {Vector3} origin the of the vortex
  82670. * @param {number} radius the radius of the vortex
  82671. * @param {number} strength the strength of the vortex
  82672. * @param {number} height the height of the vortex
  82673. */
  82674. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  82675. if (!this._physicsEngine) {
  82676. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  82677. return null;
  82678. }
  82679. if (this._physicsEngine.getImpostors().length === 0) {
  82680. return null;
  82681. }
  82682. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  82683. event.dispose(false);
  82684. return event;
  82685. };
  82686. return PhysicsHelper;
  82687. }());
  82688. BABYLON.PhysicsHelper = PhysicsHelper;
  82689. /***** Radial explosion *****/
  82690. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  82691. function PhysicsRadialExplosionEvent(scene) {
  82692. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  82693. this._rays = [];
  82694. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  82695. this._scene = scene;
  82696. }
  82697. /**
  82698. * Returns the data related to the radial explosion event (sphere & rays).
  82699. * @returns {PhysicsRadialExplosionEventData}
  82700. */
  82701. PhysicsRadialExplosionEvent.prototype.getData = function () {
  82702. this._dataFetched = true;
  82703. return {
  82704. sphere: this._sphere,
  82705. rays: this._rays,
  82706. };
  82707. };
  82708. /**
  82709. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  82710. * @param impostor
  82711. * @param {Vector3} origin the origin of the explosion
  82712. * @param {number} radius the explosion radius
  82713. * @param {number} strength the explosion strength
  82714. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  82715. * @returns {Nullable<PhysicsForceAndContactPoint>}
  82716. */
  82717. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  82718. if (impostor.mass === 0) {
  82719. return null;
  82720. }
  82721. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  82722. return null;
  82723. }
  82724. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  82725. return null;
  82726. }
  82727. var impostorObjectCenter = impostor.getObjectCenter();
  82728. var direction = impostorObjectCenter.subtract(origin);
  82729. var ray = new BABYLON.Ray(origin, direction, radius);
  82730. this._rays.push(ray);
  82731. var hit = ray.intersectsMesh(impostor.object);
  82732. var contactPoint = hit.pickedPoint;
  82733. if (!contactPoint) {
  82734. return null;
  82735. }
  82736. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  82737. if (distanceFromOrigin > radius) {
  82738. return null;
  82739. }
  82740. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  82741. ? strength
  82742. : strength * (1 - (distanceFromOrigin / radius));
  82743. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82744. return { force: force, contactPoint: contactPoint };
  82745. };
  82746. /**
  82747. * Disposes the sphere.
  82748. * @param {bolean} force
  82749. */
  82750. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  82751. var _this = this;
  82752. if (force === void 0) { force = true; }
  82753. if (force) {
  82754. this._sphere.dispose();
  82755. }
  82756. else {
  82757. setTimeout(function () {
  82758. if (!_this._dataFetched) {
  82759. _this._sphere.dispose();
  82760. }
  82761. }, 0);
  82762. }
  82763. };
  82764. /*** Helpers ***/
  82765. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  82766. if (!this._sphere) {
  82767. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  82768. this._sphere.isVisible = false;
  82769. }
  82770. };
  82771. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  82772. var impostorObject = impostor.object;
  82773. this._prepareSphere();
  82774. this._sphere.position = origin;
  82775. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  82776. this._sphere._updateBoundingInfo();
  82777. this._sphere.computeWorldMatrix(true);
  82778. return this._sphere.intersectsMesh(impostorObject, true);
  82779. };
  82780. return PhysicsRadialExplosionEvent;
  82781. }());
  82782. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  82783. /***** Gravitational Field *****/
  82784. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  82785. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  82786. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  82787. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82788. this._physicsHelper = physicsHelper;
  82789. this._scene = scene;
  82790. this._origin = origin;
  82791. this._radius = radius;
  82792. this._strength = strength;
  82793. this._falloff = falloff;
  82794. this._tickCallback = this._tick.bind(this);
  82795. }
  82796. /**
  82797. * Returns the data related to the gravitational field event (sphere).
  82798. * @returns {PhysicsGravitationalFieldEventData}
  82799. */
  82800. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  82801. this._dataFetched = true;
  82802. return {
  82803. sphere: this._sphere,
  82804. };
  82805. };
  82806. /**
  82807. * Enables the gravitational field.
  82808. */
  82809. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  82810. this._tickCallback.call(this);
  82811. this._scene.registerBeforeRender(this._tickCallback);
  82812. };
  82813. /**
  82814. * Disables the gravitational field.
  82815. */
  82816. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  82817. this._scene.unregisterBeforeRender(this._tickCallback);
  82818. };
  82819. /**
  82820. * Disposes the sphere.
  82821. * @param {bolean} force
  82822. */
  82823. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  82824. var _this = this;
  82825. if (force === void 0) { force = true; }
  82826. if (force) {
  82827. this._sphere.dispose();
  82828. }
  82829. else {
  82830. setTimeout(function () {
  82831. if (!_this._dataFetched) {
  82832. _this._sphere.dispose();
  82833. }
  82834. }, 0);
  82835. }
  82836. };
  82837. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  82838. // Since the params won't change, we fetch the event only once
  82839. if (this._sphere) {
  82840. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82841. }
  82842. else {
  82843. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  82844. if (radialExplosionEvent) {
  82845. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  82846. }
  82847. }
  82848. };
  82849. return PhysicsGravitationalFieldEvent;
  82850. }());
  82851. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  82852. /***** Updraft *****/
  82853. var PhysicsUpdraftEvent = /** @class */ (function () {
  82854. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  82855. this._scene = _scene;
  82856. this._origin = _origin;
  82857. this._radius = _radius;
  82858. this._strength = _strength;
  82859. this._height = _height;
  82860. this._updraftMode = _updraftMode;
  82861. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82862. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  82863. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82864. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82865. this._physicsEngine = this._scene.getPhysicsEngine();
  82866. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82867. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82868. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82869. this._originDirection = this._origin.subtract(this._originTop).normalize();
  82870. }
  82871. this._tickCallback = this._tick.bind(this);
  82872. }
  82873. /**
  82874. * Returns the data related to the updraft event (cylinder).
  82875. * @returns {PhysicsUpdraftEventData}
  82876. */
  82877. PhysicsUpdraftEvent.prototype.getData = function () {
  82878. this._dataFetched = true;
  82879. return {
  82880. cylinder: this._cylinder,
  82881. };
  82882. };
  82883. /**
  82884. * Enables the updraft.
  82885. */
  82886. PhysicsUpdraftEvent.prototype.enable = function () {
  82887. this._tickCallback.call(this);
  82888. this._scene.registerBeforeRender(this._tickCallback);
  82889. };
  82890. /**
  82891. * Disables the cortex.
  82892. */
  82893. PhysicsUpdraftEvent.prototype.disable = function () {
  82894. this._scene.unregisterBeforeRender(this._tickCallback);
  82895. };
  82896. /**
  82897. * Disposes the sphere.
  82898. * @param {bolean} force
  82899. */
  82900. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  82901. var _this = this;
  82902. if (force === void 0) { force = true; }
  82903. if (force) {
  82904. this._cylinder.dispose();
  82905. }
  82906. else {
  82907. setTimeout(function () {
  82908. if (!_this._dataFetched) {
  82909. _this._cylinder.dispose();
  82910. }
  82911. }, 0);
  82912. }
  82913. };
  82914. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  82915. if (impostor.mass === 0) {
  82916. return null;
  82917. }
  82918. if (!this._intersectsWithCylinder(impostor)) {
  82919. return null;
  82920. }
  82921. var impostorObjectCenter = impostor.getObjectCenter();
  82922. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  82923. var direction = this._originDirection;
  82924. }
  82925. else {
  82926. var direction = impostorObjectCenter.subtract(this._originTop);
  82927. }
  82928. var multiplier = this._strength * -1;
  82929. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  82930. return { force: force, contactPoint: impostorObjectCenter };
  82931. };
  82932. PhysicsUpdraftEvent.prototype._tick = function () {
  82933. var _this = this;
  82934. this._physicsEngine.getImpostors().forEach(function (impostor) {
  82935. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  82936. if (!impostorForceAndContactPoint) {
  82937. return;
  82938. }
  82939. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  82940. });
  82941. };
  82942. /*** Helpers ***/
  82943. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  82944. if (!this._cylinder) {
  82945. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  82946. height: this._height,
  82947. diameter: this._radius * 2,
  82948. }, this._scene);
  82949. this._cylinder.isVisible = false;
  82950. }
  82951. };
  82952. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  82953. var impostorObject = impostor.object;
  82954. this._prepareCylinder();
  82955. this._cylinder.position = this._cylinderPosition;
  82956. return this._cylinder.intersectsMesh(impostorObject, true);
  82957. };
  82958. return PhysicsUpdraftEvent;
  82959. }());
  82960. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  82961. /***** Vortex *****/
  82962. var PhysicsVortexEvent = /** @class */ (function () {
  82963. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  82964. this._scene = _scene;
  82965. this._origin = _origin;
  82966. this._radius = _radius;
  82967. this._strength = _strength;
  82968. this._height = _height;
  82969. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  82970. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  82971. this._updraftMultiplier = 0.02;
  82972. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  82973. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  82974. this._physicsEngine = this._scene.getPhysicsEngine();
  82975. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  82976. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  82977. this._tickCallback = this._tick.bind(this);
  82978. }
  82979. /**
  82980. * Returns the data related to the vortex event (cylinder).
  82981. * @returns {PhysicsVortexEventData}
  82982. */
  82983. PhysicsVortexEvent.prototype.getData = function () {
  82984. this._dataFetched = true;
  82985. return {
  82986. cylinder: this._cylinder,
  82987. };
  82988. };
  82989. /**
  82990. * Enables the vortex.
  82991. */
  82992. PhysicsVortexEvent.prototype.enable = function () {
  82993. this._tickCallback.call(this);
  82994. this._scene.registerBeforeRender(this._tickCallback);
  82995. };
  82996. /**
  82997. * Disables the cortex.
  82998. */
  82999. PhysicsVortexEvent.prototype.disable = function () {
  83000. this._scene.unregisterBeforeRender(this._tickCallback);
  83001. };
  83002. /**
  83003. * Disposes the sphere.
  83004. * @param {bolean} force
  83005. */
  83006. PhysicsVortexEvent.prototype.dispose = function (force) {
  83007. var _this = this;
  83008. if (force === void 0) { force = true; }
  83009. if (force) {
  83010. this._cylinder.dispose();
  83011. }
  83012. else {
  83013. setTimeout(function () {
  83014. if (!_this._dataFetched) {
  83015. _this._cylinder.dispose();
  83016. }
  83017. }, 0);
  83018. }
  83019. };
  83020. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  83021. if (impostor.mass === 0) {
  83022. return null;
  83023. }
  83024. if (!this._intersectsWithCylinder(impostor)) {
  83025. return null;
  83026. }
  83027. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  83028. return null;
  83029. }
  83030. var impostorObjectCenter = impostor.getObjectCenter();
  83031. 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)
  83032. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  83033. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  83034. var hit = ray.intersectsMesh(impostor.object);
  83035. var contactPoint = hit.pickedPoint;
  83036. if (!contactPoint) {
  83037. return null;
  83038. }
  83039. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  83040. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  83041. var directionToOrigin = contactPoint.normalize();
  83042. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83043. directionToOrigin = directionToOrigin.negate();
  83044. }
  83045. // TODO: find a more physically based solution
  83046. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  83047. var forceX = directionToOrigin.x * this._strength / 8;
  83048. var forceY = directionToOrigin.y * this._updraftMultiplier;
  83049. var forceZ = directionToOrigin.z * this._strength / 8;
  83050. }
  83051. else {
  83052. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  83053. var forceY = this._originTop.y * this._updraftMultiplier;
  83054. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  83055. }
  83056. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  83057. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  83058. return { force: force, contactPoint: impostorObjectCenter };
  83059. };
  83060. PhysicsVortexEvent.prototype._tick = function () {
  83061. var _this = this;
  83062. this._physicsEngine.getImpostors().forEach(function (impostor) {
  83063. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  83064. if (!impostorForceAndContactPoint) {
  83065. return;
  83066. }
  83067. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  83068. });
  83069. };
  83070. /*** Helpers ***/
  83071. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  83072. if (!this._cylinder) {
  83073. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  83074. height: this._height,
  83075. diameter: this._radius * 2,
  83076. }, this._scene);
  83077. this._cylinder.isVisible = false;
  83078. }
  83079. };
  83080. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  83081. var impostorObject = impostor.object;
  83082. this._prepareCylinder();
  83083. this._cylinder.position = this._cylinderPosition;
  83084. return this._cylinder.intersectsMesh(impostorObject, true);
  83085. };
  83086. return PhysicsVortexEvent;
  83087. }());
  83088. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  83089. /***** Enums *****/
  83090. /**
  83091. * The strenght of the force in correspondence to the distance of the affected object
  83092. */
  83093. var PhysicsRadialImpulseFalloff;
  83094. (function (PhysicsRadialImpulseFalloff) {
  83095. /** Defines that impulse is constant in strength across it's whole radius */
  83096. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  83097. /** DEfines that impulse gets weaker if it's further from the origin */
  83098. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  83099. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  83100. /**
  83101. * The strenght of the force in correspondence to the distance of the affected object
  83102. */
  83103. var PhysicsUpdraftMode;
  83104. (function (PhysicsUpdraftMode) {
  83105. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  83106. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  83107. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  83108. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  83109. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  83110. })(BABYLON || (BABYLON = {}));
  83111. //# sourceMappingURL=babylon.physicsHelper.js.map
  83112. var BABYLON;
  83113. (function (BABYLON) {
  83114. var CannonJSPlugin = /** @class */ (function () {
  83115. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  83116. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  83117. if (iterations === void 0) { iterations = 10; }
  83118. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  83119. this.name = "CannonJSPlugin";
  83120. this._physicsMaterials = new Array();
  83121. this._fixedTimeStep = 1 / 60;
  83122. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  83123. this.BJSCANNON = CANNON;
  83124. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  83125. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  83126. this._tmpPosition = BABYLON.Vector3.Zero();
  83127. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  83128. this._tmpUnityRotation = new BABYLON.Quaternion();
  83129. if (!this.isSupported()) {
  83130. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  83131. return;
  83132. }
  83133. this._extendNamespace();
  83134. this.world = new this.BJSCANNON.World();
  83135. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  83136. this.world.solver.iterations = iterations;
  83137. }
  83138. CannonJSPlugin.prototype.setGravity = function (gravity) {
  83139. this.world.gravity.copy(gravity);
  83140. };
  83141. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  83142. this._fixedTimeStep = timeStep;
  83143. };
  83144. CannonJSPlugin.prototype.getTimeStep = function () {
  83145. return this._fixedTimeStep;
  83146. };
  83147. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  83148. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  83149. };
  83150. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83151. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83152. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83153. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  83154. };
  83155. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83156. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  83157. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  83158. impostor.physicsBody.applyForce(impulse, worldPoint);
  83159. };
  83160. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83161. //parent-child relationship. Does this impostor has a parent impostor?
  83162. if (impostor.parent) {
  83163. if (impostor.physicsBody) {
  83164. this.removePhysicsBody(impostor);
  83165. //TODO is that needed?
  83166. impostor.forceUpdate();
  83167. }
  83168. return;
  83169. }
  83170. //should a new body be created for this impostor?
  83171. if (impostor.isBodyInitRequired()) {
  83172. var shape = this._createShape(impostor);
  83173. //unregister events, if body is being changed
  83174. var oldBody = impostor.physicsBody;
  83175. if (oldBody) {
  83176. this.removePhysicsBody(impostor);
  83177. }
  83178. //create the body and material
  83179. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  83180. var bodyCreationObject = {
  83181. mass: impostor.getParam("mass"),
  83182. material: material
  83183. };
  83184. // A simple extend, in case native options were used.
  83185. var nativeOptions = impostor.getParam("nativeOptions");
  83186. for (var key in nativeOptions) {
  83187. if (nativeOptions.hasOwnProperty(key)) {
  83188. bodyCreationObject[key] = nativeOptions[key];
  83189. }
  83190. }
  83191. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  83192. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  83193. this.world.addEventListener("preStep", impostor.beforeStep);
  83194. this.world.addEventListener("postStep", impostor.afterStep);
  83195. impostor.physicsBody.addShape(shape);
  83196. this.world.add(impostor.physicsBody);
  83197. //try to keep the body moving in the right direction by taking old properties.
  83198. //Should be tested!
  83199. if (oldBody) {
  83200. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  83201. impostor.physicsBody[param].copy(oldBody[param]);
  83202. });
  83203. }
  83204. this._processChildMeshes(impostor);
  83205. }
  83206. //now update the body's transformation
  83207. this._updatePhysicsBodyTransformation(impostor);
  83208. };
  83209. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  83210. var _this = this;
  83211. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  83212. var currentRotation = mainImpostor.object.rotationQuaternion;
  83213. if (meshChildren.length) {
  83214. var processMesh = function (localPosition, mesh) {
  83215. if (!currentRotation || !mesh.rotationQuaternion) {
  83216. return;
  83217. }
  83218. var childImpostor = mesh.getPhysicsImpostor();
  83219. if (childImpostor) {
  83220. var parent = childImpostor.parent;
  83221. if (parent !== mainImpostor) {
  83222. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  83223. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  83224. if (childImpostor.physicsBody) {
  83225. _this.removePhysicsBody(childImpostor);
  83226. childImpostor.physicsBody = null;
  83227. }
  83228. childImpostor.parent = mainImpostor;
  83229. childImpostor.resetUpdateFlags();
  83230. 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));
  83231. //Add the mass of the children.
  83232. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  83233. }
  83234. }
  83235. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  83236. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  83237. };
  83238. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  83239. }
  83240. };
  83241. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83242. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  83243. this.world.removeEventListener("preStep", impostor.beforeStep);
  83244. this.world.removeEventListener("postStep", impostor.afterStep);
  83245. this.world.remove(impostor.physicsBody);
  83246. };
  83247. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83248. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83249. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83250. if (!mainBody || !connectedBody) {
  83251. return;
  83252. }
  83253. var constraint;
  83254. var jointData = impostorJoint.joint.jointData;
  83255. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  83256. var constraintData = {
  83257. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  83258. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  83259. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  83260. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  83261. maxForce: jointData.nativeParams.maxForce,
  83262. collideConnected: !!jointData.collision
  83263. };
  83264. switch (impostorJoint.joint.type) {
  83265. case BABYLON.PhysicsJoint.HingeJoint:
  83266. case BABYLON.PhysicsJoint.Hinge2Joint:
  83267. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  83268. break;
  83269. case BABYLON.PhysicsJoint.DistanceJoint:
  83270. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  83271. break;
  83272. case BABYLON.PhysicsJoint.SpringJoint:
  83273. var springData = jointData;
  83274. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  83275. restLength: springData.length,
  83276. stiffness: springData.stiffness,
  83277. damping: springData.damping,
  83278. localAnchorA: constraintData.pivotA,
  83279. localAnchorB: constraintData.pivotB
  83280. });
  83281. break;
  83282. case BABYLON.PhysicsJoint.LockJoint:
  83283. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  83284. break;
  83285. case BABYLON.PhysicsJoint.PointToPointJoint:
  83286. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83287. default:
  83288. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  83289. break;
  83290. }
  83291. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  83292. constraint.collideConnected = !!jointData.collision;
  83293. impostorJoint.joint.physicsJoint = constraint;
  83294. //don't add spring as constraint, as it is not one.
  83295. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  83296. this.world.addConstraint(constraint);
  83297. }
  83298. else {
  83299. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  83300. constraint.applyForce();
  83301. });
  83302. }
  83303. };
  83304. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83305. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  83306. };
  83307. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  83308. var index;
  83309. var mat;
  83310. for (index = 0; index < this._physicsMaterials.length; index++) {
  83311. mat = this._physicsMaterials[index];
  83312. if (mat.friction === friction && mat.restitution === restitution) {
  83313. return mat;
  83314. }
  83315. }
  83316. var currentMat = new this.BJSCANNON.Material(name);
  83317. currentMat.friction = friction;
  83318. currentMat.restitution = restitution;
  83319. this._physicsMaterials.push(currentMat);
  83320. return currentMat;
  83321. };
  83322. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  83323. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  83324. };
  83325. CannonJSPlugin.prototype._createShape = function (impostor) {
  83326. var object = impostor.object;
  83327. var returnValue;
  83328. var extendSize = impostor.getObjectExtendSize();
  83329. switch (impostor.type) {
  83330. case BABYLON.PhysicsImpostor.SphereImpostor:
  83331. var radiusX = extendSize.x;
  83332. var radiusY = extendSize.y;
  83333. var radiusZ = extendSize.z;
  83334. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  83335. break;
  83336. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  83337. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83338. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  83339. break;
  83340. case BABYLON.PhysicsImpostor.BoxImpostor:
  83341. var box = extendSize.scale(0.5);
  83342. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  83343. break;
  83344. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83345. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  83346. returnValue = new this.BJSCANNON.Plane();
  83347. break;
  83348. case BABYLON.PhysicsImpostor.MeshImpostor:
  83349. // should transform the vertex data to world coordinates!!
  83350. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  83351. var rawFaces = object.getIndices ? object.getIndices() : [];
  83352. if (!rawVerts)
  83353. return;
  83354. // get only scale! so the object could transform correctly.
  83355. var oldPosition = object.position.clone();
  83356. var oldRotation = object.rotation && object.rotation.clone();
  83357. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  83358. object.position.copyFromFloats(0, 0, 0);
  83359. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83360. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83361. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83362. var transform = object.computeWorldMatrix(true);
  83363. // convert rawVerts to object space
  83364. var temp = new Array();
  83365. var index;
  83366. for (index = 0; index < rawVerts.length; index += 3) {
  83367. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  83368. }
  83369. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  83370. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  83371. //now set back the transformation!
  83372. object.position.copyFrom(oldPosition);
  83373. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  83374. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  83375. break;
  83376. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  83377. var oldPosition2 = object.position.clone();
  83378. var oldRotation2 = object.rotation && object.rotation.clone();
  83379. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  83380. object.position.copyFromFloats(0, 0, 0);
  83381. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  83382. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  83383. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  83384. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  83385. returnValue = this._createHeightmap(object);
  83386. object.position.copyFrom(oldPosition2);
  83387. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  83388. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  83389. object.computeWorldMatrix(true);
  83390. break;
  83391. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83392. returnValue = new this.BJSCANNON.Particle();
  83393. break;
  83394. }
  83395. return returnValue;
  83396. };
  83397. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  83398. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  83399. var transform = object.computeWorldMatrix(true);
  83400. // convert rawVerts to object space
  83401. var temp = new Array();
  83402. var index;
  83403. for (index = 0; index < pos.length; index += 3) {
  83404. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  83405. }
  83406. pos = temp;
  83407. var matrix = new Array();
  83408. //For now pointDepth will not be used and will be automatically calculated.
  83409. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  83410. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  83411. var boundingInfo = object.getBoundingInfo();
  83412. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  83413. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  83414. var elementSize = dim * 2 / arraySize;
  83415. for (var i = 0; i < pos.length; i = i + 3) {
  83416. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  83417. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  83418. var y = -pos[i + 2] + minY;
  83419. if (!matrix[x]) {
  83420. matrix[x] = [];
  83421. }
  83422. if (!matrix[x][z]) {
  83423. matrix[x][z] = y;
  83424. }
  83425. matrix[x][z] = Math.max(y, matrix[x][z]);
  83426. }
  83427. for (var x = 0; x <= arraySize; ++x) {
  83428. if (!matrix[x]) {
  83429. var loc = 1;
  83430. while (!matrix[(x + loc) % arraySize]) {
  83431. loc++;
  83432. }
  83433. matrix[x] = matrix[(x + loc) % arraySize].slice();
  83434. //console.log("missing x", x);
  83435. }
  83436. for (var z = 0; z <= arraySize; ++z) {
  83437. if (!matrix[x][z]) {
  83438. var loc = 1;
  83439. var newValue;
  83440. while (newValue === undefined) {
  83441. newValue = matrix[x][(z + loc++) % arraySize];
  83442. }
  83443. matrix[x][z] = newValue;
  83444. }
  83445. }
  83446. }
  83447. var shape = new this.BJSCANNON.Heightfield(matrix, {
  83448. elementSize: elementSize
  83449. });
  83450. //For future reference, needed for body transformation
  83451. shape.minY = minY;
  83452. return shape;
  83453. };
  83454. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  83455. var object = impostor.object;
  83456. //make sure it is updated...
  83457. object.computeWorldMatrix && object.computeWorldMatrix(true);
  83458. // The delta between the mesh position and the mesh bounding box center
  83459. var bInfo = object.getBoundingInfo();
  83460. if (!bInfo)
  83461. return;
  83462. var center = impostor.getObjectCenter();
  83463. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  83464. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  83465. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  83466. this._tmpPosition.copyFrom(center);
  83467. var quaternion = object.rotationQuaternion;
  83468. if (!quaternion) {
  83469. return;
  83470. }
  83471. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  83472. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  83473. //-90 DEG in X, precalculated
  83474. quaternion = quaternion.multiply(this._minus90X);
  83475. //Invert! (Precalculated, 90 deg in X)
  83476. //No need to clone. this will never change.
  83477. impostor.setDeltaRotation(this._plus90X);
  83478. }
  83479. //If it is a heightfield, if should be centered.
  83480. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  83481. var mesh = object;
  83482. var boundingInfo = mesh.getBoundingInfo();
  83483. //calculate the correct body position:
  83484. var rotationQuaternion = mesh.rotationQuaternion;
  83485. mesh.rotationQuaternion = this._tmpUnityRotation;
  83486. mesh.computeWorldMatrix(true);
  83487. //get original center with no rotation
  83488. var c = center.clone();
  83489. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  83490. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  83491. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  83492. mesh.setPreTransformMatrix(p);
  83493. mesh.computeWorldMatrix(true);
  83494. //calculate the translation
  83495. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  83496. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  83497. //add it inverted to the delta
  83498. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  83499. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  83500. //rotation is back
  83501. mesh.rotationQuaternion = rotationQuaternion;
  83502. mesh.setPreTransformMatrix(oldPivot);
  83503. mesh.computeWorldMatrix(true);
  83504. }
  83505. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  83506. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  83507. //this._tmpPosition.copyFrom(object.position);
  83508. }
  83509. impostor.setDeltaPosition(this._tmpDeltaPosition);
  83510. //Now update the impostor object
  83511. impostor.physicsBody.position.copy(this._tmpPosition);
  83512. impostor.physicsBody.quaternion.copy(quaternion);
  83513. };
  83514. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83515. impostor.object.position.copyFrom(impostor.physicsBody.position);
  83516. if (impostor.object.rotationQuaternion) {
  83517. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  83518. }
  83519. };
  83520. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83521. impostor.physicsBody.position.copy(newPosition);
  83522. impostor.physicsBody.quaternion.copy(newRotation);
  83523. };
  83524. CannonJSPlugin.prototype.isSupported = function () {
  83525. return this.BJSCANNON !== undefined;
  83526. };
  83527. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83528. impostor.physicsBody.velocity.copy(velocity);
  83529. };
  83530. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83531. impostor.physicsBody.angularVelocity.copy(velocity);
  83532. };
  83533. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83534. var v = impostor.physicsBody.velocity;
  83535. if (!v) {
  83536. return null;
  83537. }
  83538. return new BABYLON.Vector3(v.x, v.y, v.z);
  83539. };
  83540. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83541. var v = impostor.physicsBody.angularVelocity;
  83542. if (!v) {
  83543. return null;
  83544. }
  83545. return new BABYLON.Vector3(v.x, v.y, v.z);
  83546. };
  83547. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83548. impostor.physicsBody.mass = mass;
  83549. impostor.physicsBody.updateMassProperties();
  83550. };
  83551. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  83552. return impostor.physicsBody.mass;
  83553. };
  83554. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  83555. return impostor.physicsBody.material.friction;
  83556. };
  83557. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83558. impostor.physicsBody.material.friction = friction;
  83559. };
  83560. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  83561. return impostor.physicsBody.material.restitution;
  83562. };
  83563. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  83564. impostor.physicsBody.material.restitution = restitution;
  83565. };
  83566. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  83567. impostor.physicsBody.sleep();
  83568. };
  83569. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  83570. impostor.physicsBody.wakeUp();
  83571. };
  83572. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  83573. joint.physicsJoint.distance = maxDistance;
  83574. };
  83575. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83576. // if (!motorIndex) {
  83577. // joint.physicsJoint.enableMotor();
  83578. // }
  83579. // }
  83580. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  83581. // if (!motorIndex) {
  83582. // joint.physicsJoint.disableMotor();
  83583. // }
  83584. // }
  83585. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  83586. if (!motorIndex) {
  83587. joint.physicsJoint.enableMotor();
  83588. joint.physicsJoint.setMotorSpeed(speed);
  83589. if (maxForce) {
  83590. this.setLimit(joint, maxForce);
  83591. }
  83592. }
  83593. };
  83594. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  83595. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  83596. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  83597. };
  83598. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  83599. var body = impostor.physicsBody;
  83600. mesh.position.x = body.position.x;
  83601. mesh.position.y = body.position.y;
  83602. mesh.position.z = body.position.z;
  83603. if (mesh.rotationQuaternion) {
  83604. mesh.rotationQuaternion.x = body.quaternion.x;
  83605. mesh.rotationQuaternion.y = body.quaternion.y;
  83606. mesh.rotationQuaternion.z = body.quaternion.z;
  83607. mesh.rotationQuaternion.w = body.quaternion.w;
  83608. }
  83609. };
  83610. CannonJSPlugin.prototype.getRadius = function (impostor) {
  83611. var shape = impostor.physicsBody.shapes[0];
  83612. return shape.boundingSphereRadius;
  83613. };
  83614. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  83615. var shape = impostor.physicsBody.shapes[0];
  83616. result.x = shape.halfExtents.x * 2;
  83617. result.y = shape.halfExtents.y * 2;
  83618. result.z = shape.halfExtents.z * 2;
  83619. };
  83620. CannonJSPlugin.prototype.dispose = function () {
  83621. };
  83622. CannonJSPlugin.prototype._extendNamespace = function () {
  83623. //this will force cannon to execute at least one step when using interpolation
  83624. var step_tmp1 = new this.BJSCANNON.Vec3();
  83625. var Engine = this.BJSCANNON;
  83626. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  83627. maxSubSteps = maxSubSteps || 10;
  83628. timeSinceLastCalled = timeSinceLastCalled || 0;
  83629. if (timeSinceLastCalled === 0) {
  83630. this.internalStep(dt);
  83631. this.time += dt;
  83632. }
  83633. else {
  83634. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  83635. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  83636. var t0 = performance.now();
  83637. for (var i = 0; i !== internalSteps; i++) {
  83638. this.internalStep(dt);
  83639. if (performance.now() - t0 > dt * 1000) {
  83640. break;
  83641. }
  83642. }
  83643. this.time += timeSinceLastCalled;
  83644. var h = this.time % dt;
  83645. var h_div_dt = h / dt;
  83646. var interpvelo = step_tmp1;
  83647. var bodies = this.bodies;
  83648. for (var j = 0; j !== bodies.length; j++) {
  83649. var b = bodies[j];
  83650. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  83651. b.position.vsub(b.previousPosition, interpvelo);
  83652. interpvelo.scale(h_div_dt, interpvelo);
  83653. b.position.vadd(interpvelo, b.interpolatedPosition);
  83654. }
  83655. else {
  83656. b.interpolatedPosition.copy(b.position);
  83657. b.interpolatedQuaternion.copy(b.quaternion);
  83658. }
  83659. }
  83660. }
  83661. };
  83662. };
  83663. return CannonJSPlugin;
  83664. }());
  83665. BABYLON.CannonJSPlugin = CannonJSPlugin;
  83666. })(BABYLON || (BABYLON = {}));
  83667. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  83668. var BABYLON;
  83669. (function (BABYLON) {
  83670. var OimoJSPlugin = /** @class */ (function () {
  83671. function OimoJSPlugin(iterations) {
  83672. this.name = "OimoJSPlugin";
  83673. this._tmpImpostorsArray = [];
  83674. this._tmpPositionVector = BABYLON.Vector3.Zero();
  83675. this.BJSOIMO = OIMO;
  83676. this.world = new this.BJSOIMO.World({
  83677. iterations: iterations
  83678. });
  83679. this.world.clear();
  83680. }
  83681. OimoJSPlugin.prototype.setGravity = function (gravity) {
  83682. this.world.gravity.copy(gravity);
  83683. };
  83684. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  83685. this.world.timeStep = timeStep;
  83686. };
  83687. OimoJSPlugin.prototype.getTimeStep = function () {
  83688. return this.world.timeStep;
  83689. };
  83690. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  83691. var _this = this;
  83692. impostors.forEach(function (impostor) {
  83693. impostor.beforeStep();
  83694. });
  83695. this.world.step();
  83696. impostors.forEach(function (impostor) {
  83697. impostor.afterStep();
  83698. //update the ordered impostors array
  83699. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  83700. });
  83701. //check for collisions
  83702. var contact = this.world.contacts;
  83703. while (contact !== null) {
  83704. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  83705. contact = contact.next;
  83706. continue;
  83707. }
  83708. //is this body colliding with any other? get the impostor
  83709. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  83710. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  83711. if (!mainImpostor || !collidingImpostor) {
  83712. contact = contact.next;
  83713. continue;
  83714. }
  83715. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  83716. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  83717. contact = contact.next;
  83718. }
  83719. };
  83720. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  83721. var mass = impostor.physicsBody.mass;
  83722. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  83723. };
  83724. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  83725. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  83726. this.applyImpulse(impostor, force, contactPoint);
  83727. };
  83728. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  83729. var _this = this;
  83730. //parent-child relationship. Does this impostor has a parent impostor?
  83731. if (impostor.parent) {
  83732. if (impostor.physicsBody) {
  83733. this.removePhysicsBody(impostor);
  83734. //TODO is that needed?
  83735. impostor.forceUpdate();
  83736. }
  83737. return;
  83738. }
  83739. if (impostor.isBodyInitRequired()) {
  83740. var bodyConfig = {
  83741. name: impostor.uniqueId,
  83742. //Oimo must have mass, also for static objects.
  83743. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  83744. size: [],
  83745. type: [],
  83746. pos: [],
  83747. posShape: [],
  83748. rot: [],
  83749. rotShape: [],
  83750. move: impostor.getParam("mass") !== 0,
  83751. density: impostor.getParam("mass"),
  83752. friction: impostor.getParam("friction"),
  83753. restitution: impostor.getParam("restitution"),
  83754. //Supporting older versions of Oimo
  83755. world: this.world
  83756. };
  83757. var impostors = [impostor];
  83758. var addToArray = function (parent) {
  83759. if (!parent.getChildMeshes)
  83760. return;
  83761. parent.getChildMeshes().forEach(function (m) {
  83762. if (m.physicsImpostor) {
  83763. impostors.push(m.physicsImpostor);
  83764. //m.physicsImpostor._init();
  83765. }
  83766. });
  83767. };
  83768. addToArray(impostor.object);
  83769. var checkWithEpsilon_1 = function (value) {
  83770. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  83771. };
  83772. impostors.forEach(function (i) {
  83773. if (!i.object.rotationQuaternion) {
  83774. return;
  83775. }
  83776. //get the correct bounding box
  83777. var oldQuaternion = i.object.rotationQuaternion;
  83778. var rot = oldQuaternion.toEulerAngles();
  83779. var extendSize = i.getObjectExtendSize();
  83780. var radToDeg = 57.295779513082320876;
  83781. if (i === impostor) {
  83782. var center = impostor.getObjectCenter();
  83783. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  83784. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  83785. //Can also use Array.prototype.push.apply
  83786. bodyConfig.pos.push(center.x);
  83787. bodyConfig.pos.push(center.y);
  83788. bodyConfig.pos.push(center.z);
  83789. bodyConfig.posShape.push(0, 0, 0);
  83790. //tmp solution
  83791. bodyConfig.rot.push(rot.x * radToDeg);
  83792. bodyConfig.rot.push(rot.y * radToDeg);
  83793. bodyConfig.rot.push(rot.z * radToDeg);
  83794. bodyConfig.rotShape.push(0, 0, 0);
  83795. }
  83796. else {
  83797. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  83798. bodyConfig.posShape.push(localPosition.x);
  83799. bodyConfig.posShape.push(localPosition.y);
  83800. bodyConfig.posShape.push(localPosition.z);
  83801. bodyConfig.pos.push(0, 0, 0);
  83802. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  83803. bodyConfig.rot.push(0);
  83804. bodyConfig.rot.push(0);
  83805. bodyConfig.rot.push(0);
  83806. bodyConfig.rotShape.push(rot.x * radToDeg);
  83807. bodyConfig.rotShape.push(rot.y * radToDeg);
  83808. bodyConfig.rotShape.push(rot.z * radToDeg);
  83809. }
  83810. // register mesh
  83811. switch (i.type) {
  83812. case BABYLON.PhysicsImpostor.ParticleImpostor:
  83813. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  83814. case BABYLON.PhysicsImpostor.SphereImpostor:
  83815. var radiusX = extendSize.x;
  83816. var radiusY = extendSize.y;
  83817. var radiusZ = extendSize.z;
  83818. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  83819. bodyConfig.type.push('sphere');
  83820. //due to the way oimo works with compounds, add 3 times
  83821. bodyConfig.size.push(size);
  83822. bodyConfig.size.push(size);
  83823. bodyConfig.size.push(size);
  83824. break;
  83825. case BABYLON.PhysicsImpostor.CylinderImpostor:
  83826. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  83827. var sizeY = checkWithEpsilon_1(extendSize.y);
  83828. bodyConfig.type.push('cylinder');
  83829. bodyConfig.size.push(sizeX);
  83830. bodyConfig.size.push(sizeY);
  83831. //due to the way oimo works with compounds, add one more value.
  83832. bodyConfig.size.push(sizeY);
  83833. break;
  83834. case BABYLON.PhysicsImpostor.PlaneImpostor:
  83835. case BABYLON.PhysicsImpostor.BoxImpostor:
  83836. default:
  83837. var sizeX = checkWithEpsilon_1(extendSize.x);
  83838. var sizeY = checkWithEpsilon_1(extendSize.y);
  83839. var sizeZ = checkWithEpsilon_1(extendSize.z);
  83840. bodyConfig.type.push('box');
  83841. //if (i === impostor) {
  83842. bodyConfig.size.push(sizeX);
  83843. bodyConfig.size.push(sizeY);
  83844. bodyConfig.size.push(sizeZ);
  83845. //} else {
  83846. // bodyConfig.size.push(0,0,0);
  83847. //}
  83848. break;
  83849. }
  83850. //actually not needed, but hey...
  83851. i.object.rotationQuaternion = oldQuaternion;
  83852. });
  83853. impostor.physicsBody = this.world.add(bodyConfig);
  83854. }
  83855. else {
  83856. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  83857. }
  83858. impostor.setDeltaPosition(this._tmpPositionVector);
  83859. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  83860. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  83861. };
  83862. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  83863. //impostor.physicsBody.dispose();
  83864. //Same as : (older oimo versions)
  83865. this.world.removeRigidBody(impostor.physicsBody);
  83866. };
  83867. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  83868. var mainBody = impostorJoint.mainImpostor.physicsBody;
  83869. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  83870. if (!mainBody || !connectedBody) {
  83871. return;
  83872. }
  83873. var jointData = impostorJoint.joint.jointData;
  83874. var options = jointData.nativeParams || {};
  83875. var type;
  83876. var nativeJointData = {
  83877. body1: mainBody,
  83878. body2: connectedBody,
  83879. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  83880. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  83881. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  83882. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  83883. min: options.min,
  83884. max: options.max,
  83885. collision: options.collision || jointData.collision,
  83886. spring: options.spring,
  83887. //supporting older version of Oimo
  83888. world: this.world
  83889. };
  83890. switch (impostorJoint.joint.type) {
  83891. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  83892. type = "jointBall";
  83893. break;
  83894. case BABYLON.PhysicsJoint.SpringJoint:
  83895. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  83896. var springData = jointData;
  83897. nativeJointData.min = springData.length || nativeJointData.min;
  83898. //Max should also be set, just make sure it is at least min
  83899. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  83900. case BABYLON.PhysicsJoint.DistanceJoint:
  83901. type = "jointDistance";
  83902. nativeJointData.max = jointData.maxDistance;
  83903. break;
  83904. case BABYLON.PhysicsJoint.PrismaticJoint:
  83905. type = "jointPrisme";
  83906. break;
  83907. case BABYLON.PhysicsJoint.SliderJoint:
  83908. type = "jointSlide";
  83909. break;
  83910. case BABYLON.PhysicsJoint.WheelJoint:
  83911. type = "jointWheel";
  83912. break;
  83913. case BABYLON.PhysicsJoint.HingeJoint:
  83914. default:
  83915. type = "jointHinge";
  83916. break;
  83917. }
  83918. nativeJointData.type = type;
  83919. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  83920. };
  83921. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  83922. //Bug in Oimo prevents us from disposing a joint in the playground
  83923. //joint.joint.physicsJoint.dispose();
  83924. //So we will bruteforce it!
  83925. try {
  83926. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  83927. }
  83928. catch (e) {
  83929. BABYLON.Tools.Warn(e);
  83930. }
  83931. };
  83932. OimoJSPlugin.prototype.isSupported = function () {
  83933. return this.BJSOIMO !== undefined;
  83934. };
  83935. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  83936. if (!impostor.physicsBody.sleeping) {
  83937. //TODO check that
  83938. /*if (impostor.physicsBody.shapes.next) {
  83939. var parentShape = this._getLastShape(impostor.physicsBody);
  83940. impostor.object.position.copyFrom(parentShape.position);
  83941. console.log(parentShape.position);
  83942. } else {*/
  83943. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  83944. //}
  83945. if (impostor.object.rotationQuaternion) {
  83946. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  83947. }
  83948. }
  83949. };
  83950. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  83951. var body = impostor.physicsBody;
  83952. body.position.copy(newPosition);
  83953. body.orientation.copy(newRotation);
  83954. body.syncShapes();
  83955. body.awake();
  83956. };
  83957. /*private _getLastShape(body: any): any {
  83958. var lastShape = body.shapes;
  83959. while (lastShape.next) {
  83960. lastShape = lastShape.next;
  83961. }
  83962. return lastShape;
  83963. }*/
  83964. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  83965. impostor.physicsBody.linearVelocity.init(velocity.x, velocity.y, velocity.z);
  83966. };
  83967. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  83968. impostor.physicsBody.angularVelocity.init(velocity.x, velocity.y, velocity.z);
  83969. };
  83970. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  83971. var v = impostor.physicsBody.linearVelocity;
  83972. if (!v) {
  83973. return null;
  83974. }
  83975. return new BABYLON.Vector3(v.x, v.y, v.z);
  83976. };
  83977. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  83978. var v = impostor.physicsBody.angularVelocity;
  83979. if (!v) {
  83980. return null;
  83981. }
  83982. return new BABYLON.Vector3(v.x, v.y, v.z);
  83983. };
  83984. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  83985. var staticBody = mass === 0;
  83986. //this will actually set the body's density and not its mass.
  83987. //But this is how oimo treats the mass variable.
  83988. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  83989. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  83990. };
  83991. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  83992. return impostor.physicsBody.shapes.density;
  83993. };
  83994. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  83995. return impostor.physicsBody.shapes.friction;
  83996. };
  83997. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  83998. impostor.physicsBody.shapes.friction = friction;
  83999. };
  84000. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  84001. return impostor.physicsBody.shapes.restitution;
  84002. };
  84003. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  84004. impostor.physicsBody.shapes.restitution = restitution;
  84005. };
  84006. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  84007. impostor.physicsBody.sleep();
  84008. };
  84009. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  84010. impostor.physicsBody.awake();
  84011. };
  84012. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  84013. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  84014. if (minDistance !== void 0) {
  84015. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  84016. }
  84017. };
  84018. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  84019. //TODO separate rotational and transational motors.
  84020. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84021. if (motor) {
  84022. motor.setMotor(speed, maxForce);
  84023. }
  84024. };
  84025. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  84026. //TODO separate rotational and transational motors.
  84027. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  84028. if (motor) {
  84029. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  84030. }
  84031. };
  84032. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  84033. var body = impostor.physicsBody;
  84034. mesh.position.x = body.position.x;
  84035. mesh.position.y = body.position.y;
  84036. mesh.position.z = body.position.z;
  84037. if (mesh.rotationQuaternion) {
  84038. mesh.rotationQuaternion.x = body.orientation.x;
  84039. mesh.rotationQuaternion.y = body.orientation.y;
  84040. mesh.rotationQuaternion.z = body.orientation.z;
  84041. mesh.rotationQuaternion.w = body.orientation.s;
  84042. }
  84043. };
  84044. OimoJSPlugin.prototype.getRadius = function (impostor) {
  84045. return impostor.physicsBody.shapes.radius;
  84046. };
  84047. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  84048. var shape = impostor.physicsBody.shapes;
  84049. result.x = shape.halfWidth * 2;
  84050. result.y = shape.halfHeight * 2;
  84051. result.z = shape.halfDepth * 2;
  84052. };
  84053. OimoJSPlugin.prototype.dispose = function () {
  84054. this.world.clear();
  84055. };
  84056. return OimoJSPlugin;
  84057. }());
  84058. BABYLON.OimoJSPlugin = OimoJSPlugin;
  84059. })(BABYLON || (BABYLON = {}));
  84060. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  84061. var BABYLON;
  84062. (function (BABYLON) {
  84063. /*
  84064. * Based on jsTGALoader - Javascript loader for TGA file
  84065. * By Vincent Thibault
  84066. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  84067. */
  84068. var TGATools = /** @class */ (function () {
  84069. function TGATools() {
  84070. }
  84071. TGATools.GetTGAHeader = function (data) {
  84072. var offset = 0;
  84073. var header = {
  84074. id_length: data[offset++],
  84075. colormap_type: data[offset++],
  84076. image_type: data[offset++],
  84077. colormap_index: data[offset++] | data[offset++] << 8,
  84078. colormap_length: data[offset++] | data[offset++] << 8,
  84079. colormap_size: data[offset++],
  84080. origin: [
  84081. data[offset++] | data[offset++] << 8,
  84082. data[offset++] | data[offset++] << 8
  84083. ],
  84084. width: data[offset++] | data[offset++] << 8,
  84085. height: data[offset++] | data[offset++] << 8,
  84086. pixel_size: data[offset++],
  84087. flags: data[offset++]
  84088. };
  84089. return header;
  84090. };
  84091. TGATools.UploadContent = function (gl, data) {
  84092. // Not enough data to contain header ?
  84093. if (data.length < 19) {
  84094. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  84095. return;
  84096. }
  84097. // Read Header
  84098. var offset = 18;
  84099. var header = TGATools.GetTGAHeader(data);
  84100. // Assume it's a valid Targa file.
  84101. if (header.id_length + offset > data.length) {
  84102. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  84103. return;
  84104. }
  84105. // Skip not needed data
  84106. offset += header.id_length;
  84107. var use_rle = false;
  84108. var use_pal = false;
  84109. var use_grey = false;
  84110. // Get some informations.
  84111. switch (header.image_type) {
  84112. case TGATools._TYPE_RLE_INDEXED:
  84113. use_rle = true;
  84114. case TGATools._TYPE_INDEXED:
  84115. use_pal = true;
  84116. break;
  84117. case TGATools._TYPE_RLE_RGB:
  84118. use_rle = true;
  84119. case TGATools._TYPE_RGB:
  84120. // use_rgb = true;
  84121. break;
  84122. case TGATools._TYPE_RLE_GREY:
  84123. use_rle = true;
  84124. case TGATools._TYPE_GREY:
  84125. use_grey = true;
  84126. break;
  84127. }
  84128. var pixel_data;
  84129. // var numAlphaBits = header.flags & 0xf;
  84130. var pixel_size = header.pixel_size >> 3;
  84131. var pixel_total = header.width * header.height * pixel_size;
  84132. // Read palettes
  84133. var palettes;
  84134. if (use_pal) {
  84135. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  84136. }
  84137. // Read LRE
  84138. if (use_rle) {
  84139. pixel_data = new Uint8Array(pixel_total);
  84140. var c, count, i;
  84141. var localOffset = 0;
  84142. var pixels = new Uint8Array(pixel_size);
  84143. while (offset < pixel_total && localOffset < pixel_total) {
  84144. c = data[offset++];
  84145. count = (c & 0x7f) + 1;
  84146. // RLE pixels
  84147. if (c & 0x80) {
  84148. // Bind pixel tmp array
  84149. for (i = 0; i < pixel_size; ++i) {
  84150. pixels[i] = data[offset++];
  84151. }
  84152. // Copy pixel array
  84153. for (i = 0; i < count; ++i) {
  84154. pixel_data.set(pixels, localOffset + i * pixel_size);
  84155. }
  84156. localOffset += pixel_size * count;
  84157. }
  84158. // Raw pixels
  84159. else {
  84160. count *= pixel_size;
  84161. for (i = 0; i < count; ++i) {
  84162. pixel_data[localOffset + i] = data[offset++];
  84163. }
  84164. localOffset += count;
  84165. }
  84166. }
  84167. }
  84168. // RAW Pixels
  84169. else {
  84170. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  84171. }
  84172. // Load to texture
  84173. var x_start, y_start, x_step, y_step, y_end, x_end;
  84174. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  84175. default:
  84176. case TGATools._ORIGIN_UL:
  84177. x_start = 0;
  84178. x_step = 1;
  84179. x_end = header.width;
  84180. y_start = 0;
  84181. y_step = 1;
  84182. y_end = header.height;
  84183. break;
  84184. case TGATools._ORIGIN_BL:
  84185. x_start = 0;
  84186. x_step = 1;
  84187. x_end = header.width;
  84188. y_start = header.height - 1;
  84189. y_step = -1;
  84190. y_end = -1;
  84191. break;
  84192. case TGATools._ORIGIN_UR:
  84193. x_start = header.width - 1;
  84194. x_step = -1;
  84195. x_end = -1;
  84196. y_start = 0;
  84197. y_step = 1;
  84198. y_end = header.height;
  84199. break;
  84200. case TGATools._ORIGIN_BR:
  84201. x_start = header.width - 1;
  84202. x_step = -1;
  84203. x_end = -1;
  84204. y_start = header.height - 1;
  84205. y_step = -1;
  84206. y_end = -1;
  84207. break;
  84208. }
  84209. // Load the specify method
  84210. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  84211. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  84212. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  84213. };
  84214. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84215. var image = pixel_data, colormap = palettes;
  84216. var width = header.width, height = header.height;
  84217. var color, i = 0, x, y;
  84218. var imageData = new Uint8Array(width * height * 4);
  84219. for (y = y_start; y !== y_end; y += y_step) {
  84220. for (x = x_start; x !== x_end; x += x_step, i++) {
  84221. color = image[i];
  84222. imageData[(x + width * y) * 4 + 3] = 255;
  84223. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  84224. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  84225. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  84226. }
  84227. }
  84228. return imageData;
  84229. };
  84230. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84231. var image = pixel_data;
  84232. var width = header.width, height = header.height;
  84233. var color, i = 0, x, y;
  84234. var imageData = new Uint8Array(width * height * 4);
  84235. for (y = y_start; y !== y_end; y += y_step) {
  84236. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84237. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  84238. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  84239. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  84240. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  84241. imageData[(x + width * y) * 4 + 0] = r;
  84242. imageData[(x + width * y) * 4 + 1] = g;
  84243. imageData[(x + width * y) * 4 + 2] = b;
  84244. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  84245. }
  84246. }
  84247. return imageData;
  84248. };
  84249. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84250. var image = pixel_data;
  84251. var width = header.width, height = header.height;
  84252. var i = 0, x, y;
  84253. var imageData = new Uint8Array(width * height * 4);
  84254. for (y = y_start; y !== y_end; y += y_step) {
  84255. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  84256. imageData[(x + width * y) * 4 + 3] = 255;
  84257. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84258. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84259. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84260. }
  84261. }
  84262. return imageData;
  84263. };
  84264. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84265. var image = pixel_data;
  84266. var width = header.width, height = header.height;
  84267. var i = 0, x, y;
  84268. var imageData = new Uint8Array(width * height * 4);
  84269. for (y = y_start; y !== y_end; y += y_step) {
  84270. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  84271. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84272. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  84273. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  84274. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  84275. }
  84276. }
  84277. return imageData;
  84278. };
  84279. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84280. var image = pixel_data;
  84281. var width = header.width, height = header.height;
  84282. var color, i = 0, x, y;
  84283. var imageData = new Uint8Array(width * height * 4);
  84284. for (y = y_start; y !== y_end; y += y_step) {
  84285. for (x = x_start; x !== x_end; x += x_step, i++) {
  84286. color = image[i];
  84287. imageData[(x + width * y) * 4 + 0] = color;
  84288. imageData[(x + width * y) * 4 + 1] = color;
  84289. imageData[(x + width * y) * 4 + 2] = color;
  84290. imageData[(x + width * y) * 4 + 3] = 255;
  84291. }
  84292. }
  84293. return imageData;
  84294. };
  84295. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  84296. var image = pixel_data;
  84297. var width = header.width, height = header.height;
  84298. var i = 0, x, y;
  84299. var imageData = new Uint8Array(width * height * 4);
  84300. for (y = y_start; y !== y_end; y += y_step) {
  84301. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  84302. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  84303. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  84304. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  84305. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  84306. }
  84307. }
  84308. return imageData;
  84309. };
  84310. //private static _TYPE_NO_DATA = 0;
  84311. TGATools._TYPE_INDEXED = 1;
  84312. TGATools._TYPE_RGB = 2;
  84313. TGATools._TYPE_GREY = 3;
  84314. TGATools._TYPE_RLE_INDEXED = 9;
  84315. TGATools._TYPE_RLE_RGB = 10;
  84316. TGATools._TYPE_RLE_GREY = 11;
  84317. TGATools._ORIGIN_MASK = 0x30;
  84318. TGATools._ORIGIN_SHIFT = 0x04;
  84319. TGATools._ORIGIN_BL = 0x00;
  84320. TGATools._ORIGIN_BR = 0x01;
  84321. TGATools._ORIGIN_UL = 0x02;
  84322. TGATools._ORIGIN_UR = 0x03;
  84323. return TGATools;
  84324. }());
  84325. BABYLON.TGATools = TGATools;
  84326. })(BABYLON || (BABYLON = {}));
  84327. //# sourceMappingURL=babylon.tga.js.map
  84328. var BABYLON;
  84329. (function (BABYLON) {
  84330. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  84331. // All values and structures referenced from:
  84332. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  84333. var DDS_MAGIC = 0x20534444;
  84334. var
  84335. //DDSD_CAPS = 0x1,
  84336. //DDSD_HEIGHT = 0x2,
  84337. //DDSD_WIDTH = 0x4,
  84338. //DDSD_PITCH = 0x8,
  84339. //DDSD_PIXELFORMAT = 0x1000,
  84340. DDSD_MIPMAPCOUNT = 0x20000;
  84341. //DDSD_LINEARSIZE = 0x80000,
  84342. //DDSD_DEPTH = 0x800000;
  84343. // var DDSCAPS_COMPLEX = 0x8,
  84344. // DDSCAPS_MIPMAP = 0x400000,
  84345. // DDSCAPS_TEXTURE = 0x1000;
  84346. var DDSCAPS2_CUBEMAP = 0x200;
  84347. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  84348. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  84349. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  84350. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  84351. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  84352. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  84353. // DDSCAPS2_VOLUME = 0x200000;
  84354. var
  84355. //DDPF_ALPHAPIXELS = 0x1,
  84356. //DDPF_ALPHA = 0x2,
  84357. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  84358. //DDPF_YUV = 0x200,
  84359. DDPF_LUMINANCE = 0x20000;
  84360. function FourCCToInt32(value) {
  84361. return value.charCodeAt(0) +
  84362. (value.charCodeAt(1) << 8) +
  84363. (value.charCodeAt(2) << 16) +
  84364. (value.charCodeAt(3) << 24);
  84365. }
  84366. function Int32ToFourCC(value) {
  84367. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  84368. }
  84369. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  84370. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  84371. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  84372. var FOURCC_DX10 = FourCCToInt32("DX10");
  84373. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  84374. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  84375. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  84376. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  84377. var headerLengthInt = 31; // The header length in 32 bit ints
  84378. // Offsets into the header array
  84379. var off_magic = 0;
  84380. var off_size = 1;
  84381. var off_flags = 2;
  84382. var off_height = 3;
  84383. var off_width = 4;
  84384. var off_mipmapCount = 7;
  84385. var off_pfFlags = 20;
  84386. var off_pfFourCC = 21;
  84387. var off_RGBbpp = 22;
  84388. var off_RMask = 23;
  84389. var off_GMask = 24;
  84390. var off_BMask = 25;
  84391. var off_AMask = 26;
  84392. // var off_caps1 = 27;
  84393. var off_caps2 = 28;
  84394. // var off_caps3 = 29;
  84395. // var off_caps4 = 30;
  84396. var off_dxgiFormat = 32;
  84397. ;
  84398. var DDSTools = /** @class */ (function () {
  84399. function DDSTools() {
  84400. }
  84401. DDSTools.GetDDSInfo = function (arrayBuffer) {
  84402. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84403. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  84404. var mipmapCount = 1;
  84405. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  84406. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84407. }
  84408. var fourCC = header[off_pfFourCC];
  84409. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  84410. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84411. switch (fourCC) {
  84412. case FOURCC_D3DFMT_R16G16B16A16F:
  84413. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84414. break;
  84415. case FOURCC_D3DFMT_R32G32B32A32F:
  84416. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84417. break;
  84418. case FOURCC_DX10:
  84419. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  84420. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  84421. break;
  84422. }
  84423. }
  84424. return {
  84425. width: header[off_width],
  84426. height: header[off_height],
  84427. mipmapCount: mipmapCount,
  84428. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  84429. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  84430. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  84431. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  84432. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  84433. dxgiFormat: dxgiFormat,
  84434. textureType: textureType
  84435. };
  84436. };
  84437. DDSTools._ToHalfFloat = function (value) {
  84438. if (!DDSTools._FloatView) {
  84439. DDSTools._FloatView = new Float32Array(1);
  84440. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  84441. }
  84442. DDSTools._FloatView[0] = value;
  84443. var x = DDSTools._Int32View[0];
  84444. var bits = (x >> 16) & 0x8000; /* Get the sign */
  84445. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  84446. var e = (x >> 23) & 0xff; /* Using int is faster here */
  84447. /* If zero, or denormal, or exponent underflows too much for a denormal
  84448. * half, return signed zero. */
  84449. if (e < 103) {
  84450. return bits;
  84451. }
  84452. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  84453. if (e > 142) {
  84454. bits |= 0x7c00;
  84455. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  84456. * not Inf, so make sure we set one mantissa bit too. */
  84457. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  84458. return bits;
  84459. }
  84460. /* If exponent underflows but not too much, return a denormal */
  84461. if (e < 113) {
  84462. m |= 0x0800;
  84463. /* Extra rounding may overflow and set mantissa to 0 and exponent
  84464. * to 1, which is OK. */
  84465. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  84466. return bits;
  84467. }
  84468. bits |= ((e - 112) << 10) | (m >> 1);
  84469. bits += m & 1;
  84470. return bits;
  84471. };
  84472. DDSTools._FromHalfFloat = function (value) {
  84473. var s = (value & 0x8000) >> 15;
  84474. var e = (value & 0x7C00) >> 10;
  84475. var f = value & 0x03FF;
  84476. if (e === 0) {
  84477. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  84478. }
  84479. else if (e == 0x1F) {
  84480. return f ? NaN : ((s ? -1 : 1) * Infinity);
  84481. }
  84482. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  84483. };
  84484. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84485. var destArray = new Float32Array(dataLength);
  84486. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84487. var index = 0;
  84488. for (var y = 0; y < height; y++) {
  84489. for (var x = 0; x < width; x++) {
  84490. var srcPos = (x + y * width) * 4;
  84491. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  84492. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  84493. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  84494. if (DDSTools.StoreLODInAlphaChannel) {
  84495. destArray[index + 3] = lod;
  84496. }
  84497. else {
  84498. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  84499. }
  84500. index += 4;
  84501. }
  84502. }
  84503. return destArray;
  84504. };
  84505. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84506. if (DDSTools.StoreLODInAlphaChannel) {
  84507. var destArray = new Uint16Array(dataLength);
  84508. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84509. var index = 0;
  84510. for (var y = 0; y < height; y++) {
  84511. for (var x = 0; x < width; x++) {
  84512. var srcPos = (x + y * width) * 4;
  84513. destArray[index] = srcData[srcPos];
  84514. destArray[index + 1] = srcData[srcPos + 1];
  84515. destArray[index + 2] = srcData[srcPos + 2];
  84516. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  84517. index += 4;
  84518. }
  84519. }
  84520. return destArray;
  84521. }
  84522. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  84523. };
  84524. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84525. if (DDSTools.StoreLODInAlphaChannel) {
  84526. var destArray = new Float32Array(dataLength);
  84527. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84528. var index = 0;
  84529. for (var y = 0; y < height; y++) {
  84530. for (var x = 0; x < width; x++) {
  84531. var srcPos = (x + y * width) * 4;
  84532. destArray[index] = srcData[srcPos];
  84533. destArray[index + 1] = srcData[srcPos + 1];
  84534. destArray[index + 2] = srcData[srcPos + 2];
  84535. destArray[index + 3] = lod;
  84536. index += 4;
  84537. }
  84538. }
  84539. return destArray;
  84540. }
  84541. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  84542. };
  84543. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84544. var destArray = new Uint8Array(dataLength);
  84545. var srcData = new Float32Array(arrayBuffer, dataOffset);
  84546. var index = 0;
  84547. for (var y = 0; y < height; y++) {
  84548. for (var x = 0; x < width; x++) {
  84549. var srcPos = (x + y * width) * 4;
  84550. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  84551. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  84552. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  84553. if (DDSTools.StoreLODInAlphaChannel) {
  84554. destArray[index + 3] = lod;
  84555. }
  84556. else {
  84557. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  84558. }
  84559. index += 4;
  84560. }
  84561. }
  84562. return destArray;
  84563. };
  84564. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  84565. var destArray = new Uint8Array(dataLength);
  84566. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  84567. var index = 0;
  84568. for (var y = 0; y < height; y++) {
  84569. for (var x = 0; x < width; x++) {
  84570. var srcPos = (x + y * width) * 4;
  84571. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  84572. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  84573. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  84574. if (DDSTools.StoreLODInAlphaChannel) {
  84575. destArray[index + 3] = lod;
  84576. }
  84577. else {
  84578. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  84579. }
  84580. index += 4;
  84581. }
  84582. }
  84583. return destArray;
  84584. };
  84585. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  84586. var byteArray = new Uint8Array(dataLength);
  84587. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84588. var index = 0;
  84589. for (var y = 0; y < height; y++) {
  84590. for (var x = 0; x < width; x++) {
  84591. var srcPos = (x + y * width) * 4;
  84592. byteArray[index] = srcData[srcPos + rOffset];
  84593. byteArray[index + 1] = srcData[srcPos + gOffset];
  84594. byteArray[index + 2] = srcData[srcPos + bOffset];
  84595. byteArray[index + 3] = srcData[srcPos + aOffset];
  84596. index += 4;
  84597. }
  84598. }
  84599. return byteArray;
  84600. };
  84601. DDSTools._ExtractLongWordOrder = function (value) {
  84602. if (value === 0 || value === 255 || value === -16777216) {
  84603. return 0;
  84604. }
  84605. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  84606. };
  84607. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  84608. var byteArray = new Uint8Array(dataLength);
  84609. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  84610. var index = 0;
  84611. for (var y = 0; y < height; y++) {
  84612. for (var x = 0; x < width; x++) {
  84613. var srcPos = (x + y * width) * 3;
  84614. byteArray[index] = srcData[srcPos + rOffset];
  84615. byteArray[index + 1] = srcData[srcPos + gOffset];
  84616. byteArray[index + 2] = srcData[srcPos + bOffset];
  84617. index += 3;
  84618. }
  84619. }
  84620. return byteArray;
  84621. };
  84622. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  84623. var byteArray = new Uint8Array(dataLength);
  84624. var srcData = new Uint8Array(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);
  84629. byteArray[index] = srcData[srcPos];
  84630. index++;
  84631. }
  84632. }
  84633. return byteArray;
  84634. };
  84635. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  84636. if (lodIndex === void 0) { lodIndex = -1; }
  84637. var sphericalPolynomialFaces = null;
  84638. if (info.sphericalPolynomial) {
  84639. sphericalPolynomialFaces = new Array();
  84640. }
  84641. var ext = engine.getCaps().s3tc;
  84642. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  84643. var fourCC, width, height, dataLength = 0, dataOffset;
  84644. var byteArray, mipmapCount, mip;
  84645. var internalFormat = 0;
  84646. var format = 0;
  84647. var blockBytes = 1;
  84648. if (header[off_magic] !== DDS_MAGIC) {
  84649. BABYLON.Tools.Error("Invalid magic number in DDS header");
  84650. return;
  84651. }
  84652. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  84653. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  84654. return;
  84655. }
  84656. if (info.isCompressed && !ext) {
  84657. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  84658. return;
  84659. }
  84660. var bpp = header[off_RGBbpp];
  84661. dataOffset = header[off_size] + 4;
  84662. var computeFormats = false;
  84663. if (info.isFourCC) {
  84664. fourCC = header[off_pfFourCC];
  84665. switch (fourCC) {
  84666. case FOURCC_DXT1:
  84667. blockBytes = 8;
  84668. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  84669. break;
  84670. case FOURCC_DXT3:
  84671. blockBytes = 16;
  84672. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  84673. break;
  84674. case FOURCC_DXT5:
  84675. blockBytes = 16;
  84676. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  84677. break;
  84678. case FOURCC_D3DFMT_R16G16B16A16F:
  84679. computeFormats = true;
  84680. break;
  84681. case FOURCC_D3DFMT_R32G32B32A32F:
  84682. computeFormats = true;
  84683. break;
  84684. case FOURCC_DX10:
  84685. // There is an additionnal header so dataOffset need to be changed
  84686. dataOffset += 5 * 4; // 5 uints
  84687. var supported = false;
  84688. switch (info.dxgiFormat) {
  84689. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  84690. computeFormats = true;
  84691. supported = true;
  84692. break;
  84693. case DXGI_FORMAT_B8G8R8X8_UNORM:
  84694. info.isRGB = true;
  84695. info.isFourCC = false;
  84696. bpp = 32;
  84697. supported = true;
  84698. break;
  84699. }
  84700. if (supported) {
  84701. break;
  84702. }
  84703. default:
  84704. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  84705. return;
  84706. }
  84707. }
  84708. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  84709. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  84710. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  84711. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  84712. if (computeFormats) {
  84713. format = engine._getWebGLTextureType(info.textureType);
  84714. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84715. }
  84716. mipmapCount = 1;
  84717. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  84718. mipmapCount = Math.max(1, header[off_mipmapCount]);
  84719. }
  84720. for (var face = 0; face < faces; face++) {
  84721. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  84722. width = header[off_width];
  84723. height = header[off_height];
  84724. for (mip = 0; mip < mipmapCount; ++mip) {
  84725. if (lodIndex === -1 || lodIndex === mip) {
  84726. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  84727. var i = (lodIndex === -1) ? mip : 0;
  84728. if (!info.isCompressed && info.isFourCC) {
  84729. dataLength = width * height * 4;
  84730. var floatArray = null;
  84731. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  84732. if (bpp === 128) {
  84733. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84734. if (sphericalPolynomialFaces && i == 0) {
  84735. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84736. }
  84737. }
  84738. else if (bpp === 64) {
  84739. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84740. if (sphericalPolynomialFaces && i == 0) {
  84741. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84742. }
  84743. }
  84744. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  84745. format = engine._getWebGLTextureType(info.textureType);
  84746. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84747. }
  84748. else {
  84749. if (bpp === 128) {
  84750. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84751. if (sphericalPolynomialFaces && i == 0) {
  84752. sphericalPolynomialFaces.push(floatArray);
  84753. }
  84754. }
  84755. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  84756. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84757. if (sphericalPolynomialFaces && i == 0) {
  84758. sphericalPolynomialFaces.push(floatArray);
  84759. }
  84760. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  84761. format = engine._getWebGLTextureType(info.textureType);
  84762. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  84763. }
  84764. else { // 64
  84765. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  84766. if (sphericalPolynomialFaces && i == 0) {
  84767. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  84768. }
  84769. }
  84770. }
  84771. if (floatArray) {
  84772. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  84773. }
  84774. }
  84775. else if (info.isRGB) {
  84776. if (bpp === 24) {
  84777. dataLength = width * height * 3;
  84778. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  84779. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  84780. }
  84781. else { // 32
  84782. dataLength = width * height * 4;
  84783. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  84784. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  84785. }
  84786. }
  84787. else if (info.isLuminance) {
  84788. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  84789. var unpaddedRowSize = width;
  84790. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  84791. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  84792. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  84793. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  84794. }
  84795. else {
  84796. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  84797. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  84798. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  84799. }
  84800. }
  84801. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  84802. width *= 0.5;
  84803. height *= 0.5;
  84804. width = Math.max(1.0, width);
  84805. height = Math.max(1.0, height);
  84806. }
  84807. if (currentFace !== undefined) {
  84808. // Loading a single face
  84809. break;
  84810. }
  84811. }
  84812. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  84813. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  84814. size: header[off_width],
  84815. right: sphericalPolynomialFaces[0],
  84816. left: sphericalPolynomialFaces[1],
  84817. up: sphericalPolynomialFaces[2],
  84818. down: sphericalPolynomialFaces[3],
  84819. front: sphericalPolynomialFaces[4],
  84820. back: sphericalPolynomialFaces[5],
  84821. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  84822. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  84823. gammaSpace: false,
  84824. });
  84825. }
  84826. else {
  84827. info.sphericalPolynomial = undefined;
  84828. }
  84829. };
  84830. DDSTools.StoreLODInAlphaChannel = false;
  84831. return DDSTools;
  84832. }());
  84833. BABYLON.DDSTools = DDSTools;
  84834. })(BABYLON || (BABYLON = {}));
  84835. //# sourceMappingURL=babylon.dds.js.map
  84836. var BABYLON;
  84837. (function (BABYLON) {
  84838. /**
  84839. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  84840. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  84841. */
  84842. var KhronosTextureContainer = /** @class */ (function () {
  84843. /**
  84844. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  84845. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  84846. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  84847. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  84848. */
  84849. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  84850. this.arrayBuffer = arrayBuffer;
  84851. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  84852. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  84853. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  84854. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  84855. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  84856. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  84857. BABYLON.Tools.Error("texture missing KTX identifier");
  84858. return;
  84859. }
  84860. // load the reset of the header in native 32 bit int
  84861. var header = new Int32Array(this.arrayBuffer, 12, 13);
  84862. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  84863. var oppositeEndianess = header[0] === 0x01020304;
  84864. // read all the header elements in order they exist in the file, without modification (sans endainness)
  84865. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  84866. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  84867. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  84868. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  84869. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  84870. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  84871. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  84872. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  84873. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  84874. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  84875. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  84876. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  84877. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  84878. if (this.glType !== 0) {
  84879. BABYLON.Tools.Error("only compressed formats currently supported");
  84880. return;
  84881. }
  84882. else {
  84883. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  84884. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  84885. }
  84886. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  84887. BABYLON.Tools.Error("only 2D textures currently supported");
  84888. return;
  84889. }
  84890. if (this.numberOfArrayElements !== 0) {
  84891. BABYLON.Tools.Error("texture arrays not currently supported");
  84892. return;
  84893. }
  84894. if (this.numberOfFaces !== facesExpected) {
  84895. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  84896. return;
  84897. }
  84898. // we now have a completely validated file, so could use existence of loadType as success
  84899. // would need to make this more elaborate & adjust checks above to support more than one load type
  84900. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  84901. }
  84902. // not as fast hardware based, but will probably never need to use
  84903. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  84904. return ((val & 0xFF) << 24)
  84905. | ((val & 0xFF00) << 8)
  84906. | ((val >> 8) & 0xFF00)
  84907. | ((val >> 24) & 0xFF);
  84908. };
  84909. /**
  84910. * It is assumed that the texture has already been created & is currently bound
  84911. */
  84912. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  84913. switch (this.loadType) {
  84914. case KhronosTextureContainer.COMPRESSED_2D:
  84915. this._upload2DCompressedLevels(gl, loadMipmaps);
  84916. break;
  84917. case KhronosTextureContainer.TEX_2D:
  84918. case KhronosTextureContainer.COMPRESSED_3D:
  84919. case KhronosTextureContainer.TEX_3D:
  84920. }
  84921. };
  84922. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  84923. // initialize width & height for level 1
  84924. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  84925. var width = this.pixelWidth;
  84926. var height = this.pixelHeight;
  84927. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  84928. for (var level = 0; level < mipmapCount; level++) {
  84929. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  84930. for (var face = 0; face < this.numberOfFaces; face++) {
  84931. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  84932. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset + 4, imageSize);
  84933. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  84934. dataOffset += imageSize + 4; // size of the image + 4 for the imageSize field
  84935. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  84936. }
  84937. width = Math.max(1.0, width * 0.5);
  84938. height = Math.max(1.0, height * 0.5);
  84939. }
  84940. };
  84941. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  84942. // load types
  84943. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  84944. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  84945. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  84946. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  84947. return KhronosTextureContainer;
  84948. }());
  84949. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  84950. })(BABYLON || (BABYLON = {}));
  84951. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  84952. var BABYLON;
  84953. (function (BABYLON) {
  84954. var Debug;
  84955. (function (Debug) {
  84956. /**
  84957. * Demo available here: http://www.babylonjs-playground.com/#1BZJVJ#8
  84958. */
  84959. var SkeletonViewer = /** @class */ (function () {
  84960. function SkeletonViewer(skeleton, mesh, scene, autoUpdateBonesMatrices, renderingGroupId) {
  84961. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  84962. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  84963. this.skeleton = skeleton;
  84964. this.mesh = mesh;
  84965. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  84966. this.renderingGroupId = renderingGroupId;
  84967. this.color = BABYLON.Color3.White();
  84968. this._debugLines = new Array();
  84969. this._isEnabled = false;
  84970. this._scene = scene;
  84971. this.update();
  84972. this._renderFunction = this.update.bind(this);
  84973. }
  84974. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  84975. get: function () {
  84976. return this._isEnabled;
  84977. },
  84978. set: function (value) {
  84979. if (this._isEnabled === value) {
  84980. return;
  84981. }
  84982. this._isEnabled = value;
  84983. if (value) {
  84984. this._scene.registerBeforeRender(this._renderFunction);
  84985. }
  84986. else {
  84987. this._scene.unregisterBeforeRender(this._renderFunction);
  84988. }
  84989. },
  84990. enumerable: true,
  84991. configurable: true
  84992. });
  84993. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  84994. if (x === void 0) { x = 0; }
  84995. if (y === void 0) { y = 0; }
  84996. if (z === void 0) { z = 0; }
  84997. var tmat = BABYLON.Tmp.Matrix[0];
  84998. var parentBone = bone.getParent();
  84999. tmat.copyFrom(bone.getLocalMatrix());
  85000. if (x !== 0 || y !== 0 || z !== 0) {
  85001. var tmat2 = BABYLON.Tmp.Matrix[1];
  85002. BABYLON.Matrix.IdentityToRef(tmat2);
  85003. tmat2.m[12] = x;
  85004. tmat2.m[13] = y;
  85005. tmat2.m[14] = z;
  85006. tmat2.multiplyToRef(tmat, tmat);
  85007. }
  85008. if (parentBone) {
  85009. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  85010. }
  85011. tmat.multiplyToRef(meshMat, tmat);
  85012. position.x = tmat.m[12];
  85013. position.y = tmat.m[13];
  85014. position.z = tmat.m[14];
  85015. };
  85016. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  85017. var len = bones.length;
  85018. var meshPos = this.mesh.position;
  85019. for (var i = 0; i < len; i++) {
  85020. var bone = bones[i];
  85021. var points = this._debugLines[i];
  85022. if (!points) {
  85023. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85024. this._debugLines[i] = points;
  85025. }
  85026. this._getBonePosition(points[0], bone, meshMat);
  85027. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  85028. points[0].subtractInPlace(meshPos);
  85029. points[1].subtractInPlace(meshPos);
  85030. }
  85031. };
  85032. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  85033. var len = bones.length;
  85034. var boneNum = 0;
  85035. var meshPos = this.mesh.position;
  85036. for (var i = len - 1; i >= 0; i--) {
  85037. var childBone = bones[i];
  85038. var parentBone = childBone.getParent();
  85039. if (!parentBone) {
  85040. continue;
  85041. }
  85042. var points = this._debugLines[boneNum];
  85043. if (!points) {
  85044. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85045. this._debugLines[boneNum] = points;
  85046. }
  85047. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  85048. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  85049. points[0].subtractInPlace(meshPos);
  85050. points[1].subtractInPlace(meshPos);
  85051. boneNum++;
  85052. }
  85053. };
  85054. SkeletonViewer.prototype.update = function () {
  85055. if (this.autoUpdateBonesMatrices) {
  85056. this.skeleton.computeAbsoluteTransforms();
  85057. }
  85058. if (this.skeleton.bones[0].length === undefined) {
  85059. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85060. }
  85061. else {
  85062. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  85063. }
  85064. if (!this._debugMesh) {
  85065. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  85066. this._debugMesh.renderingGroupId = this.renderingGroupId;
  85067. }
  85068. else {
  85069. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  85070. }
  85071. this._debugMesh.position.copyFrom(this.mesh.position);
  85072. this._debugMesh.color = this.color;
  85073. };
  85074. SkeletonViewer.prototype.dispose = function () {
  85075. if (this._debugMesh) {
  85076. this.isEnabled = false;
  85077. this._debugMesh.dispose();
  85078. this._debugMesh = null;
  85079. }
  85080. };
  85081. return SkeletonViewer;
  85082. }());
  85083. Debug.SkeletonViewer = SkeletonViewer;
  85084. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85085. })(BABYLON || (BABYLON = {}));
  85086. //# sourceMappingURL=babylon.skeletonViewer.js.map
  85087. /**
  85088. * Module Debug contains the (visual) components to debug a scene correctly
  85089. */
  85090. var BABYLON;
  85091. (function (BABYLON) {
  85092. var Debug;
  85093. (function (Debug) {
  85094. /**
  85095. * The Axes viewer will show 3 axes in a specific point in space
  85096. */
  85097. var AxesViewer = /** @class */ (function () {
  85098. function AxesViewer(scene, scaleLines) {
  85099. if (scaleLines === void 0) { scaleLines = 1; }
  85100. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85101. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85102. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  85103. this.scaleLines = 1;
  85104. this.scaleLines = scaleLines;
  85105. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  85106. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  85107. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  85108. this._xmesh.renderingGroupId = 2;
  85109. this._ymesh.renderingGroupId = 2;
  85110. this._zmesh.renderingGroupId = 2;
  85111. this._xmesh.material.checkReadyOnlyOnce = true;
  85112. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  85113. this._ymesh.material.checkReadyOnlyOnce = true;
  85114. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  85115. this._zmesh.material.checkReadyOnlyOnce = true;
  85116. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  85117. this.scene = scene;
  85118. }
  85119. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  85120. var scaleLines = this.scaleLines;
  85121. if (this._xmesh) {
  85122. this._xmesh.position.copyFrom(position);
  85123. }
  85124. if (this._ymesh) {
  85125. this._ymesh.position.copyFrom(position);
  85126. }
  85127. if (this._zmesh) {
  85128. this._zmesh.position.copyFrom(position);
  85129. }
  85130. var point2 = this._xline[1];
  85131. point2.x = xaxis.x * scaleLines;
  85132. point2.y = xaxis.y * scaleLines;
  85133. point2.z = xaxis.z * scaleLines;
  85134. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  85135. point2 = this._yline[1];
  85136. point2.x = yaxis.x * scaleLines;
  85137. point2.y = yaxis.y * scaleLines;
  85138. point2.z = yaxis.z * scaleLines;
  85139. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  85140. point2 = this._zline[1];
  85141. point2.x = zaxis.x * scaleLines;
  85142. point2.y = zaxis.y * scaleLines;
  85143. point2.z = zaxis.z * scaleLines;
  85144. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  85145. };
  85146. AxesViewer.prototype.dispose = function () {
  85147. if (this._xmesh) {
  85148. this._xmesh.dispose();
  85149. }
  85150. if (this._ymesh) {
  85151. this._ymesh.dispose();
  85152. }
  85153. if (this._zmesh) {
  85154. this._zmesh.dispose();
  85155. }
  85156. this._xmesh = null;
  85157. this._ymesh = null;
  85158. this._zmesh = null;
  85159. this.scene = null;
  85160. };
  85161. return AxesViewer;
  85162. }());
  85163. Debug.AxesViewer = AxesViewer;
  85164. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85165. })(BABYLON || (BABYLON = {}));
  85166. //# sourceMappingURL=babylon.axesViewer.js.map
  85167. var BABYLON;
  85168. (function (BABYLON) {
  85169. var Debug;
  85170. (function (Debug) {
  85171. /**
  85172. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  85173. */
  85174. var BoneAxesViewer = /** @class */ (function (_super) {
  85175. __extends(BoneAxesViewer, _super);
  85176. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  85177. if (scaleLines === void 0) { scaleLines = 1; }
  85178. var _this = _super.call(this, scene, scaleLines) || this;
  85179. _this.pos = BABYLON.Vector3.Zero();
  85180. _this.xaxis = BABYLON.Vector3.Zero();
  85181. _this.yaxis = BABYLON.Vector3.Zero();
  85182. _this.zaxis = BABYLON.Vector3.Zero();
  85183. _this.mesh = mesh;
  85184. _this.bone = bone;
  85185. return _this;
  85186. }
  85187. BoneAxesViewer.prototype.update = function () {
  85188. if (!this.mesh || !this.bone) {
  85189. return;
  85190. }
  85191. var bone = this.bone;
  85192. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  85193. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  85194. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  85195. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  85196. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  85197. };
  85198. BoneAxesViewer.prototype.dispose = function () {
  85199. if (this.mesh) {
  85200. this.mesh = null;
  85201. this.bone = null;
  85202. _super.prototype.dispose.call(this);
  85203. }
  85204. };
  85205. return BoneAxesViewer;
  85206. }(Debug.AxesViewer));
  85207. Debug.BoneAxesViewer = BoneAxesViewer;
  85208. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85209. })(BABYLON || (BABYLON = {}));
  85210. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  85211. var BABYLON;
  85212. (function (BABYLON) {
  85213. var RayHelper = /** @class */ (function () {
  85214. function RayHelper(ray) {
  85215. this.ray = ray;
  85216. }
  85217. RayHelper.CreateAndShow = function (ray, scene, color) {
  85218. var helper = new RayHelper(ray);
  85219. helper.show(scene, color);
  85220. return helper;
  85221. };
  85222. RayHelper.prototype.show = function (scene, color) {
  85223. if (!this._renderFunction && this.ray) {
  85224. var ray = this.ray;
  85225. this._renderFunction = this._render.bind(this);
  85226. this._scene = scene;
  85227. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  85228. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  85229. if (this._renderFunction) {
  85230. this._scene.registerBeforeRender(this._renderFunction);
  85231. }
  85232. }
  85233. if (color && this._renderLine) {
  85234. this._renderLine.color.copyFrom(color);
  85235. }
  85236. };
  85237. RayHelper.prototype.hide = function () {
  85238. if (this._renderFunction && this._scene) {
  85239. this._scene.unregisterBeforeRender(this._renderFunction);
  85240. this._scene = null;
  85241. this._renderFunction = null;
  85242. if (this._renderLine) {
  85243. this._renderLine.dispose();
  85244. this._renderLine = null;
  85245. }
  85246. this._renderPoints = [];
  85247. }
  85248. };
  85249. RayHelper.prototype._render = function () {
  85250. var ray = this.ray;
  85251. if (!ray) {
  85252. return;
  85253. }
  85254. var point = this._renderPoints[1];
  85255. var len = Math.min(ray.length, 1000000);
  85256. point.copyFrom(ray.direction);
  85257. point.scaleInPlace(len);
  85258. point.addInPlace(ray.origin);
  85259. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  85260. };
  85261. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  85262. this._attachedToMesh = mesh;
  85263. var ray = this.ray;
  85264. if (!ray) {
  85265. return;
  85266. }
  85267. if (!ray.direction) {
  85268. ray.direction = BABYLON.Vector3.Zero();
  85269. }
  85270. if (!ray.origin) {
  85271. ray.origin = BABYLON.Vector3.Zero();
  85272. }
  85273. if (length) {
  85274. ray.length = length;
  85275. }
  85276. if (!meshSpaceOrigin) {
  85277. meshSpaceOrigin = BABYLON.Vector3.Zero();
  85278. }
  85279. if (!meshSpaceDirection) {
  85280. // -1 so that this will work with Mesh.lookAt
  85281. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  85282. }
  85283. if (!this._meshSpaceDirection) {
  85284. this._meshSpaceDirection = meshSpaceDirection.clone();
  85285. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  85286. }
  85287. else {
  85288. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  85289. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  85290. }
  85291. if (!this._updateToMeshFunction) {
  85292. this._updateToMeshFunction = this._updateToMesh.bind(this);
  85293. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  85294. }
  85295. this._updateToMesh();
  85296. };
  85297. RayHelper.prototype.detachFromMesh = function () {
  85298. if (this._attachedToMesh) {
  85299. if (this._updateToMeshFunction) {
  85300. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  85301. }
  85302. this._attachedToMesh = null;
  85303. this._updateToMeshFunction = null;
  85304. }
  85305. };
  85306. RayHelper.prototype._updateToMesh = function () {
  85307. var ray = this.ray;
  85308. if (!this._attachedToMesh || !ray) {
  85309. return;
  85310. }
  85311. if (this._attachedToMesh._isDisposed) {
  85312. this.detachFromMesh();
  85313. return;
  85314. }
  85315. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  85316. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  85317. };
  85318. RayHelper.prototype.dispose = function () {
  85319. this.hide();
  85320. this.detachFromMesh();
  85321. this.ray = null;
  85322. };
  85323. return RayHelper;
  85324. }());
  85325. BABYLON.RayHelper = RayHelper;
  85326. })(BABYLON || (BABYLON = {}));
  85327. //# sourceMappingURL=babylon.rayHelper.js.map
  85328. var BABYLON;
  85329. (function (BABYLON) {
  85330. // load the inspector using require, if not present in the global namespace.
  85331. var DebugLayer = /** @class */ (function () {
  85332. function DebugLayer(scene) {
  85333. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85334. this._scene = scene;
  85335. // load inspector using require, if it doesn't exist on the global namespace.
  85336. }
  85337. /** Creates the inspector window. */
  85338. DebugLayer.prototype._createInspector = function (config) {
  85339. if (config === void 0) { config = {}; }
  85340. var popup = config.popup || false;
  85341. var initialTab = config.initialTab || 0;
  85342. var parentElement = config.parentElement || null;
  85343. if (!this._inspector) {
  85344. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  85345. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  85346. } // else nothing to do,; instance is already existing
  85347. };
  85348. DebugLayer.prototype.isVisible = function () {
  85349. if (!this._inspector) {
  85350. return false;
  85351. }
  85352. return true;
  85353. };
  85354. DebugLayer.prototype.hide = function () {
  85355. if (this._inspector) {
  85356. try {
  85357. this._inspector.dispose();
  85358. }
  85359. catch (e) {
  85360. // If the inspector has been removed directly from the inspector tool
  85361. }
  85362. this._inspector = null;
  85363. }
  85364. };
  85365. DebugLayer.prototype.show = function (config) {
  85366. if (config === void 0) { config = {}; }
  85367. if (typeof this.BJSINSPECTOR == 'undefined') {
  85368. // Load inspector and add it to the DOM
  85369. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  85370. }
  85371. else {
  85372. // Otherwise creates the inspector
  85373. this._createInspector(config);
  85374. }
  85375. };
  85376. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  85377. return DebugLayer;
  85378. }());
  85379. BABYLON.DebugLayer = DebugLayer;
  85380. })(BABYLON || (BABYLON = {}));
  85381. //# sourceMappingURL=babylon.debugLayer.js.map
  85382. var BABYLON;
  85383. (function (BABYLON) {
  85384. var Debug;
  85385. (function (Debug) {
  85386. /**
  85387. * Used to show the physics impostor around the specific mesh.
  85388. */
  85389. var PhysicsViewer = /** @class */ (function () {
  85390. function PhysicsViewer(scene) {
  85391. this._impostors = [];
  85392. this._meshes = [];
  85393. this._numMeshes = 0;
  85394. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85395. var physicEngine = this._scene.getPhysicsEngine();
  85396. if (physicEngine) {
  85397. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  85398. }
  85399. }
  85400. PhysicsViewer.prototype._updateDebugMeshes = function () {
  85401. var plugin = this._physicsEnginePlugin;
  85402. for (var i = 0; i < this._numMeshes; i++) {
  85403. var impostor = this._impostors[i];
  85404. if (!impostor) {
  85405. continue;
  85406. }
  85407. if (impostor.isDisposed) {
  85408. this.hideImpostor(this._impostors[i--]);
  85409. }
  85410. else {
  85411. var mesh = this._meshes[i];
  85412. if (mesh && plugin) {
  85413. plugin.syncMeshWithImpostor(mesh, impostor);
  85414. }
  85415. }
  85416. }
  85417. };
  85418. PhysicsViewer.prototype.showImpostor = function (impostor) {
  85419. if (!this._scene) {
  85420. return;
  85421. }
  85422. for (var i = 0; i < this._numMeshes; i++) {
  85423. if (this._impostors[i] == impostor) {
  85424. return;
  85425. }
  85426. }
  85427. var debugMesh = this._getDebugMesh(impostor, this._scene);
  85428. if (debugMesh) {
  85429. this._impostors[this._numMeshes] = impostor;
  85430. this._meshes[this._numMeshes] = debugMesh;
  85431. if (this._numMeshes === 0) {
  85432. this._renderFunction = this._updateDebugMeshes.bind(this);
  85433. this._scene.registerBeforeRender(this._renderFunction);
  85434. }
  85435. this._numMeshes++;
  85436. }
  85437. };
  85438. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  85439. if (!impostor || !this._scene) {
  85440. return;
  85441. }
  85442. var removed = false;
  85443. for (var i = 0; i < this._numMeshes; i++) {
  85444. if (this._impostors[i] == impostor) {
  85445. var mesh = this._meshes[i];
  85446. if (!mesh) {
  85447. continue;
  85448. }
  85449. this._scene.removeMesh(mesh);
  85450. mesh.dispose();
  85451. this._numMeshes--;
  85452. if (this._numMeshes > 0) {
  85453. this._meshes[i] = this._meshes[this._numMeshes];
  85454. this._impostors[i] = this._impostors[this._numMeshes];
  85455. this._meshes[this._numMeshes] = null;
  85456. this._impostors[this._numMeshes] = null;
  85457. }
  85458. else {
  85459. this._meshes[0] = null;
  85460. this._impostors[0] = null;
  85461. }
  85462. removed = true;
  85463. break;
  85464. }
  85465. }
  85466. if (removed && this._numMeshes === 0) {
  85467. this._scene.unregisterBeforeRender(this._renderFunction);
  85468. }
  85469. };
  85470. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  85471. if (!this._debugMaterial) {
  85472. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  85473. this._debugMaterial.wireframe = true;
  85474. }
  85475. return this._debugMaterial;
  85476. };
  85477. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  85478. if (!this._debugBoxMesh) {
  85479. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  85480. this._debugBoxMesh.renderingGroupId = 1;
  85481. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85482. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  85483. scene.removeMesh(this._debugBoxMesh);
  85484. }
  85485. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  85486. };
  85487. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  85488. if (!this._debugSphereMesh) {
  85489. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  85490. this._debugSphereMesh.renderingGroupId = 1;
  85491. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  85492. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  85493. scene.removeMesh(this._debugSphereMesh);
  85494. }
  85495. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  85496. };
  85497. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  85498. var mesh = null;
  85499. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  85500. mesh = this._getDebugBoxMesh(scene);
  85501. impostor.getBoxSizeToRef(mesh.scaling);
  85502. }
  85503. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  85504. mesh = this._getDebugSphereMesh(scene);
  85505. var radius = impostor.getRadius();
  85506. mesh.scaling.x = radius * 2;
  85507. mesh.scaling.y = radius * 2;
  85508. mesh.scaling.z = radius * 2;
  85509. }
  85510. return mesh;
  85511. };
  85512. PhysicsViewer.prototype.dispose = function () {
  85513. for (var i = 0; i < this._numMeshes; i++) {
  85514. this.hideImpostor(this._impostors[i]);
  85515. }
  85516. if (this._debugBoxMesh) {
  85517. this._debugBoxMesh.dispose();
  85518. }
  85519. if (this._debugSphereMesh) {
  85520. this._debugSphereMesh.dispose();
  85521. }
  85522. if (this._debugMaterial) {
  85523. this._debugMaterial.dispose();
  85524. }
  85525. this._impostors.length = 0;
  85526. this._scene = null;
  85527. this._physicsEnginePlugin = null;
  85528. };
  85529. return PhysicsViewer;
  85530. }());
  85531. Debug.PhysicsViewer = PhysicsViewer;
  85532. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  85533. })(BABYLON || (BABYLON = {}));
  85534. //# sourceMappingURL=babylon.physicsViewer.js.map
  85535. var BABYLON;
  85536. (function (BABYLON) {
  85537. var BoundingBoxRenderer = /** @class */ (function () {
  85538. function BoundingBoxRenderer(scene) {
  85539. this.frontColor = new BABYLON.Color3(1, 1, 1);
  85540. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  85541. this.showBackLines = true;
  85542. this.renderList = new BABYLON.SmartArray(32);
  85543. this._vertexBuffers = {};
  85544. this._scene = scene;
  85545. }
  85546. BoundingBoxRenderer.prototype._prepareRessources = function () {
  85547. if (this._colorShader) {
  85548. return;
  85549. }
  85550. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  85551. attributes: [BABYLON.VertexBuffer.PositionKind],
  85552. uniforms: ["world", "viewProjection", "color"]
  85553. });
  85554. var engine = this._scene.getEngine();
  85555. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  85556. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  85557. this._createIndexBuffer();
  85558. };
  85559. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  85560. var engine = this._scene.getEngine();
  85561. 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]);
  85562. };
  85563. BoundingBoxRenderer.prototype._rebuild = function () {
  85564. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85565. if (vb) {
  85566. vb._rebuild();
  85567. }
  85568. this._createIndexBuffer();
  85569. };
  85570. BoundingBoxRenderer.prototype.reset = function () {
  85571. this.renderList.reset();
  85572. };
  85573. BoundingBoxRenderer.prototype.render = function () {
  85574. if (this.renderList.length === 0) {
  85575. return;
  85576. }
  85577. this._prepareRessources();
  85578. if (!this._colorShader.isReady()) {
  85579. return;
  85580. }
  85581. var engine = this._scene.getEngine();
  85582. engine.setDepthWrite(false);
  85583. this._colorShader._preBind();
  85584. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  85585. var boundingBox = this.renderList.data[boundingBoxIndex];
  85586. var min = boundingBox.minimum;
  85587. var max = boundingBox.maximum;
  85588. var diff = max.subtract(min);
  85589. var median = min.add(diff.scale(0.5));
  85590. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85591. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85592. .multiply(boundingBox.getWorldMatrix());
  85593. // VBOs
  85594. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85595. if (this.showBackLines) {
  85596. // Back
  85597. engine.setDepthFunctionToGreaterOrEqual();
  85598. this._scene.resetCachedMaterial();
  85599. this._colorShader.setColor4("color", this.backColor.toColor4());
  85600. this._colorShader.bind(worldMatrix);
  85601. // Draw order
  85602. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85603. }
  85604. // Front
  85605. engine.setDepthFunctionToLess();
  85606. this._scene.resetCachedMaterial();
  85607. this._colorShader.setColor4("color", this.frontColor.toColor4());
  85608. this._colorShader.bind(worldMatrix);
  85609. // Draw order
  85610. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85611. }
  85612. this._colorShader.unbind();
  85613. engine.setDepthFunctionToLessOrEqual();
  85614. engine.setDepthWrite(true);
  85615. };
  85616. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  85617. this._prepareRessources();
  85618. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  85619. return;
  85620. }
  85621. var engine = this._scene.getEngine();
  85622. engine.setDepthWrite(false);
  85623. engine.setColorWrite(false);
  85624. this._colorShader._preBind();
  85625. var boundingBox = mesh._boundingInfo.boundingBox;
  85626. var min = boundingBox.minimum;
  85627. var max = boundingBox.maximum;
  85628. var diff = max.subtract(min);
  85629. var median = min.add(diff.scale(0.5));
  85630. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  85631. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  85632. .multiply(boundingBox.getWorldMatrix());
  85633. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  85634. engine.setDepthFunctionToLess();
  85635. this._scene.resetCachedMaterial();
  85636. this._colorShader.bind(worldMatrix);
  85637. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  85638. this._colorShader.unbind();
  85639. engine.setDepthFunctionToLessOrEqual();
  85640. engine.setDepthWrite(true);
  85641. engine.setColorWrite(true);
  85642. };
  85643. BoundingBoxRenderer.prototype.dispose = function () {
  85644. if (!this._colorShader) {
  85645. return;
  85646. }
  85647. this.renderList.dispose();
  85648. this._colorShader.dispose();
  85649. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  85650. if (buffer) {
  85651. buffer.dispose();
  85652. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  85653. }
  85654. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  85655. };
  85656. return BoundingBoxRenderer;
  85657. }());
  85658. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  85659. })(BABYLON || (BABYLON = {}));
  85660. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  85661. var BABYLON;
  85662. (function (BABYLON) {
  85663. /**
  85664. * Defines a target to use with MorphTargetManager
  85665. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85666. */
  85667. var MorphTarget = /** @class */ (function () {
  85668. /**
  85669. * Creates a new MorphTarget
  85670. * @param name defines the name of the target
  85671. * @param influence defines the influence to use
  85672. */
  85673. function MorphTarget(
  85674. /** defines the name of the target */
  85675. name, influence, scene) {
  85676. if (influence === void 0) { influence = 0; }
  85677. if (scene === void 0) { scene = null; }
  85678. this.name = name;
  85679. /**
  85680. * Gets or sets the list of animations
  85681. */
  85682. this.animations = new Array();
  85683. this._positions = null;
  85684. this._normals = null;
  85685. this._tangents = null;
  85686. /**
  85687. * Observable raised when the influence changes
  85688. */
  85689. this.onInfluenceChanged = new BABYLON.Observable();
  85690. this._animationPropertiesOverride = null;
  85691. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  85692. this.influence = influence;
  85693. }
  85694. Object.defineProperty(MorphTarget.prototype, "influence", {
  85695. /**
  85696. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  85697. */
  85698. get: function () {
  85699. return this._influence;
  85700. },
  85701. set: function (influence) {
  85702. if (this._influence === influence) {
  85703. return;
  85704. }
  85705. var previous = this._influence;
  85706. this._influence = influence;
  85707. if (this.onInfluenceChanged.hasObservers) {
  85708. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  85709. }
  85710. },
  85711. enumerable: true,
  85712. configurable: true
  85713. });
  85714. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  85715. /**
  85716. * Gets or sets the animation properties override
  85717. */
  85718. get: function () {
  85719. if (!this._animationPropertiesOverride && this._scene) {
  85720. return this._scene.animationPropertiesOverride;
  85721. }
  85722. return this._animationPropertiesOverride;
  85723. },
  85724. set: function (value) {
  85725. this._animationPropertiesOverride = value;
  85726. },
  85727. enumerable: true,
  85728. configurable: true
  85729. });
  85730. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  85731. /**
  85732. * Gets a boolean defining if the target contains position data
  85733. */
  85734. get: function () {
  85735. return !!this._positions;
  85736. },
  85737. enumerable: true,
  85738. configurable: true
  85739. });
  85740. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  85741. /**
  85742. * Gets a boolean defining if the target contains normal data
  85743. */
  85744. get: function () {
  85745. return !!this._normals;
  85746. },
  85747. enumerable: true,
  85748. configurable: true
  85749. });
  85750. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  85751. /**
  85752. * Gets a boolean defining if the target contains tangent data
  85753. */
  85754. get: function () {
  85755. return !!this._tangents;
  85756. },
  85757. enumerable: true,
  85758. configurable: true
  85759. });
  85760. /**
  85761. * Affects position data to this target
  85762. * @param data defines the position data to use
  85763. */
  85764. MorphTarget.prototype.setPositions = function (data) {
  85765. this._positions = data;
  85766. };
  85767. /**
  85768. * Gets the position data stored in this target
  85769. * @returns a FloatArray containing the position data (or null if not present)
  85770. */
  85771. MorphTarget.prototype.getPositions = function () {
  85772. return this._positions;
  85773. };
  85774. /**
  85775. * Affects normal data to this target
  85776. * @param data defines the normal data to use
  85777. */
  85778. MorphTarget.prototype.setNormals = function (data) {
  85779. this._normals = data;
  85780. };
  85781. /**
  85782. * Gets the normal data stored in this target
  85783. * @returns a FloatArray containing the normal data (or null if not present)
  85784. */
  85785. MorphTarget.prototype.getNormals = function () {
  85786. return this._normals;
  85787. };
  85788. /**
  85789. * Affects tangent data to this target
  85790. * @param data defines the tangent data to use
  85791. */
  85792. MorphTarget.prototype.setTangents = function (data) {
  85793. this._tangents = data;
  85794. };
  85795. /**
  85796. * Gets the tangent data stored in this target
  85797. * @returns a FloatArray containing the tangent data (or null if not present)
  85798. */
  85799. MorphTarget.prototype.getTangents = function () {
  85800. return this._tangents;
  85801. };
  85802. /**
  85803. * Serializes the current target into a Serialization object
  85804. * @returns the serialized object
  85805. */
  85806. MorphTarget.prototype.serialize = function () {
  85807. var serializationObject = {};
  85808. serializationObject.name = this.name;
  85809. serializationObject.influence = this.influence;
  85810. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  85811. if (this.hasNormals) {
  85812. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  85813. }
  85814. if (this.hasTangents) {
  85815. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  85816. }
  85817. // Animations
  85818. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  85819. return serializationObject;
  85820. };
  85821. // Statics
  85822. /**
  85823. * Creates a new target from serialized data
  85824. * @param serializationObject defines the serialized data to use
  85825. * @returns a new MorphTarget
  85826. */
  85827. MorphTarget.Parse = function (serializationObject) {
  85828. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  85829. result.setPositions(serializationObject.positions);
  85830. if (serializationObject.normals) {
  85831. result.setNormals(serializationObject.normals);
  85832. }
  85833. if (serializationObject.tangents) {
  85834. result.setTangents(serializationObject.tangents);
  85835. }
  85836. // Animations
  85837. if (serializationObject.animations) {
  85838. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  85839. var parsedAnimation = serializationObject.animations[animationIndex];
  85840. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  85841. }
  85842. }
  85843. return result;
  85844. };
  85845. /**
  85846. * Creates a MorphTarget from mesh data
  85847. * @param mesh defines the source mesh
  85848. * @param name defines the name to use for the new target
  85849. * @param influence defines the influence to attach to the target
  85850. * @returns a new MorphTarget
  85851. */
  85852. MorphTarget.FromMesh = function (mesh, name, influence) {
  85853. if (!name) {
  85854. name = mesh.name;
  85855. }
  85856. var result = new MorphTarget(name, influence, mesh.getScene());
  85857. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85858. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  85859. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  85860. }
  85861. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  85862. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  85863. }
  85864. return result;
  85865. };
  85866. return MorphTarget;
  85867. }());
  85868. BABYLON.MorphTarget = MorphTarget;
  85869. })(BABYLON || (BABYLON = {}));
  85870. //# sourceMappingURL=babylon.morphTarget.js.map
  85871. var BABYLON;
  85872. (function (BABYLON) {
  85873. /**
  85874. * This class is used to deform meshes using morphing between different targets
  85875. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  85876. */
  85877. var MorphTargetManager = /** @class */ (function () {
  85878. /**
  85879. * Creates a new MorphTargetManager
  85880. * @param scene defines the current scene
  85881. */
  85882. function MorphTargetManager(scene) {
  85883. if (scene === void 0) { scene = null; }
  85884. this._targets = new Array();
  85885. this._targetObservable = new Array();
  85886. this._activeTargets = new BABYLON.SmartArray(16);
  85887. this._supportsNormals = false;
  85888. this._supportsTangents = false;
  85889. this._vertexCount = 0;
  85890. this._uniqueId = 0;
  85891. this._tempInfluences = new Array();
  85892. if (!scene) {
  85893. scene = BABYLON.Engine.LastCreatedScene;
  85894. }
  85895. this._scene = scene;
  85896. if (this._scene) {
  85897. this._scene.morphTargetManagers.push(this);
  85898. this._uniqueId = this._scene.getUniqueId();
  85899. }
  85900. }
  85901. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  85902. /**
  85903. * Gets the unique ID of this manager
  85904. */
  85905. get: function () {
  85906. return this._uniqueId;
  85907. },
  85908. enumerable: true,
  85909. configurable: true
  85910. });
  85911. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  85912. /**
  85913. * Gets the number of vertices handled by this manager
  85914. */
  85915. get: function () {
  85916. return this._vertexCount;
  85917. },
  85918. enumerable: true,
  85919. configurable: true
  85920. });
  85921. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  85922. /**
  85923. * Gets a boolean indicating if this manager supports morphing of normals
  85924. */
  85925. get: function () {
  85926. return this._supportsNormals;
  85927. },
  85928. enumerable: true,
  85929. configurable: true
  85930. });
  85931. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  85932. /**
  85933. * Gets a boolean indicating if this manager supports morphing of tangents
  85934. */
  85935. get: function () {
  85936. return this._supportsTangents;
  85937. },
  85938. enumerable: true,
  85939. configurable: true
  85940. });
  85941. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  85942. /**
  85943. * Gets the number of targets stored in this manager
  85944. */
  85945. get: function () {
  85946. return this._targets.length;
  85947. },
  85948. enumerable: true,
  85949. configurable: true
  85950. });
  85951. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  85952. /**
  85953. * Gets the number of influencers (ie. the number of targets with influences > 0)
  85954. */
  85955. get: function () {
  85956. return this._activeTargets.length;
  85957. },
  85958. enumerable: true,
  85959. configurable: true
  85960. });
  85961. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  85962. /**
  85963. * Gets the list of influences (one per target)
  85964. */
  85965. get: function () {
  85966. return this._influences;
  85967. },
  85968. enumerable: true,
  85969. configurable: true
  85970. });
  85971. /**
  85972. * Gets the active target at specified index. An active target is a target with an influence > 0
  85973. * @param index defines the index to check
  85974. * @returns the requested target
  85975. */
  85976. MorphTargetManager.prototype.getActiveTarget = function (index) {
  85977. return this._activeTargets.data[index];
  85978. };
  85979. /**
  85980. * Gets the target at specified index
  85981. * @param index defines the index to check
  85982. * @returns the requested target
  85983. */
  85984. MorphTargetManager.prototype.getTarget = function (index) {
  85985. return this._targets[index];
  85986. };
  85987. /**
  85988. * Add a new target to this manager
  85989. * @param target defines the target to add
  85990. */
  85991. MorphTargetManager.prototype.addTarget = function (target) {
  85992. var _this = this;
  85993. this._targets.push(target);
  85994. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  85995. _this._syncActiveTargets(needUpdate);
  85996. }));
  85997. this._syncActiveTargets(true);
  85998. };
  85999. /**
  86000. * Removes a target from the manager
  86001. * @param target defines the target to remove
  86002. */
  86003. MorphTargetManager.prototype.removeTarget = function (target) {
  86004. var index = this._targets.indexOf(target);
  86005. if (index >= 0) {
  86006. this._targets.splice(index, 1);
  86007. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  86008. this._syncActiveTargets(true);
  86009. }
  86010. };
  86011. /**
  86012. * Serializes the current manager into a Serialization object
  86013. * @returns the serialized object
  86014. */
  86015. MorphTargetManager.prototype.serialize = function () {
  86016. var serializationObject = {};
  86017. serializationObject.id = this.uniqueId;
  86018. serializationObject.targets = [];
  86019. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86020. var target = _a[_i];
  86021. serializationObject.targets.push(target.serialize());
  86022. }
  86023. return serializationObject;
  86024. };
  86025. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  86026. var influenceCount = 0;
  86027. this._activeTargets.reset();
  86028. this._supportsNormals = true;
  86029. this._supportsTangents = true;
  86030. this._vertexCount = 0;
  86031. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  86032. var target = _a[_i];
  86033. this._activeTargets.push(target);
  86034. this._tempInfluences[influenceCount++] = target.influence;
  86035. var positions = target.getPositions();
  86036. if (positions) {
  86037. this._supportsNormals = this._supportsNormals && target.hasNormals;
  86038. this._supportsTangents = this._supportsTangents && target.hasTangents;
  86039. var vertexCount = positions.length / 3;
  86040. if (this._vertexCount === 0) {
  86041. this._vertexCount = vertexCount;
  86042. }
  86043. else if (this._vertexCount !== vertexCount) {
  86044. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  86045. return;
  86046. }
  86047. }
  86048. }
  86049. if (!this._influences || this._influences.length !== influenceCount) {
  86050. this._influences = new Float32Array(influenceCount);
  86051. }
  86052. for (var index = 0; index < influenceCount; index++) {
  86053. this._influences[index] = this._tempInfluences[index];
  86054. }
  86055. if (needUpdate) {
  86056. this.synchronize();
  86057. }
  86058. };
  86059. /**
  86060. * Syncrhonize the targets with all the meshes using this morph target manager
  86061. */
  86062. MorphTargetManager.prototype.synchronize = function () {
  86063. if (!this._scene) {
  86064. return;
  86065. }
  86066. // Flag meshes as dirty to resync with the active targets
  86067. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  86068. var mesh = _a[_i];
  86069. if (mesh.morphTargetManager === this) {
  86070. mesh._syncGeometryWithMorphTargetManager();
  86071. }
  86072. }
  86073. };
  86074. // Statics
  86075. /**
  86076. * Creates a new MorphTargetManager from serialized data
  86077. * @param serializationObject defines the serialized data
  86078. * @param scene defines the hosting scene
  86079. * @returns the new MorphTargetManager
  86080. */
  86081. MorphTargetManager.Parse = function (serializationObject, scene) {
  86082. var result = new MorphTargetManager(scene);
  86083. result._uniqueId = serializationObject.id;
  86084. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  86085. var targetData = _a[_i];
  86086. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  86087. }
  86088. return result;
  86089. };
  86090. return MorphTargetManager;
  86091. }());
  86092. BABYLON.MorphTargetManager = MorphTargetManager;
  86093. })(BABYLON || (BABYLON = {}));
  86094. //# sourceMappingURL=babylon.morphTargetManager.js.map
  86095. var BABYLON;
  86096. (function (BABYLON) {
  86097. var Octree = /** @class */ (function () {
  86098. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  86099. if (maxDepth === void 0) { maxDepth = 2; }
  86100. this.maxDepth = maxDepth;
  86101. this.dynamicContent = new Array();
  86102. this._maxBlockCapacity = maxBlockCapacity || 64;
  86103. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  86104. this._creationFunc = creationFunc;
  86105. }
  86106. // Methods
  86107. Octree.prototype.update = function (worldMin, worldMax, entries) {
  86108. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  86109. };
  86110. Octree.prototype.addMesh = function (entry) {
  86111. for (var index = 0; index < this.blocks.length; index++) {
  86112. var block = this.blocks[index];
  86113. block.addEntry(entry);
  86114. }
  86115. };
  86116. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  86117. this._selectionContent.reset();
  86118. for (var index = 0; index < this.blocks.length; index++) {
  86119. var block = this.blocks[index];
  86120. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  86121. }
  86122. if (allowDuplicate) {
  86123. this._selectionContent.concat(this.dynamicContent);
  86124. }
  86125. else {
  86126. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86127. }
  86128. return this._selectionContent;
  86129. };
  86130. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  86131. this._selectionContent.reset();
  86132. for (var index = 0; index < this.blocks.length; index++) {
  86133. var block = this.blocks[index];
  86134. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  86135. }
  86136. if (allowDuplicate) {
  86137. this._selectionContent.concat(this.dynamicContent);
  86138. }
  86139. else {
  86140. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86141. }
  86142. return this._selectionContent;
  86143. };
  86144. Octree.prototype.intersectsRay = function (ray) {
  86145. this._selectionContent.reset();
  86146. for (var index = 0; index < this.blocks.length; index++) {
  86147. var block = this.blocks[index];
  86148. block.intersectsRay(ray, this._selectionContent);
  86149. }
  86150. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  86151. return this._selectionContent;
  86152. };
  86153. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  86154. target.blocks = new Array();
  86155. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  86156. // Segmenting space
  86157. for (var x = 0; x < 2; x++) {
  86158. for (var y = 0; y < 2; y++) {
  86159. for (var z = 0; z < 2; z++) {
  86160. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  86161. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  86162. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  86163. block.addEntries(entries);
  86164. target.blocks.push(block);
  86165. }
  86166. }
  86167. }
  86168. };
  86169. Octree.CreationFuncForMeshes = function (entry, block) {
  86170. var boundingInfo = entry.getBoundingInfo();
  86171. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86172. block.entries.push(entry);
  86173. }
  86174. };
  86175. Octree.CreationFuncForSubMeshes = function (entry, block) {
  86176. var boundingInfo = entry.getBoundingInfo();
  86177. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  86178. block.entries.push(entry);
  86179. }
  86180. };
  86181. return Octree;
  86182. }());
  86183. BABYLON.Octree = Octree;
  86184. })(BABYLON || (BABYLON = {}));
  86185. //# sourceMappingURL=babylon.octree.js.map
  86186. var BABYLON;
  86187. (function (BABYLON) {
  86188. var OctreeBlock = /** @class */ (function () {
  86189. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  86190. this.entries = new Array();
  86191. this._boundingVectors = new Array();
  86192. this._capacity = capacity;
  86193. this._depth = depth;
  86194. this._maxDepth = maxDepth;
  86195. this._creationFunc = creationFunc;
  86196. this._minPoint = minPoint;
  86197. this._maxPoint = maxPoint;
  86198. this._boundingVectors.push(minPoint.clone());
  86199. this._boundingVectors.push(maxPoint.clone());
  86200. this._boundingVectors.push(minPoint.clone());
  86201. this._boundingVectors[2].x = maxPoint.x;
  86202. this._boundingVectors.push(minPoint.clone());
  86203. this._boundingVectors[3].y = maxPoint.y;
  86204. this._boundingVectors.push(minPoint.clone());
  86205. this._boundingVectors[4].z = maxPoint.z;
  86206. this._boundingVectors.push(maxPoint.clone());
  86207. this._boundingVectors[5].z = minPoint.z;
  86208. this._boundingVectors.push(maxPoint.clone());
  86209. this._boundingVectors[6].x = minPoint.x;
  86210. this._boundingVectors.push(maxPoint.clone());
  86211. this._boundingVectors[7].y = minPoint.y;
  86212. }
  86213. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  86214. // Property
  86215. get: function () {
  86216. return this._capacity;
  86217. },
  86218. enumerable: true,
  86219. configurable: true
  86220. });
  86221. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  86222. get: function () {
  86223. return this._minPoint;
  86224. },
  86225. enumerable: true,
  86226. configurable: true
  86227. });
  86228. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  86229. get: function () {
  86230. return this._maxPoint;
  86231. },
  86232. enumerable: true,
  86233. configurable: true
  86234. });
  86235. // Methods
  86236. OctreeBlock.prototype.addEntry = function (entry) {
  86237. if (this.blocks) {
  86238. for (var index = 0; index < this.blocks.length; index++) {
  86239. var block = this.blocks[index];
  86240. block.addEntry(entry);
  86241. }
  86242. return;
  86243. }
  86244. this._creationFunc(entry, this);
  86245. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  86246. this.createInnerBlocks();
  86247. }
  86248. };
  86249. OctreeBlock.prototype.addEntries = function (entries) {
  86250. for (var index = 0; index < entries.length; index++) {
  86251. var mesh = entries[index];
  86252. this.addEntry(mesh);
  86253. }
  86254. };
  86255. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  86256. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  86257. if (this.blocks) {
  86258. for (var index = 0; index < this.blocks.length; index++) {
  86259. var block = this.blocks[index];
  86260. block.select(frustumPlanes, selection, allowDuplicate);
  86261. }
  86262. return;
  86263. }
  86264. if (allowDuplicate) {
  86265. selection.concat(this.entries);
  86266. }
  86267. else {
  86268. selection.concatWithNoDuplicate(this.entries);
  86269. }
  86270. }
  86271. };
  86272. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  86273. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  86274. if (this.blocks) {
  86275. for (var index = 0; index < this.blocks.length; index++) {
  86276. var block = this.blocks[index];
  86277. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  86278. }
  86279. return;
  86280. }
  86281. if (allowDuplicate) {
  86282. selection.concat(this.entries);
  86283. }
  86284. else {
  86285. selection.concatWithNoDuplicate(this.entries);
  86286. }
  86287. }
  86288. };
  86289. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  86290. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  86291. if (this.blocks) {
  86292. for (var index = 0; index < this.blocks.length; index++) {
  86293. var block = this.blocks[index];
  86294. block.intersectsRay(ray, selection);
  86295. }
  86296. return;
  86297. }
  86298. selection.concatWithNoDuplicate(this.entries);
  86299. }
  86300. };
  86301. OctreeBlock.prototype.createInnerBlocks = function () {
  86302. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  86303. };
  86304. return OctreeBlock;
  86305. }());
  86306. BABYLON.OctreeBlock = OctreeBlock;
  86307. })(BABYLON || (BABYLON = {}));
  86308. //# sourceMappingURL=babylon.octreeBlock.js.map
  86309. var BABYLON;
  86310. (function (BABYLON) {
  86311. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  86312. __extends(VRDistortionCorrectionPostProcess, _super);
  86313. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  86314. var _this = _super.call(this, name, "vrDistortionCorrection", [
  86315. 'LensCenter',
  86316. 'Scale',
  86317. 'ScaleIn',
  86318. 'HmdWarpParam'
  86319. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  86320. _this._isRightEye = isRightEye;
  86321. _this._distortionFactors = vrMetrics.distortionK;
  86322. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  86323. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  86324. _this.adaptScaleToCurrentViewport = true;
  86325. _this.onSizeChangedObservable.add(function () {
  86326. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  86327. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  86328. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  86329. });
  86330. _this.onApplyObservable.add(function (effect) {
  86331. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  86332. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  86333. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  86334. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  86335. });
  86336. return _this;
  86337. }
  86338. return VRDistortionCorrectionPostProcess;
  86339. }(BABYLON.PostProcess));
  86340. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  86341. })(BABYLON || (BABYLON = {}));
  86342. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  86343. var BABYLON;
  86344. (function (BABYLON) {
  86345. /**
  86346. * Postprocess used to generate anaglyphic rendering
  86347. */
  86348. var AnaglyphPostProcess = /** @class */ (function (_super) {
  86349. __extends(AnaglyphPostProcess, _super);
  86350. /**
  86351. * Creates a new AnaglyphPostProcess
  86352. * @param name defines postprocess name
  86353. * @param options defines creation options or target ratio scale
  86354. * @param rigCameras defines cameras using this postprocess
  86355. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  86356. * @param engine defines hosting engine
  86357. * @param reusable defines if the postprocess will be reused multiple times per frame
  86358. */
  86359. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  86360. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  86361. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86362. _this.onApplyObservable.add(function (effect) {
  86363. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  86364. });
  86365. return _this;
  86366. }
  86367. return AnaglyphPostProcess;
  86368. }(BABYLON.PostProcess));
  86369. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  86370. })(BABYLON || (BABYLON = {}));
  86371. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  86372. var BABYLON;
  86373. (function (BABYLON) {
  86374. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  86375. __extends(StereoscopicInterlacePostProcess, _super);
  86376. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  86377. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  86378. _this._passedProcess = rigCameras[0]._rigPostProcess;
  86379. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86380. _this.onSizeChangedObservable.add(function () {
  86381. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  86382. });
  86383. _this.onApplyObservable.add(function (effect) {
  86384. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  86385. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  86386. });
  86387. return _this;
  86388. }
  86389. return StereoscopicInterlacePostProcess;
  86390. }(BABYLON.PostProcess));
  86391. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  86392. })(BABYLON || (BABYLON = {}));
  86393. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  86394. var BABYLON;
  86395. (function (BABYLON) {
  86396. /**
  86397. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  86398. * Screen rotation is taken into account.
  86399. */
  86400. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  86401. function FreeCameraDeviceOrientationInput() {
  86402. var _this = this;
  86403. this._screenOrientationAngle = 0;
  86404. this._screenQuaternion = new BABYLON.Quaternion();
  86405. this._alpha = 0;
  86406. this._beta = 0;
  86407. this._gamma = 0;
  86408. this._orientationChanged = function () {
  86409. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  86410. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  86411. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  86412. };
  86413. this._deviceOrientation = function (evt) {
  86414. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  86415. _this._beta = evt.beta !== null ? evt.beta : 0;
  86416. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  86417. };
  86418. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  86419. this._orientationChanged();
  86420. }
  86421. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  86422. get: function () {
  86423. return this._camera;
  86424. },
  86425. set: function (camera) {
  86426. this._camera = camera;
  86427. if (this._camera != null && !this._camera.rotationQuaternion) {
  86428. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  86429. }
  86430. },
  86431. enumerable: true,
  86432. configurable: true
  86433. });
  86434. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86435. window.addEventListener("orientationchange", this._orientationChanged);
  86436. window.addEventListener("deviceorientation", this._deviceOrientation);
  86437. //In certain cases, the attach control is called AFTER orientation was changed,
  86438. //So this is needed.
  86439. this._orientationChanged();
  86440. };
  86441. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  86442. window.removeEventListener("orientationchange", this._orientationChanged);
  86443. window.removeEventListener("deviceorientation", this._deviceOrientation);
  86444. };
  86445. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  86446. //if no device orientation provided, don't update the rotation.
  86447. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  86448. if (!this._alpha)
  86449. return;
  86450. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  86451. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  86452. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  86453. //Mirror on XY Plane
  86454. this._camera.rotationQuaternion.z *= -1;
  86455. this._camera.rotationQuaternion.w *= -1;
  86456. };
  86457. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  86458. return "FreeCameraDeviceOrientationInput";
  86459. };
  86460. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  86461. return "deviceOrientation";
  86462. };
  86463. return FreeCameraDeviceOrientationInput;
  86464. }());
  86465. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  86466. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  86467. })(BABYLON || (BABYLON = {}));
  86468. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  86469. var BABYLON;
  86470. (function (BABYLON) {
  86471. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  86472. function ArcRotateCameraVRDeviceOrientationInput() {
  86473. this.alphaCorrection = 1;
  86474. this.betaCorrection = 1;
  86475. this.gammaCorrection = 1;
  86476. this._alpha = 0;
  86477. this._gamma = 0;
  86478. this._dirty = false;
  86479. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  86480. }
  86481. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  86482. this.camera.attachControl(element, noPreventDefault);
  86483. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  86484. };
  86485. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  86486. if (evt.alpha !== null) {
  86487. this._alpha = +evt.alpha | 0;
  86488. }
  86489. if (evt.gamma !== null) {
  86490. this._gamma = +evt.gamma | 0;
  86491. }
  86492. this._dirty = true;
  86493. };
  86494. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  86495. if (this._dirty) {
  86496. this._dirty = false;
  86497. if (this._gamma < 0) {
  86498. this._gamma = 180 + this._gamma;
  86499. }
  86500. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  86501. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  86502. }
  86503. };
  86504. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  86505. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  86506. };
  86507. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  86508. return "ArcRotateCameraVRDeviceOrientationInput";
  86509. };
  86510. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  86511. return "VRDeviceOrientation";
  86512. };
  86513. return ArcRotateCameraVRDeviceOrientationInput;
  86514. }());
  86515. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  86516. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  86517. })(BABYLON || (BABYLON = {}));
  86518. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  86519. var BABYLON;
  86520. (function (BABYLON) {
  86521. var VRCameraMetrics = /** @class */ (function () {
  86522. function VRCameraMetrics() {
  86523. this.compensateDistortion = true;
  86524. }
  86525. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  86526. get: function () {
  86527. return this.hResolution / (2 * this.vResolution);
  86528. },
  86529. enumerable: true,
  86530. configurable: true
  86531. });
  86532. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  86533. get: function () {
  86534. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  86535. },
  86536. enumerable: true,
  86537. configurable: true
  86538. });
  86539. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  86540. get: function () {
  86541. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86542. var h = (4 * meters) / this.hScreenSize;
  86543. return BABYLON.Matrix.Translation(h, 0, 0);
  86544. },
  86545. enumerable: true,
  86546. configurable: true
  86547. });
  86548. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  86549. get: function () {
  86550. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  86551. var h = (4 * meters) / this.hScreenSize;
  86552. return BABYLON.Matrix.Translation(-h, 0, 0);
  86553. },
  86554. enumerable: true,
  86555. configurable: true
  86556. });
  86557. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  86558. get: function () {
  86559. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  86560. },
  86561. enumerable: true,
  86562. configurable: true
  86563. });
  86564. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  86565. get: function () {
  86566. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  86567. },
  86568. enumerable: true,
  86569. configurable: true
  86570. });
  86571. VRCameraMetrics.GetDefault = function () {
  86572. var result = new VRCameraMetrics();
  86573. result.hResolution = 1280;
  86574. result.vResolution = 800;
  86575. result.hScreenSize = 0.149759993;
  86576. result.vScreenSize = 0.0935999975;
  86577. result.vScreenCenter = 0.0467999987;
  86578. result.eyeToScreenDistance = 0.0410000011;
  86579. result.lensSeparationDistance = 0.0635000020;
  86580. result.interpupillaryDistance = 0.0640000030;
  86581. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  86582. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  86583. result.postProcessScaleFactor = 1.714605507808412;
  86584. result.lensCenterOffset = 0.151976421;
  86585. return result;
  86586. };
  86587. return VRCameraMetrics;
  86588. }());
  86589. BABYLON.VRCameraMetrics = VRCameraMetrics;
  86590. })(BABYLON || (BABYLON = {}));
  86591. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  86592. var BABYLON;
  86593. (function (BABYLON) {
  86594. /**
  86595. * This represents a WebVR camera.
  86596. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  86597. * @example http://doc.babylonjs.com/how_to/webvr_camera
  86598. */
  86599. var WebVRFreeCamera = /** @class */ (function (_super) {
  86600. __extends(WebVRFreeCamera, _super);
  86601. /**
  86602. * Instantiates a WebVRFreeCamera.
  86603. * @param name The name of the WebVRFreeCamera
  86604. * @param position The starting anchor position for the camera
  86605. * @param scene The scene the camera belongs to
  86606. * @param webVROptions a set of customizable options for the webVRCamera
  86607. */
  86608. function WebVRFreeCamera(name, position, scene, webVROptions) {
  86609. if (webVROptions === void 0) { webVROptions = {}; }
  86610. var _this = _super.call(this, name, position, scene) || this;
  86611. _this.webVROptions = webVROptions;
  86612. /**
  86613. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  86614. */
  86615. _this._vrDevice = null;
  86616. /**
  86617. * The rawPose of the vrDevice.
  86618. */
  86619. _this.rawPose = null;
  86620. _this._specsVersion = "1.1";
  86621. _this._attached = false;
  86622. _this._descendants = [];
  86623. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  86624. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  86625. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  86626. _this._standingMatrix = null;
  86627. /**
  86628. * Represents device position in babylon space.
  86629. */
  86630. _this.devicePosition = BABYLON.Vector3.Zero();
  86631. /**
  86632. * Represents device rotation in babylon space.
  86633. */
  86634. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  86635. /**
  86636. * The scale of the device to be used when translating from device space to babylon space.
  86637. */
  86638. _this.deviceScaleFactor = 1;
  86639. _this._deviceToWorld = BABYLON.Matrix.Identity();
  86640. _this._worldToDevice = BABYLON.Matrix.Identity();
  86641. /**
  86642. * References to the webVR controllers for the vrDevice.
  86643. */
  86644. _this.controllers = [];
  86645. /**
  86646. * Emits an event when a controller is attached.
  86647. */
  86648. _this.onControllersAttachedObservable = new BABYLON.Observable();
  86649. /**
  86650. * Emits an event when a controller's mesh has been loaded;
  86651. */
  86652. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  86653. /**
  86654. * If the rig cameras be used as parent instead of this camera.
  86655. */
  86656. _this.rigParenting = true;
  86657. _this._defaultHeight = undefined;
  86658. _this._workingVector = BABYLON.Vector3.Zero();
  86659. _this._oneVector = BABYLON.Vector3.One();
  86660. _this._workingMatrix = BABYLON.Matrix.Identity();
  86661. _this._cache.position = BABYLON.Vector3.Zero();
  86662. if (webVROptions.defaultHeight) {
  86663. _this._defaultHeight = webVROptions.defaultHeight;
  86664. _this.position.y = _this._defaultHeight;
  86665. }
  86666. _this.minZ = 0.1;
  86667. //legacy support - the compensation boolean was removed.
  86668. if (arguments.length === 5) {
  86669. _this.webVROptions = arguments[4];
  86670. }
  86671. // default webVR options
  86672. if (_this.webVROptions.trackPosition == undefined) {
  86673. _this.webVROptions.trackPosition = true;
  86674. }
  86675. if (_this.webVROptions.controllerMeshes == undefined) {
  86676. _this.webVROptions.controllerMeshes = true;
  86677. }
  86678. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  86679. _this.webVROptions.defaultLightingOnControllers = true;
  86680. }
  86681. _this.rotationQuaternion = new BABYLON.Quaternion();
  86682. if (_this.webVROptions && _this.webVROptions.positionScale) {
  86683. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  86684. }
  86685. //enable VR
  86686. var engine = _this.getEngine();
  86687. _this._onVREnabled = function (success) { if (success) {
  86688. _this.initControllers();
  86689. } };
  86690. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  86691. engine.initWebVR().add(function (event) {
  86692. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  86693. return;
  86694. }
  86695. _this._vrDevice = event.vrDisplay;
  86696. //reset the rig parameters.
  86697. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  86698. if (_this._attached) {
  86699. _this.getEngine().enableVR();
  86700. }
  86701. });
  86702. if (typeof (VRFrameData) !== "undefined")
  86703. _this._frameData = new VRFrameData();
  86704. /**
  86705. * The idea behind the following lines:
  86706. * objects that have the camera as parent should actually have the rig cameras as a parent.
  86707. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  86708. * the second will not show it correctly.
  86709. *
  86710. * To solve this - each object that has the camera as parent will be added to a protected array.
  86711. * When the rig camera renders, it will take this array and set all of those to be its children.
  86712. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  86713. * Amazing!
  86714. */
  86715. scene.onBeforeCameraRenderObservable.add(function (camera) {
  86716. if (camera.parent === _this && _this.rigParenting) {
  86717. _this._descendants = _this.getDescendants(true, function (n) {
  86718. // don't take the cameras or the controllers!
  86719. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  86720. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  86721. return !isController && !isRigCamera;
  86722. });
  86723. _this._descendants.forEach(function (node) {
  86724. node.parent = camera;
  86725. });
  86726. }
  86727. });
  86728. scene.onAfterCameraRenderObservable.add(function (camera) {
  86729. if (camera.parent === _this && _this.rigParenting) {
  86730. _this._descendants.forEach(function (node) {
  86731. node.parent = _this;
  86732. });
  86733. }
  86734. });
  86735. return _this;
  86736. }
  86737. /**
  86738. * Gets the device distance from the ground in meters.
  86739. * @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.
  86740. */
  86741. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  86742. if (this._standingMatrix) {
  86743. // Add standing matrix offset to get real offset from ground in room
  86744. this._standingMatrix.getTranslationToRef(this._workingVector);
  86745. return this._deviceRoomPosition.y + this._workingVector.y;
  86746. }
  86747. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  86748. return this._defaultHeight || 0;
  86749. };
  86750. /**
  86751. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86752. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  86753. */
  86754. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  86755. var _this = this;
  86756. if (callback === void 0) { callback = function (bool) { }; }
  86757. // Use standing matrix if available
  86758. this.getEngine().initWebVRAsync().then(function (result) {
  86759. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  86760. callback(false);
  86761. }
  86762. else {
  86763. _this._standingMatrix = new BABYLON.Matrix();
  86764. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  86765. if (!_this.getScene().useRightHandedSystem) {
  86766. [2, 6, 8, 9, 14].forEach(function (num) {
  86767. if (_this._standingMatrix) {
  86768. _this._standingMatrix.m[num] *= -1;
  86769. }
  86770. });
  86771. }
  86772. callback(true);
  86773. }
  86774. });
  86775. };
  86776. /**
  86777. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  86778. * @returns A promise with a boolean set to if the standing matrix is supported.
  86779. */
  86780. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  86781. var _this = this;
  86782. return new Promise(function (res, rej) {
  86783. _this.useStandingMatrix(function (supported) {
  86784. res(supported);
  86785. });
  86786. });
  86787. };
  86788. /**
  86789. * Disposes the camera
  86790. */
  86791. WebVRFreeCamera.prototype.dispose = function () {
  86792. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  86793. _super.prototype.dispose.call(this);
  86794. };
  86795. /**
  86796. * Gets a vrController by name.
  86797. * @param name The name of the controller to retreive
  86798. * @returns the controller matching the name specified or null if not found
  86799. */
  86800. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  86801. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  86802. var gp = _a[_i];
  86803. if (gp.hand === name) {
  86804. return gp;
  86805. }
  86806. }
  86807. return null;
  86808. };
  86809. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  86810. /**
  86811. * The controller corrisponding to the users left hand.
  86812. */
  86813. get: function () {
  86814. if (!this._leftController) {
  86815. this._leftController = this.getControllerByName("left");
  86816. }
  86817. return this._leftController;
  86818. },
  86819. enumerable: true,
  86820. configurable: true
  86821. });
  86822. ;
  86823. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  86824. /**
  86825. * The controller corrisponding to the users right hand.
  86826. */
  86827. get: function () {
  86828. if (!this._rightController) {
  86829. this._rightController = this.getControllerByName("right");
  86830. }
  86831. return this._rightController;
  86832. },
  86833. enumerable: true,
  86834. configurable: true
  86835. });
  86836. ;
  86837. /**
  86838. * Casts a ray forward from the vrCamera's gaze.
  86839. * @param length Length of the ray (default: 100)
  86840. * @returns the ray corrisponding to the gaze
  86841. */
  86842. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  86843. if (length === void 0) { length = 100; }
  86844. if (this.leftCamera) {
  86845. // Use left eye to avoid computation to compute center on every call
  86846. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  86847. }
  86848. else {
  86849. return _super.prototype.getForwardRay.call(this, length);
  86850. }
  86851. };
  86852. /**
  86853. * Updates the camera based on device's frame data
  86854. */
  86855. WebVRFreeCamera.prototype._checkInputs = function () {
  86856. if (this._vrDevice && this._vrDevice.isPresenting) {
  86857. this._vrDevice.getFrameData(this._frameData);
  86858. this.updateFromDevice(this._frameData.pose);
  86859. }
  86860. _super.prototype._checkInputs.call(this);
  86861. };
  86862. /**
  86863. * Updates the poseControlled values based on the input device pose.
  86864. * @param poseData Pose coming from the device
  86865. */
  86866. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  86867. if (poseData && poseData.orientation) {
  86868. this.rawPose = poseData;
  86869. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  86870. if (this.getScene().useRightHandedSystem) {
  86871. this._deviceRoomRotationQuaternion.z *= -1;
  86872. this._deviceRoomRotationQuaternion.w *= -1;
  86873. }
  86874. if (this.webVROptions.trackPosition && this.rawPose.position) {
  86875. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  86876. if (this.getScene().useRightHandedSystem) {
  86877. this._deviceRoomPosition.z *= -1;
  86878. }
  86879. }
  86880. }
  86881. };
  86882. /**
  86883. * WebVR's attach control will start broadcasting frames to the device.
  86884. * Note that in certain browsers (chrome for example) this function must be called
  86885. * within a user-interaction callback. Example:
  86886. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  86887. *
  86888. * @param element html element to attach the vrDevice to
  86889. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  86890. */
  86891. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  86892. _super.prototype.attachControl.call(this, element, noPreventDefault);
  86893. this._attached = true;
  86894. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  86895. if (this._vrDevice) {
  86896. this.getEngine().enableVR();
  86897. }
  86898. };
  86899. /**
  86900. * Detaches the camera from the html element and disables VR
  86901. *
  86902. * @param element html element to detach from
  86903. */
  86904. WebVRFreeCamera.prototype.detachControl = function (element) {
  86905. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  86906. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  86907. _super.prototype.detachControl.call(this, element);
  86908. this._attached = false;
  86909. this.getEngine().disableVR();
  86910. };
  86911. /**
  86912. * @returns the name of this class
  86913. */
  86914. WebVRFreeCamera.prototype.getClassName = function () {
  86915. return "WebVRFreeCamera";
  86916. };
  86917. /**
  86918. * Calls resetPose on the vrDisplay
  86919. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  86920. */
  86921. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  86922. //uses the vrDisplay's "resetPose()".
  86923. //pitch and roll won't be affected.
  86924. this._vrDevice.resetPose();
  86925. };
  86926. /**
  86927. * Updates the rig cameras (left and right eye)
  86928. */
  86929. WebVRFreeCamera.prototype._updateRigCameras = function () {
  86930. var camLeft = this._rigCameras[0];
  86931. var camRight = this._rigCameras[1];
  86932. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86933. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  86934. camLeft.position.copyFrom(this._deviceRoomPosition);
  86935. camRight.position.copyFrom(this._deviceRoomPosition);
  86936. };
  86937. /**
  86938. * Updates the cached values of the camera
  86939. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  86940. */
  86941. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  86942. var _this = this;
  86943. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  86944. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  86945. if (!this.updateCacheCalled) {
  86946. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  86947. this.updateCacheCalled = true;
  86948. this.update();
  86949. }
  86950. // Set working vector to the device position in room space rotated by the new rotation
  86951. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  86952. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  86953. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  86954. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  86955. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  86956. // Add translation from anchor position
  86957. this._deviceToWorld.getTranslationToRef(this._workingVector);
  86958. this._workingVector.addInPlace(this.position);
  86959. this._workingVector.subtractInPlace(this._cache.position);
  86960. this._deviceToWorld.setTranslation(this._workingVector);
  86961. // Set an inverted matrix to be used when updating the camera
  86962. this._deviceToWorld.invertToRef(this._worldToDevice);
  86963. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  86964. this.controllers.forEach(function (controller) {
  86965. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  86966. controller.update();
  86967. });
  86968. }
  86969. if (!ignoreParentClass) {
  86970. _super.prototype._updateCache.call(this);
  86971. }
  86972. this.updateCacheCalled = false;
  86973. };
  86974. /**
  86975. * Updates the current device position and rotation in the babylon world
  86976. */
  86977. WebVRFreeCamera.prototype.update = function () {
  86978. // Get current device position in babylon world
  86979. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  86980. // Get current device rotation in babylon world
  86981. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  86982. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  86983. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  86984. _super.prototype.update.call(this);
  86985. };
  86986. /**
  86987. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  86988. * @returns an identity matrix
  86989. */
  86990. WebVRFreeCamera.prototype._getViewMatrix = function () {
  86991. return BABYLON.Matrix.Identity();
  86992. };
  86993. /**
  86994. * This function is called by the two RIG cameras.
  86995. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  86996. */
  86997. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  86998. var _this = this;
  86999. // Update the parent camera prior to using a child camera to avoid desynchronization
  87000. var parentCamera = this._cameraRigParams["parentCamera"];
  87001. parentCamera._updateCache();
  87002. //WebVR 1.1
  87003. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  87004. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  87005. if (!this.getScene().useRightHandedSystem) {
  87006. [2, 6, 8, 9, 14].forEach(function (num) {
  87007. _this._webvrViewMatrix.m[num] *= -1;
  87008. });
  87009. }
  87010. // update the camera rotation matrix
  87011. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  87012. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  87013. // Computing target and final matrix
  87014. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  87015. // should the view matrix be updated with scale and position offset?
  87016. if (parentCamera.deviceScaleFactor !== 1) {
  87017. this._webvrViewMatrix.invert();
  87018. // scale the position, if set
  87019. if (parentCamera.deviceScaleFactor) {
  87020. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  87021. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  87022. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  87023. }
  87024. this._webvrViewMatrix.invert();
  87025. }
  87026. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  87027. // Compute global position
  87028. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  87029. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  87030. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  87031. this._workingMatrix.getTranslationToRef(this._globalPosition);
  87032. this._markSyncedWithParent();
  87033. return this._webvrViewMatrix;
  87034. };
  87035. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  87036. var _this = this;
  87037. var parentCamera = this.parent;
  87038. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  87039. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  87040. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  87041. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  87042. //babylon compatible matrix
  87043. if (!this.getScene().useRightHandedSystem) {
  87044. [8, 9, 10, 11].forEach(function (num) {
  87045. _this._projectionMatrix.m[num] *= -1;
  87046. });
  87047. }
  87048. return this._projectionMatrix;
  87049. };
  87050. /**
  87051. * Initializes the controllers and their meshes
  87052. */
  87053. WebVRFreeCamera.prototype.initControllers = function () {
  87054. var _this = this;
  87055. this.controllers = [];
  87056. var manager = this.getScene().gamepadManager;
  87057. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  87058. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87059. var webVrController = gamepad;
  87060. if (webVrController.defaultModel) {
  87061. webVrController.defaultModel.setEnabled(false);
  87062. }
  87063. if (webVrController.hand === "right") {
  87064. _this._rightController = null;
  87065. }
  87066. if (webVrController.hand === "left") {
  87067. _this._leftController = null;
  87068. }
  87069. var controllerIndex = _this.controllers.indexOf(webVrController);
  87070. if (controllerIndex !== -1) {
  87071. _this.controllers.splice(controllerIndex, 1);
  87072. }
  87073. }
  87074. });
  87075. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  87076. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  87077. var webVrController_1 = gamepad;
  87078. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  87079. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  87080. if (_this.webVROptions.controllerMeshes) {
  87081. if (webVrController_1.defaultModel) {
  87082. webVrController_1.defaultModel.setEnabled(true);
  87083. }
  87084. else {
  87085. // Load the meshes
  87086. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  87087. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  87088. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  87089. if (_this.webVROptions.defaultLightingOnControllers) {
  87090. if (!_this._lightOnControllers) {
  87091. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  87092. }
  87093. var activateLightOnSubMeshes_1 = function (mesh, light) {
  87094. var children = mesh.getChildren();
  87095. if (children.length !== 0) {
  87096. children.forEach(function (mesh) {
  87097. light.includedOnlyMeshes.push(mesh);
  87098. activateLightOnSubMeshes_1(mesh, light);
  87099. });
  87100. }
  87101. };
  87102. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  87103. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  87104. }
  87105. });
  87106. }
  87107. }
  87108. webVrController_1.attachToPoseControlledCamera(_this);
  87109. // since this is async - sanity check. Is the controller already stored?
  87110. if (_this.controllers.indexOf(webVrController_1) === -1) {
  87111. //add to the controllers array
  87112. _this.controllers.push(webVrController_1);
  87113. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  87114. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  87115. // So we're overriding setting left & right manually to be sure
  87116. var firstViveWandDetected = false;
  87117. for (var i = 0; i < _this.controllers.length; i++) {
  87118. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  87119. if (!firstViveWandDetected) {
  87120. firstViveWandDetected = true;
  87121. _this.controllers[i].hand = "left";
  87122. }
  87123. else {
  87124. _this.controllers[i].hand = "right";
  87125. }
  87126. }
  87127. }
  87128. //did we find enough controllers? Great! let the developer know.
  87129. if (_this.controllers.length >= 2) {
  87130. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  87131. }
  87132. }
  87133. }
  87134. });
  87135. };
  87136. return WebVRFreeCamera;
  87137. }(BABYLON.FreeCamera));
  87138. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  87139. })(BABYLON || (BABYLON = {}));
  87140. //# sourceMappingURL=babylon.webVRCamera.js.map
  87141. var BABYLON;
  87142. (function (BABYLON) {
  87143. // We're mainly based on the logic defined into the FreeCamera code
  87144. /**
  87145. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  87146. * being tilted forward or back and left or right.
  87147. */
  87148. var DeviceOrientationCamera = /** @class */ (function (_super) {
  87149. __extends(DeviceOrientationCamera, _super);
  87150. /**
  87151. * Creates a new device orientation camera
  87152. * @param name The name of the camera
  87153. * @param position The start position camera
  87154. * @param scene The scene the camera belongs to
  87155. */
  87156. function DeviceOrientationCamera(name, position, scene) {
  87157. var _this = _super.call(this, name, position, scene) || this;
  87158. _this._quaternionCache = new BABYLON.Quaternion();
  87159. _this.inputs.addDeviceOrientation();
  87160. return _this;
  87161. }
  87162. /**
  87163. * Gets the current instance class name ("DeviceOrientationCamera").
  87164. * This helps avoiding instanceof at run time.
  87165. * @returns the class name
  87166. */
  87167. DeviceOrientationCamera.prototype.getClassName = function () {
  87168. return "DeviceOrientationCamera";
  87169. };
  87170. /**
  87171. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  87172. */
  87173. DeviceOrientationCamera.prototype._checkInputs = function () {
  87174. _super.prototype._checkInputs.call(this);
  87175. this._quaternionCache.copyFrom(this.rotationQuaternion);
  87176. if (this._initialQuaternion) {
  87177. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87178. }
  87179. };
  87180. /**
  87181. * Reset the camera to its default orientation on the specified axis only.
  87182. * @param axis The axis to reset
  87183. */
  87184. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  87185. var _this = this;
  87186. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  87187. //can only work if this camera has a rotation quaternion already.
  87188. if (!this.rotationQuaternion)
  87189. return;
  87190. if (!this._initialQuaternion) {
  87191. this._initialQuaternion = new BABYLON.Quaternion();
  87192. }
  87193. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  87194. ['x', 'y', 'z'].forEach(function (axisName) {
  87195. if (!axis[axisName]) {
  87196. _this._initialQuaternion[axisName] = 0;
  87197. }
  87198. else {
  87199. _this._initialQuaternion[axisName] *= -1;
  87200. }
  87201. });
  87202. this._initialQuaternion.normalize();
  87203. //force rotation update
  87204. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  87205. };
  87206. return DeviceOrientationCamera;
  87207. }(BABYLON.FreeCamera));
  87208. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  87209. })(BABYLON || (BABYLON = {}));
  87210. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  87211. var BABYLON;
  87212. (function (BABYLON) {
  87213. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  87214. __extends(VRDeviceOrientationFreeCamera, _super);
  87215. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87216. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87217. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87218. var _this = _super.call(this, name, position, scene) || this;
  87219. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87220. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87221. return _this;
  87222. }
  87223. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  87224. return "VRDeviceOrientationFreeCamera";
  87225. };
  87226. return VRDeviceOrientationFreeCamera;
  87227. }(BABYLON.DeviceOrientationCamera));
  87228. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  87229. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  87230. __extends(VRDeviceOrientationGamepadCamera, _super);
  87231. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  87232. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87233. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87234. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  87235. _this.inputs.addGamepad();
  87236. return _this;
  87237. }
  87238. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  87239. return "VRDeviceOrientationGamepadCamera";
  87240. };
  87241. return VRDeviceOrientationGamepadCamera;
  87242. }(VRDeviceOrientationFreeCamera));
  87243. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  87244. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  87245. __extends(VRDeviceOrientationArcRotateCamera, _super);
  87246. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  87247. if (compensateDistortion === void 0) { compensateDistortion = true; }
  87248. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  87249. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87250. vrCameraMetrics.compensateDistortion = compensateDistortion;
  87251. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  87252. _this.inputs.addVRDeviceOrientation();
  87253. return _this;
  87254. }
  87255. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  87256. return "VRDeviceOrientationArcRotateCamera";
  87257. };
  87258. return VRDeviceOrientationArcRotateCamera;
  87259. }(BABYLON.ArcRotateCamera));
  87260. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  87261. })(BABYLON || (BABYLON = {}));
  87262. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  87263. var BABYLON;
  87264. (function (BABYLON) {
  87265. /**
  87266. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  87267. */
  87268. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  87269. __extends(AnaglyphFreeCamera, _super);
  87270. /**
  87271. * Creates a new AnaglyphFreeCamera
  87272. * @param name defines camera name
  87273. * @param position defines initial position
  87274. * @param interaxialDistance defines distance between each color axis
  87275. * @param scene defines the hosting scene
  87276. */
  87277. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  87278. var _this = _super.call(this, name, position, scene) || this;
  87279. _this.interaxialDistance = interaxialDistance;
  87280. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87281. return _this;
  87282. }
  87283. /**
  87284. * Gets camera class name
  87285. * @returns AnaglyphFreeCamera
  87286. */
  87287. AnaglyphFreeCamera.prototype.getClassName = function () {
  87288. return "AnaglyphFreeCamera";
  87289. };
  87290. return AnaglyphFreeCamera;
  87291. }(BABYLON.FreeCamera));
  87292. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  87293. /**
  87294. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  87295. */
  87296. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  87297. __extends(AnaglyphArcRotateCamera, _super);
  87298. /**
  87299. * Creates a new AnaglyphArcRotateCamera
  87300. * @param name defines camera name
  87301. * @param alpha defines alpha angle (in radians)
  87302. * @param beta defines beta angle (in radians)
  87303. * @param radius defines radius
  87304. * @param target defines camera target
  87305. * @param interaxialDistance defines distance between each color axis
  87306. * @param scene defines the hosting scene
  87307. */
  87308. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  87309. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87310. _this.interaxialDistance = interaxialDistance;
  87311. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87312. return _this;
  87313. }
  87314. /**
  87315. * Gets camera class name
  87316. * @returns AnaglyphArcRotateCamera
  87317. */
  87318. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  87319. return "AnaglyphArcRotateCamera";
  87320. };
  87321. return AnaglyphArcRotateCamera;
  87322. }(BABYLON.ArcRotateCamera));
  87323. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  87324. /**
  87325. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  87326. */
  87327. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  87328. __extends(AnaglyphGamepadCamera, _super);
  87329. /**
  87330. * Creates a new AnaglyphGamepadCamera
  87331. * @param name defines camera name
  87332. * @param position defines initial position
  87333. * @param interaxialDistance defines distance between each color axis
  87334. * @param scene defines the hosting scene
  87335. */
  87336. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  87337. var _this = _super.call(this, name, position, scene) || this;
  87338. _this.interaxialDistance = interaxialDistance;
  87339. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87340. return _this;
  87341. }
  87342. /**
  87343. * Gets camera class name
  87344. * @returns AnaglyphGamepadCamera
  87345. */
  87346. AnaglyphGamepadCamera.prototype.getClassName = function () {
  87347. return "AnaglyphGamepadCamera";
  87348. };
  87349. return AnaglyphGamepadCamera;
  87350. }(BABYLON.GamepadCamera));
  87351. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  87352. /**
  87353. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  87354. */
  87355. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  87356. __extends(AnaglyphUniversalCamera, _super);
  87357. /**
  87358. * Creates a new AnaglyphUniversalCamera
  87359. * @param name defines camera name
  87360. * @param position defines initial position
  87361. * @param interaxialDistance defines distance between each color axis
  87362. * @param scene defines the hosting scene
  87363. */
  87364. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  87365. var _this = _super.call(this, name, position, scene) || this;
  87366. _this.interaxialDistance = interaxialDistance;
  87367. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  87368. return _this;
  87369. }
  87370. /**
  87371. * Gets camera class name
  87372. * @returns AnaglyphUniversalCamera
  87373. */
  87374. AnaglyphUniversalCamera.prototype.getClassName = function () {
  87375. return "AnaglyphUniversalCamera";
  87376. };
  87377. return AnaglyphUniversalCamera;
  87378. }(BABYLON.UniversalCamera));
  87379. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  87380. /**
  87381. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  87382. */
  87383. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  87384. __extends(StereoscopicFreeCamera, _super);
  87385. /**
  87386. * Creates a new StereoscopicFreeCamera
  87387. * @param name defines camera name
  87388. * @param position defines initial position
  87389. * @param interaxialDistance defines distance between each color axis
  87390. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87391. * @param scene defines the hosting scene
  87392. */
  87393. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87394. var _this = _super.call(this, name, position, scene) || this;
  87395. _this.interaxialDistance = interaxialDistance;
  87396. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87397. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87398. return _this;
  87399. }
  87400. /**
  87401. * Gets camera class name
  87402. * @returns StereoscopicFreeCamera
  87403. */
  87404. StereoscopicFreeCamera.prototype.getClassName = function () {
  87405. return "StereoscopicFreeCamera";
  87406. };
  87407. return StereoscopicFreeCamera;
  87408. }(BABYLON.FreeCamera));
  87409. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  87410. /**
  87411. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  87412. */
  87413. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  87414. __extends(StereoscopicArcRotateCamera, _super);
  87415. /**
  87416. * Creates a new StereoscopicArcRotateCamera
  87417. * @param name defines camera name
  87418. * @param alpha defines alpha angle (in radians)
  87419. * @param beta defines beta angle (in radians)
  87420. * @param radius defines radius
  87421. * @param target defines camera target
  87422. * @param interaxialDistance defines distance between each color axis
  87423. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87424. * @param scene defines the hosting scene
  87425. */
  87426. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  87427. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  87428. _this.interaxialDistance = interaxialDistance;
  87429. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87430. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87431. return _this;
  87432. }
  87433. /**
  87434. * Gets camera class name
  87435. * @returns StereoscopicArcRotateCamera
  87436. */
  87437. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  87438. return "StereoscopicArcRotateCamera";
  87439. };
  87440. return StereoscopicArcRotateCamera;
  87441. }(BABYLON.ArcRotateCamera));
  87442. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  87443. /**
  87444. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  87445. */
  87446. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  87447. __extends(StereoscopicGamepadCamera, _super);
  87448. /**
  87449. * Creates a new StereoscopicGamepadCamera
  87450. * @param name defines camera name
  87451. * @param position defines initial position
  87452. * @param interaxialDistance defines distance between each color axis
  87453. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87454. * @param scene defines the hosting scene
  87455. */
  87456. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87457. var _this = _super.call(this, name, position, scene) || this;
  87458. _this.interaxialDistance = interaxialDistance;
  87459. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87460. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87461. return _this;
  87462. }
  87463. /**
  87464. * Gets camera class name
  87465. * @returns StereoscopicGamepadCamera
  87466. */
  87467. StereoscopicGamepadCamera.prototype.getClassName = function () {
  87468. return "StereoscopicGamepadCamera";
  87469. };
  87470. return StereoscopicGamepadCamera;
  87471. }(BABYLON.GamepadCamera));
  87472. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  87473. /**
  87474. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  87475. */
  87476. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  87477. __extends(StereoscopicUniversalCamera, _super);
  87478. /**
  87479. * Creates a new StereoscopicUniversalCamera
  87480. * @param name defines camera name
  87481. * @param position defines initial position
  87482. * @param interaxialDistance defines distance between each color axis
  87483. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  87484. * @param scene defines the hosting scene
  87485. */
  87486. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  87487. var _this = _super.call(this, name, position, scene) || this;
  87488. _this.interaxialDistance = interaxialDistance;
  87489. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  87490. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  87491. return _this;
  87492. }
  87493. /**
  87494. * Gets camera class name
  87495. * @returns StereoscopicUniversalCamera
  87496. */
  87497. StereoscopicUniversalCamera.prototype.getClassName = function () {
  87498. return "StereoscopicUniversalCamera";
  87499. };
  87500. return StereoscopicUniversalCamera;
  87501. }(BABYLON.UniversalCamera));
  87502. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  87503. })(BABYLON || (BABYLON = {}));
  87504. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  87505. var BABYLON;
  87506. (function (BABYLON) {
  87507. var VRExperienceHelperGazer = /** @class */ (function () {
  87508. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  87509. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  87510. this.scene = scene;
  87511. this._pointerDownOnMeshAsked = false;
  87512. this._isActionableMesh = false;
  87513. this._teleportationRequestInitiated = false;
  87514. this._teleportationBackRequestInitiated = false;
  87515. this._rotationRightAsked = false;
  87516. this._rotationLeftAsked = false;
  87517. this._dpadPressed = true;
  87518. this._activePointer = false;
  87519. this._id = VRExperienceHelperGazer._idCounter++;
  87520. // Gaze tracker
  87521. if (!gazeTrackerToClone) {
  87522. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  87523. this._gazeTracker.bakeCurrentTransformIntoVertices();
  87524. this._gazeTracker.isPickable = false;
  87525. this._gazeTracker.isVisible = false;
  87526. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  87527. targetMat.specularColor = BABYLON.Color3.Black();
  87528. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87529. targetMat.backFaceCulling = false;
  87530. this._gazeTracker.material = targetMat;
  87531. }
  87532. else {
  87533. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  87534. }
  87535. }
  87536. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  87537. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  87538. };
  87539. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  87540. this._pointerDownOnMeshAsked = true;
  87541. if (this._currentMeshSelected && this._currentHit) {
  87542. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  87543. }
  87544. };
  87545. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  87546. if (this._currentMeshSelected && this._currentHit) {
  87547. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  87548. }
  87549. this._pointerDownOnMeshAsked = false;
  87550. };
  87551. VRExperienceHelperGazer.prototype._activatePointer = function () {
  87552. this._activePointer = true;
  87553. };
  87554. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  87555. this._activePointer = false;
  87556. };
  87557. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  87558. if (distance === void 0) { distance = 100; }
  87559. };
  87560. VRExperienceHelperGazer.prototype.dispose = function () {
  87561. this._interactionsEnabled = false;
  87562. this._teleportationEnabled = false;
  87563. if (this._gazeTracker) {
  87564. this._gazeTracker.dispose();
  87565. }
  87566. };
  87567. VRExperienceHelperGazer._idCounter = 0;
  87568. return VRExperienceHelperGazer;
  87569. }());
  87570. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  87571. __extends(VRExperienceHelperControllerGazer, _super);
  87572. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  87573. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  87574. _this.webVRController = webVRController;
  87575. // Laser pointer
  87576. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  87577. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  87578. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  87579. laserPointerMaterial.alpha = 0.6;
  87580. _this._laserPointer.material = laserPointerMaterial;
  87581. _this._laserPointer.rotation.x = Math.PI / 2;
  87582. _this._laserPointer.position.z = -0.5;
  87583. _this._laserPointer.isVisible = false;
  87584. if (!webVRController.mesh) {
  87585. // Create an empty mesh that is used prior to loading the high quality model
  87586. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  87587. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  87588. preloadPointerPose.rotation.x = -0.7;
  87589. preloadMesh.addChild(preloadPointerPose);
  87590. webVRController.attachToMesh(preloadMesh);
  87591. }
  87592. _this._setLaserPointerParent(webVRController.mesh);
  87593. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  87594. _this._setLaserPointerParent(mesh);
  87595. });
  87596. return _this;
  87597. }
  87598. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  87599. return this.webVRController.getForwardRay(length);
  87600. };
  87601. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  87602. _super.prototype._activatePointer.call(this);
  87603. this._laserPointer.isVisible = true;
  87604. };
  87605. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  87606. _super.prototype._deactivatePointer.call(this);
  87607. this._laserPointer.isVisible = false;
  87608. };
  87609. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  87610. this._laserPointer.material.emissiveColor = color;
  87611. };
  87612. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  87613. var makeNotPick = function (root) {
  87614. root.name += " laserPointer";
  87615. root.getChildMeshes().forEach(function (c) {
  87616. makeNotPick(c);
  87617. });
  87618. };
  87619. makeNotPick(mesh);
  87620. var childMeshes = mesh.getChildMeshes();
  87621. this.webVRController._pointingPoseNode = null;
  87622. for (var i = 0; i < childMeshes.length; i++) {
  87623. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  87624. mesh = childMeshes[i];
  87625. this.webVRController._pointingPoseNode = mesh;
  87626. break;
  87627. }
  87628. }
  87629. this._laserPointer.parent = mesh;
  87630. };
  87631. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  87632. if (distance === void 0) { distance = 100; }
  87633. this._laserPointer.scaling.y = distance;
  87634. this._laserPointer.position.z = -distance / 2;
  87635. };
  87636. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  87637. _super.prototype.dispose.call(this);
  87638. this._laserPointer.dispose();
  87639. if (this._meshAttachedObserver) {
  87640. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  87641. }
  87642. };
  87643. return VRExperienceHelperControllerGazer;
  87644. }(VRExperienceHelperGazer));
  87645. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  87646. __extends(VRExperienceHelperCameraGazer, _super);
  87647. function VRExperienceHelperCameraGazer(getCamera, scene) {
  87648. var _this = _super.call(this, scene) || this;
  87649. _this.getCamera = getCamera;
  87650. return _this;
  87651. }
  87652. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  87653. var camera = this.getCamera();
  87654. if (camera) {
  87655. return camera.getForwardRay(length);
  87656. }
  87657. else {
  87658. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  87659. }
  87660. };
  87661. return VRExperienceHelperCameraGazer;
  87662. }(VRExperienceHelperGazer));
  87663. /**
  87664. * Helps to quickly add VR support to an existing scene.
  87665. * See http://doc.babylonjs.com/how_to/webvr_helper
  87666. */
  87667. var VRExperienceHelper = /** @class */ (function () {
  87668. /**
  87669. * Instantiates a VRExperienceHelper.
  87670. * Helps to quickly add VR support to an existing scene.
  87671. * @param scene The scene the VRExperienceHelper belongs to.
  87672. * @param webVROptions Options to modify the vr experience helper's behavior.
  87673. */
  87674. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  87675. if (webVROptions === void 0) { webVROptions = {}; }
  87676. var _this = this;
  87677. this.webVROptions = webVROptions;
  87678. // Can the system support WebVR, even if a headset isn't plugged in?
  87679. this._webVRsupported = false;
  87680. // If WebVR is supported, is a headset plugged in and are we ready to present?
  87681. this._webVRready = false;
  87682. // Are we waiting for the requestPresent callback to complete?
  87683. this._webVRrequesting = false;
  87684. // Are we presenting to the headset right now?
  87685. this._webVRpresenting = false;
  87686. // Are we presenting in the fullscreen fallback?
  87687. this._fullscreenVRpresenting = false;
  87688. /**
  87689. * Observable raised when entering VR.
  87690. */
  87691. this.onEnteringVRObservable = new BABYLON.Observable();
  87692. /**
  87693. * Observable raised when exiting VR.
  87694. */
  87695. this.onExitingVRObservable = new BABYLON.Observable();
  87696. /**
  87697. * Observable raised when controller mesh is loaded.
  87698. */
  87699. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  87700. this._useCustomVRButton = false;
  87701. this._teleportationRequested = false;
  87702. this._teleportActive = false;
  87703. this._floorMeshesCollection = [];
  87704. this._rotationAllowed = true;
  87705. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  87706. this._isDefaultTeleportationTarget = true;
  87707. this._teleportationFillColor = "#444444";
  87708. this._teleportationBorderColor = "#FFFFFF";
  87709. this._rotationAngle = 0;
  87710. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  87711. this._padSensibilityUp = 0.65;
  87712. this._padSensibilityDown = 0.35;
  87713. this.leftController = null;
  87714. this.rightController = null;
  87715. /**
  87716. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  87717. */
  87718. this.onNewMeshSelected = new BABYLON.Observable();
  87719. /**
  87720. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  87721. */
  87722. this.onNewMeshPicked = new BABYLON.Observable();
  87723. /**
  87724. * Observable raised before camera teleportation
  87725. */
  87726. this.onBeforeCameraTeleport = new BABYLON.Observable();
  87727. /**
  87728. * Observable raised after camera teleportation
  87729. */
  87730. this.onAfterCameraTeleport = new BABYLON.Observable();
  87731. /**
  87732. * Observable raised when current selected mesh gets unselected
  87733. */
  87734. this.onSelectedMeshUnselected = new BABYLON.Observable();
  87735. /**
  87736. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  87737. */
  87738. this.teleportationEnabled = true;
  87739. this._teleportationInitialized = false;
  87740. this._interactionsEnabled = false;
  87741. this._interactionsRequested = false;
  87742. this._displayGaze = true;
  87743. this._displayLaserPointer = true;
  87744. this._onResize = function () {
  87745. _this.moveButtonToBottomRight();
  87746. if (_this._fullscreenVRpresenting && _this._webVRready) {
  87747. _this.exitVR();
  87748. }
  87749. };
  87750. this._onFullscreenChange = function () {
  87751. if (document.fullscreen !== undefined) {
  87752. _this._fullscreenVRpresenting = document.fullscreen;
  87753. }
  87754. else if (document.mozFullScreen !== undefined) {
  87755. _this._fullscreenVRpresenting = document.mozFullScreen;
  87756. }
  87757. else if (document.webkitIsFullScreen !== undefined) {
  87758. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  87759. }
  87760. else if (document.msIsFullScreen !== undefined) {
  87761. _this._fullscreenVRpresenting = document.msIsFullScreen;
  87762. }
  87763. if (!_this._fullscreenVRpresenting && _this._canvas) {
  87764. _this.exitVR();
  87765. if (!_this._useCustomVRButton) {
  87766. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  87767. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  87768. }
  87769. }
  87770. };
  87771. this.beforeRender = function () {
  87772. if (_this.leftController && _this.leftController._activePointer) {
  87773. _this._castRayAndSelectObject(_this.leftController);
  87774. }
  87775. if (_this.rightController && _this.rightController._activePointer) {
  87776. _this._castRayAndSelectObject(_this.rightController);
  87777. }
  87778. if (!(_this.leftController && _this.leftController._activePointer) && !(_this.rightController && _this.rightController._activePointer)) {
  87779. _this._castRayAndSelectObject(_this._cameraGazer);
  87780. }
  87781. else {
  87782. _this._cameraGazer._gazeTracker.isVisible = false;
  87783. }
  87784. };
  87785. this._onNewGamepadConnected = function (gamepad) {
  87786. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  87787. if (gamepad.leftStick) {
  87788. gamepad.onleftstickchanged(function (stickValues) {
  87789. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  87790. // Listening to classic/xbox gamepad only if no VR controller is active
  87791. if ((!_this.leftController && !_this.rightController) ||
  87792. ((_this.leftController && !_this.leftController._activePointer) &&
  87793. (_this.rightController && !_this.rightController._activePointer))) {
  87794. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  87795. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  87796. }
  87797. }
  87798. });
  87799. }
  87800. if (gamepad.rightStick) {
  87801. gamepad.onrightstickchanged(function (stickValues) {
  87802. if (_this._teleportationInitialized) {
  87803. _this._checkRotate(stickValues, _this._cameraGazer);
  87804. }
  87805. });
  87806. }
  87807. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  87808. gamepad.onbuttondown(function (buttonPressed) {
  87809. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87810. _this._cameraGazer._selectionPointerDown();
  87811. }
  87812. });
  87813. gamepad.onbuttonup(function (buttonPressed) {
  87814. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  87815. _this._cameraGazer._selectionPointerUp();
  87816. }
  87817. });
  87818. }
  87819. }
  87820. else {
  87821. var webVRController = gamepad;
  87822. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  87823. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  87824. _this.rightController = controller;
  87825. }
  87826. else {
  87827. _this.leftController = controller;
  87828. }
  87829. _this._tryEnableInteractionOnController(controller);
  87830. }
  87831. };
  87832. // 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
  87833. this._tryEnableInteractionOnController = function (controller) {
  87834. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  87835. _this._enableInteractionOnController(controller);
  87836. }
  87837. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  87838. _this._enableTeleportationOnController(controller);
  87839. }
  87840. };
  87841. this._onNewGamepadDisconnected = function (gamepad) {
  87842. if (gamepad instanceof BABYLON.WebVRController) {
  87843. if (gamepad.hand === "left" && _this.leftController != null) {
  87844. _this.leftController.dispose();
  87845. _this.leftController = null;
  87846. }
  87847. if (gamepad.hand === "right" && _this.rightController != null) {
  87848. _this.rightController.dispose();
  87849. _this.rightController = null;
  87850. }
  87851. }
  87852. };
  87853. this._workingVector = BABYLON.Vector3.Zero();
  87854. this._workingQuaternion = BABYLON.Quaternion.Identity();
  87855. this._workingMatrix = BABYLON.Matrix.Identity();
  87856. this._scene = scene;
  87857. this._canvas = scene.getEngine().getRenderingCanvas();
  87858. // Parse options
  87859. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  87860. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  87861. }
  87862. if (webVROptions.createDeviceOrientationCamera === undefined) {
  87863. webVROptions.createDeviceOrientationCamera = true;
  87864. }
  87865. if (webVROptions.defaultHeight === undefined) {
  87866. webVROptions.defaultHeight = 1.7;
  87867. }
  87868. if (webVROptions.useCustomVRButton) {
  87869. this._useCustomVRButton = true;
  87870. if (webVROptions.customVRButton) {
  87871. this._btnVR = webVROptions.customVRButton;
  87872. }
  87873. }
  87874. if (webVROptions.rayLength) {
  87875. this._rayLength = webVROptions.rayLength;
  87876. }
  87877. this._defaultHeight = webVROptions.defaultHeight;
  87878. if (webVROptions.positionScale) {
  87879. this._rayLength *= webVROptions.positionScale;
  87880. this._defaultHeight *= webVROptions.positionScale;
  87881. }
  87882. // Set position
  87883. if (this._scene.activeCamera) {
  87884. this._position = this._scene.activeCamera.position.clone();
  87885. }
  87886. else {
  87887. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  87888. }
  87889. // Set non-vr camera
  87890. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  87891. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  87892. // Copy data from existing camera
  87893. if (this._scene.activeCamera) {
  87894. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  87895. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  87896. // Set rotation from previous camera
  87897. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  87898. var targetCamera = this._scene.activeCamera;
  87899. if (targetCamera.rotationQuaternion) {
  87900. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  87901. }
  87902. else {
  87903. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  87904. }
  87905. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  87906. }
  87907. }
  87908. this._scene.activeCamera = this._deviceOrientationCamera;
  87909. if (this._canvas) {
  87910. this._scene.activeCamera.attachControl(this._canvas);
  87911. }
  87912. }
  87913. else {
  87914. this._existingCamera = this._scene.activeCamera;
  87915. }
  87916. // Create VR cameras
  87917. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87918. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  87919. }
  87920. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  87921. this._webVRCamera.useStandingMatrix();
  87922. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  87923. // Create default button
  87924. if (!this._useCustomVRButton) {
  87925. this._btnVR = document.createElement("BUTTON");
  87926. this._btnVR.className = "babylonVRicon";
  87927. this._btnVR.id = "babylonVRiconbtn";
  87928. this._btnVR.title = "Click to switch to VR";
  87929. 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) }";
  87930. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  87931. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  87932. // css += ".babylonVRicon.vrdisplaysupported { }";
  87933. // css += ".babylonVRicon.vrdisplayready { }";
  87934. // css += ".babylonVRicon.vrdisplayrequesting { }";
  87935. var style = document.createElement('style');
  87936. style.appendChild(document.createTextNode(css));
  87937. document.getElementsByTagName('head')[0].appendChild(style);
  87938. this.moveButtonToBottomRight();
  87939. }
  87940. // VR button click event
  87941. if (this._btnVR) {
  87942. this._btnVR.addEventListener("click", function () {
  87943. if (!_this.isInVRMode) {
  87944. _this.enterVR();
  87945. }
  87946. else {
  87947. _this.exitVR();
  87948. }
  87949. });
  87950. }
  87951. // Window events
  87952. window.addEventListener("resize", this._onResize);
  87953. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  87954. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  87955. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  87956. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  87957. // Display vr button when headset is connected
  87958. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  87959. this.displayVRButton();
  87960. }
  87961. else {
  87962. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  87963. if (e.vrDisplay) {
  87964. _this.displayVRButton();
  87965. }
  87966. });
  87967. }
  87968. // Exiting VR mode using 'ESC' key on desktop
  87969. this._onKeyDown = function (event) {
  87970. if (event.keyCode === 27 && _this.isInVRMode) {
  87971. _this.exitVR();
  87972. }
  87973. };
  87974. document.addEventListener("keydown", this._onKeyDown);
  87975. // Exiting VR mode double tapping the touch screen
  87976. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  87977. if (_this.isInVRMode) {
  87978. _this.exitVR();
  87979. if (_this._fullscreenVRpresenting) {
  87980. _this._scene.getEngine().switchFullscreen(true);
  87981. }
  87982. }
  87983. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  87984. // Listen for WebVR display changes
  87985. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  87986. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  87987. this._onVRRequestPresentStart = function () {
  87988. _this._webVRrequesting = true;
  87989. _this.updateButtonVisibility();
  87990. };
  87991. this._onVRRequestPresentComplete = function (success) {
  87992. _this._webVRrequesting = false;
  87993. _this.updateButtonVisibility();
  87994. };
  87995. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  87996. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  87997. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  87998. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  87999. scene.onDisposeObservable.add(function () {
  88000. _this.dispose();
  88001. });
  88002. // Gamepad connection events
  88003. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  88004. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  88005. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  88006. this.updateButtonVisibility();
  88007. //create easing functions
  88008. this._circleEase = new BABYLON.CircleEase();
  88009. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88010. }
  88011. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  88012. /** Return this.onEnteringVRObservable
  88013. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  88014. */
  88015. get: function () {
  88016. return this.onEnteringVRObservable;
  88017. },
  88018. enumerable: true,
  88019. configurable: true
  88020. });
  88021. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  88022. /** Return this.onExitingVRObservable
  88023. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  88024. */
  88025. get: function () {
  88026. return this.onExitingVRObservable;
  88027. },
  88028. enumerable: true,
  88029. configurable: true
  88030. });
  88031. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  88032. /** Return this.onControllerMeshLoadedObservable
  88033. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  88034. */
  88035. get: function () {
  88036. return this.onControllerMeshLoadedObservable;
  88037. },
  88038. enumerable: true,
  88039. configurable: true
  88040. });
  88041. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  88042. /**
  88043. * The mesh used to display where the user is going to teleport.
  88044. */
  88045. get: function () {
  88046. return this._teleportationTarget;
  88047. },
  88048. /**
  88049. * Sets the mesh to be used to display where the user is going to teleport.
  88050. */
  88051. set: function (value) {
  88052. if (value) {
  88053. value.name = "teleportationTarget";
  88054. this._isDefaultTeleportationTarget = false;
  88055. this._teleportationTarget = value;
  88056. }
  88057. },
  88058. enumerable: true,
  88059. configurable: true
  88060. });
  88061. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  88062. /**
  88063. * The mesh used to display where the user is selecting,
  88064. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  88065. * See http://doc.babylonjs.com/resources/baking_transformations
  88066. */
  88067. get: function () {
  88068. return this._cameraGazer._gazeTracker;
  88069. },
  88070. set: function (value) {
  88071. if (value) {
  88072. this._cameraGazer._gazeTracker = value;
  88073. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  88074. this._cameraGazer._gazeTracker.isPickable = false;
  88075. this._cameraGazer._gazeTracker.isVisible = false;
  88076. this._cameraGazer._gazeTracker.name = "gazeTracker";
  88077. if (this.leftController) {
  88078. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88079. }
  88080. if (this.rightController) {
  88081. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  88082. }
  88083. }
  88084. },
  88085. enumerable: true,
  88086. configurable: true
  88087. });
  88088. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  88089. /**
  88090. * If the ray of the gaze should be displayed.
  88091. */
  88092. get: function () {
  88093. return this._displayGaze;
  88094. },
  88095. /**
  88096. * Sets if the ray of the gaze should be displayed.
  88097. */
  88098. set: function (value) {
  88099. this._displayGaze = value;
  88100. if (!value) {
  88101. this._cameraGazer._gazeTracker.isVisible = false;
  88102. if (this.leftController) {
  88103. this.leftController._gazeTracker.isVisible = false;
  88104. }
  88105. if (this.rightController) {
  88106. this.rightController._gazeTracker.isVisible = false;
  88107. }
  88108. }
  88109. },
  88110. enumerable: true,
  88111. configurable: true
  88112. });
  88113. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  88114. /**
  88115. * If the ray of the LaserPointer should be displayed.
  88116. */
  88117. get: function () {
  88118. return this._displayLaserPointer;
  88119. },
  88120. /**
  88121. * Sets if the ray of the LaserPointer should be displayed.
  88122. */
  88123. set: function (value) {
  88124. this._displayLaserPointer = value;
  88125. if (!value) {
  88126. if (this.rightController) {
  88127. this.rightController._deactivatePointer();
  88128. this.rightController._gazeTracker.isVisible = false;
  88129. }
  88130. if (this.leftController) {
  88131. this.leftController._deactivatePointer();
  88132. this.leftController._gazeTracker.isVisible = false;
  88133. }
  88134. }
  88135. else {
  88136. if (this.rightController) {
  88137. this.rightController._activatePointer();
  88138. }
  88139. if (this.leftController) {
  88140. this.leftController._activatePointer();
  88141. }
  88142. }
  88143. },
  88144. enumerable: true,
  88145. configurable: true
  88146. });
  88147. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  88148. /**
  88149. * The deviceOrientationCamera used as the camera when not in VR.
  88150. */
  88151. get: function () {
  88152. return this._deviceOrientationCamera;
  88153. },
  88154. enumerable: true,
  88155. configurable: true
  88156. });
  88157. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  88158. /**
  88159. * Based on the current WebVR support, returns the current VR camera used.
  88160. */
  88161. get: function () {
  88162. if (this._webVRready) {
  88163. return this._webVRCamera;
  88164. }
  88165. else {
  88166. return this._scene.activeCamera;
  88167. }
  88168. },
  88169. enumerable: true,
  88170. configurable: true
  88171. });
  88172. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  88173. /**
  88174. * The webVRCamera which is used when in VR.
  88175. */
  88176. get: function () {
  88177. return this._webVRCamera;
  88178. },
  88179. enumerable: true,
  88180. configurable: true
  88181. });
  88182. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  88183. /**
  88184. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  88185. */
  88186. get: function () {
  88187. return this._vrDeviceOrientationCamera;
  88188. },
  88189. enumerable: true,
  88190. configurable: true
  88191. });
  88192. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  88193. get: function () {
  88194. var result = this._cameraGazer._teleportationRequestInitiated
  88195. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  88196. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  88197. return result;
  88198. },
  88199. enumerable: true,
  88200. configurable: true
  88201. });
  88202. // Raised when one of the controller has loaded successfully its associated default mesh
  88203. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  88204. if (this.leftController && this.leftController.webVRController == webVRController) {
  88205. if (webVRController.mesh) {
  88206. this.leftController._setLaserPointerParent(webVRController.mesh);
  88207. }
  88208. }
  88209. if (this.rightController && this.rightController.webVRController == webVRController) {
  88210. if (webVRController.mesh) {
  88211. this.rightController._setLaserPointerParent(webVRController.mesh);
  88212. }
  88213. }
  88214. try {
  88215. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  88216. }
  88217. catch (err) {
  88218. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  88219. }
  88220. };
  88221. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  88222. /**
  88223. * Gets a value indicating if we are currently in VR mode.
  88224. */
  88225. get: function () {
  88226. return this._webVRpresenting || this._fullscreenVRpresenting;
  88227. },
  88228. enumerable: true,
  88229. configurable: true
  88230. });
  88231. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  88232. var vrDisplay = this._scene.getEngine().getVRDevice();
  88233. if (vrDisplay) {
  88234. var wasPresenting = this._webVRpresenting;
  88235. // A VR display is connected
  88236. this._webVRpresenting = vrDisplay.isPresenting;
  88237. if (wasPresenting && !this._webVRpresenting)
  88238. this.exitVR();
  88239. }
  88240. else {
  88241. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  88242. }
  88243. this.updateButtonVisibility();
  88244. };
  88245. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  88246. this._webVRsupported = eventArgs.vrSupported;
  88247. this._webVRready = !!eventArgs.vrDisplay;
  88248. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  88249. this.updateButtonVisibility();
  88250. };
  88251. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  88252. if (this._canvas && !this._useCustomVRButton) {
  88253. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  88254. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  88255. }
  88256. };
  88257. VRExperienceHelper.prototype.displayVRButton = function () {
  88258. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  88259. document.body.appendChild(this._btnVR);
  88260. this._btnVRDisplayed = true;
  88261. }
  88262. };
  88263. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  88264. if (!this._btnVR || this._useCustomVRButton) {
  88265. return;
  88266. }
  88267. this._btnVR.className = "babylonVRicon";
  88268. if (this.isInVRMode) {
  88269. this._btnVR.className += " vrdisplaypresenting";
  88270. }
  88271. else {
  88272. if (this._webVRready)
  88273. this._btnVR.className += " vrdisplayready";
  88274. if (this._webVRsupported)
  88275. this._btnVR.className += " vrdisplaysupported";
  88276. if (this._webVRrequesting)
  88277. this._btnVR.className += " vrdisplayrequesting";
  88278. }
  88279. };
  88280. /**
  88281. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  88282. * Otherwise, will use the fullscreen API.
  88283. */
  88284. VRExperienceHelper.prototype.enterVR = function () {
  88285. if (this.onEnteringVRObservable) {
  88286. try {
  88287. this.onEnteringVRObservable.notifyObservers(this);
  88288. }
  88289. catch (err) {
  88290. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  88291. }
  88292. }
  88293. if (this._scene.activeCamera) {
  88294. this._position = this._scene.activeCamera.position.clone();
  88295. // make sure that we return to the last active camera
  88296. this._existingCamera = this._scene.activeCamera;
  88297. }
  88298. if (this._webVRrequesting)
  88299. return;
  88300. // If WebVR is supported and a headset is connected
  88301. if (this._webVRready) {
  88302. if (!this._webVRpresenting) {
  88303. this._webVRCamera.position = this._position;
  88304. this._scene.activeCamera = this._webVRCamera;
  88305. }
  88306. }
  88307. else if (this._vrDeviceOrientationCamera) {
  88308. this._vrDeviceOrientationCamera.position = this._position;
  88309. if (this._scene.activeCamera) {
  88310. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  88311. }
  88312. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  88313. this._scene.getEngine().switchFullscreen(true);
  88314. this.updateButtonVisibility();
  88315. }
  88316. if (this._scene.activeCamera && this._canvas) {
  88317. this._scene.activeCamera.attachControl(this._canvas);
  88318. }
  88319. if (this._interactionsEnabled) {
  88320. this._scene.registerBeforeRender(this.beforeRender);
  88321. }
  88322. };
  88323. /**
  88324. * Attempt to exit VR, or fullscreen.
  88325. */
  88326. VRExperienceHelper.prototype.exitVR = function () {
  88327. if (this.onExitingVRObservable) {
  88328. try {
  88329. this.onExitingVRObservable.notifyObservers(this);
  88330. }
  88331. catch (err) {
  88332. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  88333. }
  88334. }
  88335. if (this._webVRpresenting) {
  88336. this._scene.getEngine().disableVR();
  88337. }
  88338. if (this._scene.activeCamera) {
  88339. this._position = this._scene.activeCamera.position.clone();
  88340. }
  88341. if (this._deviceOrientationCamera) {
  88342. this._deviceOrientationCamera.position = this._position;
  88343. this._scene.activeCamera = this._deviceOrientationCamera;
  88344. if (this._canvas) {
  88345. this._scene.activeCamera.attachControl(this._canvas);
  88346. }
  88347. }
  88348. else if (this._existingCamera) {
  88349. this._existingCamera.position = this._position;
  88350. this._scene.activeCamera = this._existingCamera;
  88351. }
  88352. this.updateButtonVisibility();
  88353. if (this._interactionsEnabled) {
  88354. this._scene.unregisterBeforeRender(this.beforeRender);
  88355. }
  88356. // resize to update width and height when exiting vr exits fullscreen
  88357. this._scene.getEngine().resize();
  88358. };
  88359. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  88360. /**
  88361. * The position of the vr experience helper.
  88362. */
  88363. get: function () {
  88364. return this._position;
  88365. },
  88366. /**
  88367. * Sets the position of the vr experience helper.
  88368. */
  88369. set: function (value) {
  88370. this._position = value;
  88371. if (this._scene.activeCamera) {
  88372. this._scene.activeCamera.position = value;
  88373. }
  88374. },
  88375. enumerable: true,
  88376. configurable: true
  88377. });
  88378. /**
  88379. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  88380. */
  88381. VRExperienceHelper.prototype.enableInteractions = function () {
  88382. var _this = this;
  88383. if (!this._interactionsEnabled) {
  88384. this._interactionsRequested = true;
  88385. if (this.leftController) {
  88386. this._enableInteractionOnController(this.leftController);
  88387. }
  88388. if (this.rightController) {
  88389. this._enableInteractionOnController(this.rightController);
  88390. }
  88391. this.raySelectionPredicate = function (mesh) {
  88392. return mesh.isVisible;
  88393. };
  88394. this.meshSelectionPredicate = function (mesh) {
  88395. return true;
  88396. };
  88397. this._raySelectionPredicate = function (mesh) {
  88398. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  88399. && mesh.name.indexOf("teleportationTarget") === -1
  88400. && mesh.name.indexOf("torusTeleportation") === -1
  88401. && mesh.name.indexOf("laserPointer") === -1)) {
  88402. return _this.raySelectionPredicate(mesh);
  88403. }
  88404. return false;
  88405. };
  88406. this._interactionsEnabled = true;
  88407. }
  88408. };
  88409. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  88410. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  88411. if (this._floorMeshesCollection[i].id === mesh.id) {
  88412. return true;
  88413. }
  88414. }
  88415. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  88416. return true;
  88417. }
  88418. return false;
  88419. };
  88420. /**
  88421. * Adds a floor mesh to be used for teleportation.
  88422. * @param floorMesh the mesh to be used for teleportation.
  88423. */
  88424. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  88425. if (!this._floorMeshesCollection) {
  88426. return;
  88427. }
  88428. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  88429. return;
  88430. }
  88431. this._floorMeshesCollection.push(floorMesh);
  88432. };
  88433. /**
  88434. * Removes a floor mesh from being used for teleportation.
  88435. * @param floorMesh the mesh to be removed.
  88436. */
  88437. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  88438. if (!this._floorMeshesCollection) {
  88439. return;
  88440. }
  88441. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  88442. if (meshIndex !== -1) {
  88443. this._floorMeshesCollection.splice(meshIndex, 1);
  88444. }
  88445. };
  88446. /**
  88447. * Enables interactions and teleportation using the VR controllers and gaze.
  88448. * @param vrTeleportationOptions options to modify teleportation behavior.
  88449. */
  88450. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  88451. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  88452. if (!this._teleportationInitialized) {
  88453. this._teleportationRequested = true;
  88454. this.enableInteractions();
  88455. if (vrTeleportationOptions.floorMeshName) {
  88456. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  88457. }
  88458. if (vrTeleportationOptions.floorMeshes) {
  88459. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  88460. }
  88461. if (this.leftController != null) {
  88462. this._enableTeleportationOnController(this.leftController);
  88463. }
  88464. if (this.rightController != null) {
  88465. this._enableTeleportationOnController(this.rightController);
  88466. }
  88467. // Creates an image processing post process for the vignette not relying
  88468. // on the main scene configuration for image processing to reduce setup and spaces
  88469. // (gamma/linear) conflicts.
  88470. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  88471. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  88472. imageProcessingConfiguration.vignetteEnabled = true;
  88473. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  88474. this._webVRCamera.detachPostProcess(this._postProcessMove);
  88475. this._teleportationInitialized = true;
  88476. if (this._isDefaultTeleportationTarget) {
  88477. this._createTeleportationCircles();
  88478. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  88479. }
  88480. }
  88481. };
  88482. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  88483. var _this = this;
  88484. var controllerMesh = controller.webVRController.mesh;
  88485. if (controllerMesh) {
  88486. controller._interactionsEnabled = true;
  88487. controller._activatePointer();
  88488. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  88489. // Enabling / disabling laserPointer
  88490. if (_this._displayLaserPointer && stateObject.value === 1) {
  88491. if (controller._activePointer) {
  88492. controller._deactivatePointer();
  88493. }
  88494. else {
  88495. controller._activatePointer();
  88496. }
  88497. if (_this.displayGaze) {
  88498. controller._gazeTracker.isVisible = controller._activePointer;
  88499. }
  88500. }
  88501. });
  88502. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  88503. if (!controller._pointerDownOnMeshAsked) {
  88504. if (stateObject.value > _this._padSensibilityUp) {
  88505. controller._selectionPointerDown();
  88506. }
  88507. }
  88508. else if (stateObject.value < _this._padSensibilityDown) {
  88509. controller._selectionPointerUp();
  88510. }
  88511. });
  88512. }
  88513. };
  88514. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  88515. // Dont teleport if another gaze already requested teleportation
  88516. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  88517. return;
  88518. }
  88519. if (!gazer._teleportationRequestInitiated) {
  88520. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  88521. gazer._activatePointer();
  88522. gazer._teleportationRequestInitiated = true;
  88523. }
  88524. }
  88525. else {
  88526. // Listening to the proper controller values changes to confirm teleportation
  88527. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  88528. if (this._teleportActive) {
  88529. this._teleportCamera(this._haloCenter);
  88530. }
  88531. gazer._teleportationRequestInitiated = false;
  88532. }
  88533. }
  88534. };
  88535. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  88536. // Only rotate when user is not currently selecting a teleportation location
  88537. if (gazer._teleportationRequestInitiated) {
  88538. return;
  88539. }
  88540. if (!gazer._rotationLeftAsked) {
  88541. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  88542. gazer._rotationLeftAsked = true;
  88543. if (this._rotationAllowed) {
  88544. this._rotateCamera(false);
  88545. }
  88546. }
  88547. }
  88548. else {
  88549. if (stateObject.x > -this._padSensibilityDown) {
  88550. gazer._rotationLeftAsked = false;
  88551. }
  88552. }
  88553. if (!gazer._rotationRightAsked) {
  88554. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  88555. gazer._rotationRightAsked = true;
  88556. if (this._rotationAllowed) {
  88557. this._rotateCamera(true);
  88558. }
  88559. }
  88560. }
  88561. else {
  88562. if (stateObject.x < this._padSensibilityDown) {
  88563. gazer._rotationRightAsked = false;
  88564. }
  88565. }
  88566. };
  88567. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  88568. // Only teleport backwards when user is not currently selecting a teleportation location
  88569. if (gazer._teleportationRequestInitiated) {
  88570. return;
  88571. }
  88572. // Teleport backwards
  88573. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  88574. if (!gazer._teleportationBackRequestInitiated) {
  88575. if (!this.currentVRCamera) {
  88576. return;
  88577. }
  88578. // Get rotation and position of the current camera
  88579. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  88580. var position = this.currentVRCamera.position;
  88581. // If the camera has device position, use that instead
  88582. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  88583. rotation = this.currentVRCamera.deviceRotationQuaternion;
  88584. position = this.currentVRCamera.devicePosition;
  88585. }
  88586. // Get matrix with only the y rotation of the device rotation
  88587. rotation.toEulerAnglesToRef(this._workingVector);
  88588. this._workingVector.z = 0;
  88589. this._workingVector.x = 0;
  88590. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  88591. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  88592. // Rotate backwards ray by device rotation to cast at the ground behind the user
  88593. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  88594. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  88595. var ray = new BABYLON.Ray(position, this._workingVector);
  88596. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88597. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  88598. this._teleportCamera(hit.pickedPoint);
  88599. }
  88600. gazer._teleportationBackRequestInitiated = true;
  88601. }
  88602. }
  88603. else {
  88604. gazer._teleportationBackRequestInitiated = false;
  88605. }
  88606. };
  88607. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  88608. var _this = this;
  88609. var controllerMesh = controller.webVRController.mesh;
  88610. if (controllerMesh) {
  88611. if (!controller._interactionsEnabled) {
  88612. this._enableInteractionOnController(controller);
  88613. }
  88614. controller._interactionsEnabled = true;
  88615. controller._teleportationEnabled = true;
  88616. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  88617. controller._dpadPressed = false;
  88618. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  88619. controller._dpadPressed = stateObject.pressed;
  88620. if (!controller._dpadPressed) {
  88621. controller._rotationLeftAsked = false;
  88622. controller._rotationRightAsked = false;
  88623. controller._teleportationBackRequestInitiated = false;
  88624. }
  88625. });
  88626. }
  88627. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  88628. if (_this.teleportationEnabled) {
  88629. _this._checkTeleportBackwards(stateObject, controller);
  88630. _this._checkTeleportWithRay(stateObject, controller);
  88631. }
  88632. _this._checkRotate(stateObject, controller);
  88633. });
  88634. }
  88635. };
  88636. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  88637. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  88638. this._teleportationTarget.isPickable = false;
  88639. var length = 512;
  88640. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  88641. dynamicTexture.hasAlpha = true;
  88642. var context = dynamicTexture.getContext();
  88643. var centerX = length / 2;
  88644. var centerY = length / 2;
  88645. var radius = 200;
  88646. context.beginPath();
  88647. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  88648. context.fillStyle = this._teleportationFillColor;
  88649. context.fill();
  88650. context.lineWidth = 10;
  88651. context.strokeStyle = this._teleportationBorderColor;
  88652. context.stroke();
  88653. context.closePath();
  88654. dynamicTexture.update();
  88655. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  88656. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  88657. this._teleportationTarget.material = teleportationCircleMaterial;
  88658. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  88659. torus.isPickable = false;
  88660. torus.parent = this._teleportationTarget;
  88661. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  88662. var keys = [];
  88663. keys.push({
  88664. frame: 0,
  88665. value: 0
  88666. });
  88667. keys.push({
  88668. frame: 30,
  88669. value: 0.4
  88670. });
  88671. keys.push({
  88672. frame: 60,
  88673. value: 0
  88674. });
  88675. animationInnerCircle.setKeys(keys);
  88676. var easingFunction = new BABYLON.SineEase();
  88677. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  88678. animationInnerCircle.setEasingFunction(easingFunction);
  88679. torus.animations = [];
  88680. torus.animations.push(animationInnerCircle);
  88681. this._scene.beginAnimation(torus, 0, 60, true);
  88682. this._hideTeleportationTarget();
  88683. };
  88684. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  88685. this._teleportActive = true;
  88686. if (this._teleportationInitialized) {
  88687. this._teleportationTarget.isVisible = true;
  88688. if (this._isDefaultTeleportationTarget) {
  88689. this._teleportationTarget.getChildren()[0].isVisible = true;
  88690. }
  88691. }
  88692. };
  88693. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  88694. this._teleportActive = false;
  88695. if (this._teleportationInitialized) {
  88696. this._teleportationTarget.isVisible = false;
  88697. if (this._isDefaultTeleportationTarget) {
  88698. this._teleportationTarget.getChildren()[0].isVisible = false;
  88699. }
  88700. }
  88701. };
  88702. VRExperienceHelper.prototype._rotateCamera = function (right) {
  88703. var _this = this;
  88704. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88705. return;
  88706. }
  88707. if (right) {
  88708. this._rotationAngle++;
  88709. }
  88710. else {
  88711. this._rotationAngle--;
  88712. }
  88713. this.currentVRCamera.animations = [];
  88714. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  88715. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88716. var animationRotationKeys = [];
  88717. animationRotationKeys.push({
  88718. frame: 0,
  88719. value: this.currentVRCamera.rotationQuaternion
  88720. });
  88721. animationRotationKeys.push({
  88722. frame: 6,
  88723. value: target
  88724. });
  88725. animationRotation.setKeys(animationRotationKeys);
  88726. animationRotation.setEasingFunction(this._circleEase);
  88727. this.currentVRCamera.animations.push(animationRotation);
  88728. this._postProcessMove.animations = [];
  88729. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88730. var vignetteWeightKeys = [];
  88731. vignetteWeightKeys.push({
  88732. frame: 0,
  88733. value: 0
  88734. });
  88735. vignetteWeightKeys.push({
  88736. frame: 3,
  88737. value: 4
  88738. });
  88739. vignetteWeightKeys.push({
  88740. frame: 6,
  88741. value: 0
  88742. });
  88743. animationPP.setKeys(vignetteWeightKeys);
  88744. animationPP.setEasingFunction(this._circleEase);
  88745. this._postProcessMove.animations.push(animationPP);
  88746. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88747. var vignetteStretchKeys = [];
  88748. vignetteStretchKeys.push({
  88749. frame: 0,
  88750. value: 0
  88751. });
  88752. vignetteStretchKeys.push({
  88753. frame: 3,
  88754. value: 10
  88755. });
  88756. vignetteStretchKeys.push({
  88757. frame: 6,
  88758. value: 0
  88759. });
  88760. animationPP2.setKeys(vignetteStretchKeys);
  88761. animationPP2.setEasingFunction(this._circleEase);
  88762. this._postProcessMove.animations.push(animationPP2);
  88763. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88764. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88765. this._postProcessMove.samples = 4;
  88766. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88767. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  88768. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88769. });
  88770. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  88771. };
  88772. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  88773. if (hit.pickedPoint) {
  88774. if (gazer._teleportationRequestInitiated) {
  88775. this._displayTeleportationTarget();
  88776. this._haloCenter.copyFrom(hit.pickedPoint);
  88777. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  88778. }
  88779. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  88780. if (pickNormal) {
  88781. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88782. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88783. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  88784. }
  88785. this._teleportationTarget.position.y += 0.1;
  88786. }
  88787. };
  88788. VRExperienceHelper.prototype._teleportCamera = function (location) {
  88789. var _this = this;
  88790. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88791. return;
  88792. }
  88793. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  88794. // offset of the headset from the anchor.
  88795. if (this.webVRCamera.leftCamera) {
  88796. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  88797. this._workingVector.subtractInPlace(this.webVRCamera.position);
  88798. location.subtractToRef(this._workingVector, this._workingVector);
  88799. }
  88800. else {
  88801. this._workingVector.copyFrom(location);
  88802. }
  88803. // Add height to account for user's height offset
  88804. if (this.isInVRMode) {
  88805. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  88806. }
  88807. else {
  88808. this._workingVector.y += this._defaultHeight;
  88809. }
  88810. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  88811. // Create animation from the camera's position to the new location
  88812. this.currentVRCamera.animations = [];
  88813. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88814. var animationCameraTeleportationKeys = [{
  88815. frame: 0,
  88816. value: this.currentVRCamera.position
  88817. },
  88818. {
  88819. frame: 11,
  88820. value: this._workingVector
  88821. }
  88822. ];
  88823. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  88824. animationCameraTeleportation.setEasingFunction(this._circleEase);
  88825. this.currentVRCamera.animations.push(animationCameraTeleportation);
  88826. this._postProcessMove.animations = [];
  88827. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88828. var vignetteWeightKeys = [];
  88829. vignetteWeightKeys.push({
  88830. frame: 0,
  88831. value: 0
  88832. });
  88833. vignetteWeightKeys.push({
  88834. frame: 5,
  88835. value: 8
  88836. });
  88837. vignetteWeightKeys.push({
  88838. frame: 11,
  88839. value: 0
  88840. });
  88841. animationPP.setKeys(vignetteWeightKeys);
  88842. this._postProcessMove.animations.push(animationPP);
  88843. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  88844. var vignetteStretchKeys = [];
  88845. vignetteStretchKeys.push({
  88846. frame: 0,
  88847. value: 0
  88848. });
  88849. vignetteStretchKeys.push({
  88850. frame: 5,
  88851. value: 10
  88852. });
  88853. vignetteStretchKeys.push({
  88854. frame: 11,
  88855. value: 0
  88856. });
  88857. animationPP2.setKeys(vignetteStretchKeys);
  88858. this._postProcessMove.animations.push(animationPP2);
  88859. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  88860. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  88861. this._webVRCamera.attachPostProcess(this._postProcessMove);
  88862. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  88863. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  88864. });
  88865. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  88866. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  88867. });
  88868. this._hideTeleportationTarget();
  88869. };
  88870. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  88871. if (normal) {
  88872. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  88873. if (angle < Math.PI / 2) {
  88874. normal.scaleInPlace(-1);
  88875. }
  88876. }
  88877. return normal;
  88878. };
  88879. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  88880. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  88881. return;
  88882. }
  88883. var ray = gazer._getForwardRay(this._rayLength);
  88884. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  88885. // Moving the gazeTracker on the mesh face targetted
  88886. if (hit && hit.pickedPoint) {
  88887. if (this._displayGaze) {
  88888. var multiplier = 1;
  88889. gazer._gazeTracker.isVisible = true;
  88890. if (gazer._isActionableMesh) {
  88891. multiplier = 3;
  88892. }
  88893. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  88894. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  88895. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  88896. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  88897. // To avoid z-fighting
  88898. var deltaFighting = 0.002;
  88899. if (pickNormal) {
  88900. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  88901. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  88902. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  88903. }
  88904. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  88905. if (gazer._gazeTracker.position.x < 0) {
  88906. gazer._gazeTracker.position.x += deltaFighting;
  88907. }
  88908. else {
  88909. gazer._gazeTracker.position.x -= deltaFighting;
  88910. }
  88911. if (gazer._gazeTracker.position.y < 0) {
  88912. gazer._gazeTracker.position.y += deltaFighting;
  88913. }
  88914. else {
  88915. gazer._gazeTracker.position.y -= deltaFighting;
  88916. }
  88917. if (gazer._gazeTracker.position.z < 0) {
  88918. gazer._gazeTracker.position.z += deltaFighting;
  88919. }
  88920. else {
  88921. gazer._gazeTracker.position.z -= deltaFighting;
  88922. }
  88923. }
  88924. // Changing the size of the laser pointer based on the distance from the targetted point
  88925. gazer._updatePointerDistance(hit.distance);
  88926. }
  88927. else {
  88928. gazer._updatePointerDistance();
  88929. gazer._gazeTracker.isVisible = false;
  88930. }
  88931. if (hit && hit.pickedMesh) {
  88932. gazer._currentHit = hit;
  88933. if (gazer._pointerDownOnMeshAsked) {
  88934. this._scene.simulatePointerMove(gazer._currentHit, { pointerId: gazer._id });
  88935. }
  88936. // The object selected is the floor, we're in a teleportation scenario
  88937. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  88938. // Moving the teleportation area to this targetted point
  88939. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  88940. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  88941. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88942. }
  88943. gazer._currentMeshSelected = null;
  88944. if (gazer._teleportationRequestInitiated) {
  88945. this._moveTeleportationSelectorTo(hit, gazer, ray);
  88946. }
  88947. return;
  88948. }
  88949. // If not, we're in a selection scenario
  88950. //this._teleportationAllowed = false;
  88951. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  88952. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  88953. this.onNewMeshPicked.notifyObservers(hit);
  88954. gazer._currentMeshSelected = hit.pickedMesh;
  88955. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  88956. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  88957. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  88958. gazer._isActionableMesh = true;
  88959. }
  88960. else {
  88961. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88962. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88963. gazer._isActionableMesh = false;
  88964. }
  88965. try {
  88966. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  88967. }
  88968. catch (err) {
  88969. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  88970. }
  88971. }
  88972. else {
  88973. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88974. gazer._currentMeshSelected = null;
  88975. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88976. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88977. }
  88978. }
  88979. }
  88980. else {
  88981. gazer._currentHit = null;
  88982. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  88983. gazer._currentMeshSelected = null;
  88984. //this._teleportationAllowed = false;
  88985. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88986. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  88987. }
  88988. };
  88989. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  88990. if (mesh) {
  88991. this.onSelectedMeshUnselected.notifyObservers(mesh);
  88992. }
  88993. };
  88994. /**
  88995. * Sets the color of the laser ray from the vr controllers.
  88996. * @param color new color for the ray.
  88997. */
  88998. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  88999. if (this.leftController) {
  89000. this.leftController._setLaserPointerColor(color);
  89001. }
  89002. if (this.rightController) {
  89003. this.rightController._setLaserPointerColor(color);
  89004. }
  89005. };
  89006. /**
  89007. * Sets the color of the ray from the vr headsets gaze.
  89008. * @param color new color for the ray.
  89009. */
  89010. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  89011. if (!this._cameraGazer._gazeTracker.material) {
  89012. return;
  89013. }
  89014. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  89015. if (this.leftController) {
  89016. this.leftController._gazeTracker.material.emissiveColor = color;
  89017. }
  89018. if (this.rightController) {
  89019. this.rightController._gazeTracker.material.emissiveColor = color;
  89020. }
  89021. };
  89022. /**
  89023. * Exits VR and disposes of the vr experience helper
  89024. */
  89025. VRExperienceHelper.prototype.dispose = function () {
  89026. if (this.isInVRMode) {
  89027. this.exitVR();
  89028. }
  89029. if (this._postProcessMove) {
  89030. this._postProcessMove.dispose();
  89031. }
  89032. if (this._webVRCamera) {
  89033. this._webVRCamera.dispose();
  89034. }
  89035. if (this._vrDeviceOrientationCamera) {
  89036. this._vrDeviceOrientationCamera.dispose();
  89037. }
  89038. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  89039. document.body.removeChild(this._btnVR);
  89040. }
  89041. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  89042. this._deviceOrientationCamera.dispose();
  89043. }
  89044. if (this._cameraGazer) {
  89045. this._cameraGazer.dispose();
  89046. }
  89047. if (this.leftController) {
  89048. this.leftController.dispose();
  89049. }
  89050. if (this.rightController) {
  89051. this.rightController.dispose();
  89052. }
  89053. if (this._teleportationTarget) {
  89054. this._teleportationTarget.dispose();
  89055. }
  89056. this._floorMeshesCollection = [];
  89057. document.removeEventListener("keydown", this._onKeyDown);
  89058. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89059. window.removeEventListener("resize", this._onResize);
  89060. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  89061. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  89062. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  89063. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  89064. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  89065. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  89066. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  89067. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  89068. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  89069. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  89070. this._scene.unregisterBeforeRender(this.beforeRender);
  89071. };
  89072. /**
  89073. * Gets the name of the VRExperienceHelper class
  89074. * @returns "VRExperienceHelper"
  89075. */
  89076. VRExperienceHelper.prototype.getClassName = function () {
  89077. return "VRExperienceHelper";
  89078. };
  89079. return VRExperienceHelper;
  89080. }());
  89081. BABYLON.VRExperienceHelper = VRExperienceHelper;
  89082. })(BABYLON || (BABYLON = {}));
  89083. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  89084. // Mainly based on these 2 articles :
  89085. // 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
  89086. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  89087. var BABYLON;
  89088. (function (BABYLON) {
  89089. /**
  89090. * Defines the potential axis of a Joystick
  89091. */
  89092. var JoystickAxis;
  89093. (function (JoystickAxis) {
  89094. /** X axis */
  89095. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  89096. /** Y axis */
  89097. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  89098. /** Z axis */
  89099. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  89100. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  89101. /**
  89102. * Class used to define virtual joystick (used in touch mode)
  89103. */
  89104. var VirtualJoystick = /** @class */ (function () {
  89105. /**
  89106. * Creates a new virtual joystick
  89107. * @param leftJoystick defines that the joystick is for left hand (false by default)
  89108. */
  89109. function VirtualJoystick(leftJoystick) {
  89110. var _this = this;
  89111. if (leftJoystick) {
  89112. this._leftJoystick = true;
  89113. }
  89114. else {
  89115. this._leftJoystick = false;
  89116. }
  89117. VirtualJoystick._globalJoystickIndex++;
  89118. // By default left & right arrow keys are moving the X
  89119. // and up & down keys are moving the Y
  89120. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89121. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89122. this.reverseLeftRight = false;
  89123. this.reverseUpDown = false;
  89124. // collections of pointers
  89125. this._touches = new BABYLON.StringDictionary();
  89126. this.deltaPosition = BABYLON.Vector3.Zero();
  89127. this._joystickSensibility = 25;
  89128. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89129. this._onResize = function (evt) {
  89130. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89131. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89132. if (VirtualJoystick.vjCanvas) {
  89133. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  89134. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  89135. }
  89136. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  89137. };
  89138. // injecting a canvas element on top of the canvas 3D game
  89139. if (!VirtualJoystick.vjCanvas) {
  89140. window.addEventListener("resize", this._onResize, false);
  89141. VirtualJoystick.vjCanvas = document.createElement("canvas");
  89142. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  89143. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  89144. VirtualJoystick.vjCanvas.width = window.innerWidth;
  89145. VirtualJoystick.vjCanvas.height = window.innerHeight;
  89146. VirtualJoystick.vjCanvas.style.width = "100%";
  89147. VirtualJoystick.vjCanvas.style.height = "100%";
  89148. VirtualJoystick.vjCanvas.style.position = "absolute";
  89149. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  89150. VirtualJoystick.vjCanvas.style.top = "0px";
  89151. VirtualJoystick.vjCanvas.style.left = "0px";
  89152. VirtualJoystick.vjCanvas.style.zIndex = "5";
  89153. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  89154. // Support for jQuery PEP polyfill
  89155. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  89156. var context = VirtualJoystick.vjCanvas.getContext('2d');
  89157. if (!context) {
  89158. throw new Error("Unable to create canvas for virtual joystick");
  89159. }
  89160. VirtualJoystick.vjCanvasContext = context;
  89161. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  89162. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89163. document.body.appendChild(VirtualJoystick.vjCanvas);
  89164. }
  89165. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  89166. this.pressed = false;
  89167. // default joystick color
  89168. this._joystickColor = "cyan";
  89169. this._joystickPointerID = -1;
  89170. // current joystick position
  89171. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  89172. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  89173. // origin joystick position
  89174. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  89175. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  89176. this._onPointerDownHandlerRef = function (evt) {
  89177. _this._onPointerDown(evt);
  89178. };
  89179. this._onPointerMoveHandlerRef = function (evt) {
  89180. _this._onPointerMove(evt);
  89181. };
  89182. this._onPointerUpHandlerRef = function (evt) {
  89183. _this._onPointerUp(evt);
  89184. };
  89185. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  89186. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  89187. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  89188. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  89189. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  89190. evt.preventDefault(); // Disables system menu
  89191. }, false);
  89192. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89193. }
  89194. /**
  89195. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  89196. * @param newJoystickSensibility defines the new sensibility
  89197. */
  89198. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  89199. this._joystickSensibility = newJoystickSensibility;
  89200. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  89201. };
  89202. VirtualJoystick.prototype._onPointerDown = function (e) {
  89203. var positionOnScreenCondition;
  89204. e.preventDefault();
  89205. if (this._leftJoystick === true) {
  89206. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  89207. }
  89208. else {
  89209. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  89210. }
  89211. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  89212. // First contact will be dedicated to the virtual joystick
  89213. this._joystickPointerID = e.pointerId;
  89214. this._joystickPointerStartPos.x = e.clientX;
  89215. this._joystickPointerStartPos.y = e.clientY;
  89216. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  89217. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  89218. this._deltaJoystickVector.x = 0;
  89219. this._deltaJoystickVector.y = 0;
  89220. this.pressed = true;
  89221. this._touches.add(e.pointerId.toString(), e);
  89222. }
  89223. else {
  89224. // You can only trigger the action buttons with a joystick declared
  89225. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  89226. this._action();
  89227. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  89228. }
  89229. }
  89230. };
  89231. VirtualJoystick.prototype._onPointerMove = function (e) {
  89232. // If the current pointer is the one associated to the joystick (first touch contact)
  89233. if (this._joystickPointerID == e.pointerId) {
  89234. this._joystickPointerPos.x = e.clientX;
  89235. this._joystickPointerPos.y = e.clientY;
  89236. this._deltaJoystickVector = this._joystickPointerPos.clone();
  89237. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  89238. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  89239. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  89240. switch (this._axisTargetedByLeftAndRight) {
  89241. case JoystickAxis.X:
  89242. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  89243. break;
  89244. case JoystickAxis.Y:
  89245. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  89246. break;
  89247. case JoystickAxis.Z:
  89248. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  89249. break;
  89250. }
  89251. var directionUpDown = this.reverseUpDown ? 1 : -1;
  89252. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  89253. switch (this._axisTargetedByUpAndDown) {
  89254. case JoystickAxis.X:
  89255. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  89256. break;
  89257. case JoystickAxis.Y:
  89258. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  89259. break;
  89260. case JoystickAxis.Z:
  89261. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  89262. break;
  89263. }
  89264. }
  89265. else {
  89266. var data = this._touches.get(e.pointerId.toString());
  89267. if (data) {
  89268. data.x = e.clientX;
  89269. data.y = e.clientY;
  89270. }
  89271. }
  89272. };
  89273. VirtualJoystick.prototype._onPointerUp = function (e) {
  89274. if (this._joystickPointerID == e.pointerId) {
  89275. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  89276. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  89277. this._joystickPointerID = -1;
  89278. this.pressed = false;
  89279. }
  89280. else {
  89281. var touch = this._touches.get(e.pointerId.toString());
  89282. if (touch) {
  89283. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89284. }
  89285. }
  89286. this._deltaJoystickVector.x = 0;
  89287. this._deltaJoystickVector.y = 0;
  89288. this._touches.remove(e.pointerId.toString());
  89289. };
  89290. /**
  89291. * Change the color of the virtual joystick
  89292. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  89293. */
  89294. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  89295. this._joystickColor = newColor;
  89296. };
  89297. /**
  89298. * Defines a callback to call when the joystick is touched
  89299. * @param action defines the callback
  89300. */
  89301. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  89302. this._action = action;
  89303. };
  89304. /**
  89305. * Defines which axis you'd like to control for left & right
  89306. * @param axis defines the axis to use
  89307. */
  89308. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  89309. switch (axis) {
  89310. case JoystickAxis.X:
  89311. case JoystickAxis.Y:
  89312. case JoystickAxis.Z:
  89313. this._axisTargetedByLeftAndRight = axis;
  89314. break;
  89315. default:
  89316. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  89317. break;
  89318. }
  89319. };
  89320. /**
  89321. * Defines which axis you'd like to control for up & down
  89322. * @param axis defines the axis to use
  89323. */
  89324. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  89325. switch (axis) {
  89326. case JoystickAxis.X:
  89327. case JoystickAxis.Y:
  89328. case JoystickAxis.Z:
  89329. this._axisTargetedByUpAndDown = axis;
  89330. break;
  89331. default:
  89332. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  89333. break;
  89334. }
  89335. };
  89336. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  89337. var _this = this;
  89338. if (this.pressed) {
  89339. this._touches.forEach(function (key, touch) {
  89340. if (touch.pointerId === _this._joystickPointerID) {
  89341. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  89342. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  89343. VirtualJoystick.vjCanvasContext.beginPath();
  89344. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89345. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89346. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  89347. VirtualJoystick.vjCanvasContext.stroke();
  89348. VirtualJoystick.vjCanvasContext.closePath();
  89349. VirtualJoystick.vjCanvasContext.beginPath();
  89350. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89351. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  89352. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  89353. VirtualJoystick.vjCanvasContext.stroke();
  89354. VirtualJoystick.vjCanvasContext.closePath();
  89355. VirtualJoystick.vjCanvasContext.beginPath();
  89356. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  89357. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  89358. VirtualJoystick.vjCanvasContext.stroke();
  89359. VirtualJoystick.vjCanvasContext.closePath();
  89360. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  89361. }
  89362. else {
  89363. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  89364. VirtualJoystick.vjCanvasContext.beginPath();
  89365. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  89366. VirtualJoystick.vjCanvasContext.beginPath();
  89367. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  89368. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  89369. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  89370. VirtualJoystick.vjCanvasContext.stroke();
  89371. VirtualJoystick.vjCanvasContext.closePath();
  89372. touch.prevX = touch.x;
  89373. touch.prevY = touch.y;
  89374. }
  89375. ;
  89376. });
  89377. }
  89378. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  89379. };
  89380. /**
  89381. * Release internal HTML canvas
  89382. */
  89383. VirtualJoystick.prototype.releaseCanvas = function () {
  89384. if (VirtualJoystick.vjCanvas) {
  89385. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  89386. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  89387. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  89388. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  89389. window.removeEventListener("resize", this._onResize);
  89390. document.body.removeChild(VirtualJoystick.vjCanvas);
  89391. VirtualJoystick.vjCanvas = null;
  89392. }
  89393. };
  89394. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  89395. VirtualJoystick._globalJoystickIndex = 0;
  89396. return VirtualJoystick;
  89397. }());
  89398. BABYLON.VirtualJoystick = VirtualJoystick;
  89399. })(BABYLON || (BABYLON = {}));
  89400. //# sourceMappingURL=babylon.virtualJoystick.js.map
  89401. var BABYLON;
  89402. (function (BABYLON) {
  89403. // We're mainly based on the logic defined into the FreeCamera code
  89404. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  89405. __extends(VirtualJoysticksCamera, _super);
  89406. function VirtualJoysticksCamera(name, position, scene) {
  89407. var _this = _super.call(this, name, position, scene) || this;
  89408. _this.inputs.addVirtualJoystick();
  89409. return _this;
  89410. }
  89411. VirtualJoysticksCamera.prototype.getClassName = function () {
  89412. return "VirtualJoysticksCamera";
  89413. };
  89414. return VirtualJoysticksCamera;
  89415. }(BABYLON.FreeCamera));
  89416. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  89417. })(BABYLON || (BABYLON = {}));
  89418. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  89419. var BABYLON;
  89420. (function (BABYLON) {
  89421. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  89422. function FreeCameraVirtualJoystickInput() {
  89423. }
  89424. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  89425. return this._leftjoystick;
  89426. };
  89427. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  89428. return this._rightjoystick;
  89429. };
  89430. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  89431. if (this._leftjoystick) {
  89432. var camera = this.camera;
  89433. var speed = camera._computeLocalCameraSpeed() * 50;
  89434. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  89435. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  89436. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  89437. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  89438. if (!this._leftjoystick.pressed) {
  89439. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  89440. }
  89441. if (!this._rightjoystick.pressed) {
  89442. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  89443. }
  89444. }
  89445. };
  89446. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  89447. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  89448. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  89449. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  89450. this._leftjoystick.setJoystickSensibility(0.15);
  89451. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  89452. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  89453. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  89454. this._rightjoystick.reverseUpDown = true;
  89455. this._rightjoystick.setJoystickSensibility(0.05);
  89456. this._rightjoystick.setJoystickColor("yellow");
  89457. };
  89458. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  89459. this._leftjoystick.releaseCanvas();
  89460. this._rightjoystick.releaseCanvas();
  89461. };
  89462. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  89463. return "FreeCameraVirtualJoystickInput";
  89464. };
  89465. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  89466. return "virtualJoystick";
  89467. };
  89468. return FreeCameraVirtualJoystickInput;
  89469. }());
  89470. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  89471. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  89472. })(BABYLON || (BABYLON = {}));
  89473. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  89474. var BABYLON;
  89475. (function (BABYLON) {
  89476. var SimplificationSettings = /** @class */ (function () {
  89477. function SimplificationSettings(quality, distance, optimizeMesh) {
  89478. this.quality = quality;
  89479. this.distance = distance;
  89480. this.optimizeMesh = optimizeMesh;
  89481. }
  89482. return SimplificationSettings;
  89483. }());
  89484. BABYLON.SimplificationSettings = SimplificationSettings;
  89485. var SimplificationQueue = /** @class */ (function () {
  89486. function SimplificationQueue() {
  89487. this.running = false;
  89488. this._simplificationArray = [];
  89489. }
  89490. SimplificationQueue.prototype.addTask = function (task) {
  89491. this._simplificationArray.push(task);
  89492. };
  89493. SimplificationQueue.prototype.executeNext = function () {
  89494. var task = this._simplificationArray.pop();
  89495. if (task) {
  89496. this.running = true;
  89497. this.runSimplification(task);
  89498. }
  89499. else {
  89500. this.running = false;
  89501. }
  89502. };
  89503. SimplificationQueue.prototype.runSimplification = function (task) {
  89504. var _this = this;
  89505. if (task.parallelProcessing) {
  89506. //parallel simplifier
  89507. task.settings.forEach(function (setting) {
  89508. var simplifier = _this.getSimplifier(task);
  89509. simplifier.simplify(setting, function (newMesh) {
  89510. task.mesh.addLODLevel(setting.distance, newMesh);
  89511. newMesh.isVisible = true;
  89512. //check if it is the last
  89513. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  89514. //all done, run the success callback.
  89515. task.successCallback();
  89516. }
  89517. _this.executeNext();
  89518. });
  89519. });
  89520. }
  89521. else {
  89522. //single simplifier.
  89523. var simplifier = this.getSimplifier(task);
  89524. var runDecimation = function (setting, callback) {
  89525. simplifier.simplify(setting, function (newMesh) {
  89526. task.mesh.addLODLevel(setting.distance, newMesh);
  89527. newMesh.isVisible = true;
  89528. //run the next quality level
  89529. callback();
  89530. });
  89531. };
  89532. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  89533. runDecimation(task.settings[loop.index], function () {
  89534. loop.executeNext();
  89535. });
  89536. }, function () {
  89537. //execution ended, run the success callback.
  89538. if (task.successCallback) {
  89539. task.successCallback();
  89540. }
  89541. _this.executeNext();
  89542. });
  89543. }
  89544. };
  89545. SimplificationQueue.prototype.getSimplifier = function (task) {
  89546. switch (task.simplificationType) {
  89547. case SimplificationType.QUADRATIC:
  89548. default:
  89549. return new QuadraticErrorSimplification(task.mesh);
  89550. }
  89551. };
  89552. return SimplificationQueue;
  89553. }());
  89554. BABYLON.SimplificationQueue = SimplificationQueue;
  89555. /**
  89556. * The implemented types of simplification
  89557. * At the moment only Quadratic Error Decimation is implemented
  89558. */
  89559. var SimplificationType;
  89560. (function (SimplificationType) {
  89561. /** Quadratic error decimation */
  89562. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  89563. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  89564. var DecimationTriangle = /** @class */ (function () {
  89565. function DecimationTriangle(vertices) {
  89566. this.vertices = vertices;
  89567. this.error = new Array(4);
  89568. this.deleted = false;
  89569. this.isDirty = false;
  89570. this.deletePending = false;
  89571. this.borderFactor = 0;
  89572. }
  89573. return DecimationTriangle;
  89574. }());
  89575. BABYLON.DecimationTriangle = DecimationTriangle;
  89576. var DecimationVertex = /** @class */ (function () {
  89577. function DecimationVertex(position, id) {
  89578. this.position = position;
  89579. this.id = id;
  89580. this.isBorder = true;
  89581. this.q = new QuadraticMatrix();
  89582. this.triangleCount = 0;
  89583. this.triangleStart = 0;
  89584. this.originalOffsets = [];
  89585. }
  89586. DecimationVertex.prototype.updatePosition = function (newPosition) {
  89587. this.position.copyFrom(newPosition);
  89588. };
  89589. return DecimationVertex;
  89590. }());
  89591. BABYLON.DecimationVertex = DecimationVertex;
  89592. var QuadraticMatrix = /** @class */ (function () {
  89593. function QuadraticMatrix(data) {
  89594. this.data = new Array(10);
  89595. for (var i = 0; i < 10; ++i) {
  89596. if (data && data[i]) {
  89597. this.data[i] = data[i];
  89598. }
  89599. else {
  89600. this.data[i] = 0;
  89601. }
  89602. }
  89603. }
  89604. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  89605. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  89606. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  89607. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  89608. return det;
  89609. };
  89610. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  89611. for (var i = 0; i < 10; ++i) {
  89612. this.data[i] += matrix.data[i];
  89613. }
  89614. };
  89615. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  89616. for (var i = 0; i < 10; ++i) {
  89617. this.data[i] += data[i];
  89618. }
  89619. };
  89620. QuadraticMatrix.prototype.add = function (matrix) {
  89621. var m = new QuadraticMatrix();
  89622. for (var i = 0; i < 10; ++i) {
  89623. m.data[i] = this.data[i] + matrix.data[i];
  89624. }
  89625. return m;
  89626. };
  89627. QuadraticMatrix.FromData = function (a, b, c, d) {
  89628. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  89629. };
  89630. //returning an array to avoid garbage collection
  89631. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  89632. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  89633. };
  89634. return QuadraticMatrix;
  89635. }());
  89636. BABYLON.QuadraticMatrix = QuadraticMatrix;
  89637. var Reference = /** @class */ (function () {
  89638. function Reference(vertexId, triangleId) {
  89639. this.vertexId = vertexId;
  89640. this.triangleId = triangleId;
  89641. }
  89642. return Reference;
  89643. }());
  89644. BABYLON.Reference = Reference;
  89645. /**
  89646. * An implementation of the Quadratic Error simplification algorithm.
  89647. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  89648. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  89649. * @author RaananW
  89650. */
  89651. var QuadraticErrorSimplification = /** @class */ (function () {
  89652. function QuadraticErrorSimplification(_mesh) {
  89653. this._mesh = _mesh;
  89654. this.syncIterations = 5000;
  89655. this.aggressiveness = 7;
  89656. this.decimationIterations = 100;
  89657. this.boundingBoxEpsilon = BABYLON.Epsilon;
  89658. }
  89659. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  89660. var _this = this;
  89661. this.initDecimatedMesh();
  89662. //iterating through the submeshes array, one after the other.
  89663. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  89664. _this.initWithMesh(loop.index, function () {
  89665. _this.runDecimation(settings, loop.index, function () {
  89666. loop.executeNext();
  89667. });
  89668. }, settings.optimizeMesh);
  89669. }, function () {
  89670. setTimeout(function () {
  89671. successCallback(_this._reconstructedMesh);
  89672. }, 0);
  89673. });
  89674. };
  89675. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  89676. var _this = this;
  89677. var targetCount = ~~(this.triangles.length * settings.quality);
  89678. var deletedTriangles = 0;
  89679. var triangleCount = this.triangles.length;
  89680. var iterationFunction = function (iteration, callback) {
  89681. setTimeout(function () {
  89682. if (iteration % 5 === 0) {
  89683. _this.updateMesh(iteration === 0);
  89684. }
  89685. for (var i = 0; i < _this.triangles.length; ++i) {
  89686. _this.triangles[i].isDirty = false;
  89687. }
  89688. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  89689. var trianglesIterator = function (i) {
  89690. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  89691. var t = _this.triangles[tIdx];
  89692. if (!t)
  89693. return;
  89694. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  89695. return;
  89696. }
  89697. for (var j = 0; j < 3; ++j) {
  89698. if (t.error[j] < threshold) {
  89699. var deleted0 = [];
  89700. var deleted1 = [];
  89701. var v0 = t.vertices[j];
  89702. var v1 = t.vertices[(j + 1) % 3];
  89703. if (v0.isBorder || v1.isBorder)
  89704. continue;
  89705. var p = BABYLON.Vector3.Zero();
  89706. var n = BABYLON.Vector3.Zero();
  89707. var uv = BABYLON.Vector2.Zero();
  89708. var color = new BABYLON.Color4(0, 0, 0, 1);
  89709. _this.calculateError(v0, v1, p, n, uv, color);
  89710. var delTr = new Array();
  89711. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  89712. continue;
  89713. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  89714. continue;
  89715. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  89716. continue;
  89717. var uniqueArray = new Array();
  89718. delTr.forEach(function (deletedT) {
  89719. if (uniqueArray.indexOf(deletedT) === -1) {
  89720. deletedT.deletePending = true;
  89721. uniqueArray.push(deletedT);
  89722. }
  89723. });
  89724. if (uniqueArray.length % 2 !== 0) {
  89725. continue;
  89726. }
  89727. v0.q = v1.q.add(v0.q);
  89728. v0.updatePosition(p);
  89729. var tStart = _this.references.length;
  89730. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  89731. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  89732. var tCount = _this.references.length - tStart;
  89733. if (tCount <= v0.triangleCount) {
  89734. if (tCount) {
  89735. for (var c = 0; c < tCount; c++) {
  89736. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  89737. }
  89738. }
  89739. }
  89740. else {
  89741. v0.triangleStart = tStart;
  89742. }
  89743. v0.triangleCount = tCount;
  89744. break;
  89745. }
  89746. }
  89747. };
  89748. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  89749. }, 0);
  89750. };
  89751. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  89752. if (triangleCount - deletedTriangles <= targetCount)
  89753. loop.breakLoop();
  89754. else {
  89755. iterationFunction(loop.index, function () {
  89756. loop.executeNext();
  89757. });
  89758. }
  89759. }, function () {
  89760. setTimeout(function () {
  89761. //reconstruct this part of the mesh
  89762. _this.reconstructMesh(submeshIndex);
  89763. successCallback();
  89764. }, 0);
  89765. });
  89766. };
  89767. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  89768. var _this = this;
  89769. this.vertices = [];
  89770. this.triangles = [];
  89771. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  89772. var indices = this._mesh.getIndices();
  89773. var submesh = this._mesh.subMeshes[submeshIndex];
  89774. var findInVertices = function (positionToSearch) {
  89775. if (optimizeMesh) {
  89776. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  89777. if (_this.vertices[ii].position.equals(positionToSearch)) {
  89778. return _this.vertices[ii];
  89779. }
  89780. }
  89781. }
  89782. return null;
  89783. };
  89784. var vertexReferences = [];
  89785. var vertexInit = function (i) {
  89786. if (!positionData) {
  89787. return;
  89788. }
  89789. var offset = i + submesh.verticesStart;
  89790. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  89791. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  89792. vertex.originalOffsets.push(offset);
  89793. if (vertex.id === _this.vertices.length) {
  89794. _this.vertices.push(vertex);
  89795. }
  89796. vertexReferences.push(vertex.id);
  89797. };
  89798. //var totalVertices = mesh.getTotalVertices();
  89799. var totalVertices = submesh.verticesCount;
  89800. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  89801. var indicesInit = function (i) {
  89802. if (!indices) {
  89803. return;
  89804. }
  89805. var offset = (submesh.indexStart / 3) + i;
  89806. var pos = (offset * 3);
  89807. var i0 = indices[pos + 0];
  89808. var i1 = indices[pos + 1];
  89809. var i2 = indices[pos + 2];
  89810. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  89811. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  89812. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  89813. var triangle = new DecimationTriangle([v0, v1, v2]);
  89814. triangle.originalOffset = pos;
  89815. _this.triangles.push(triangle);
  89816. };
  89817. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  89818. _this.init(callback);
  89819. });
  89820. });
  89821. };
  89822. QuadraticErrorSimplification.prototype.init = function (callback) {
  89823. var _this = this;
  89824. var triangleInit1 = function (i) {
  89825. var t = _this.triangles[i];
  89826. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  89827. for (var j = 0; j < 3; j++) {
  89828. 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))));
  89829. }
  89830. };
  89831. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  89832. var triangleInit2 = function (i) {
  89833. var t = _this.triangles[i];
  89834. for (var j = 0; j < 3; ++j) {
  89835. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  89836. }
  89837. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89838. };
  89839. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  89840. callback();
  89841. });
  89842. });
  89843. };
  89844. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  89845. var newTriangles = [];
  89846. var i;
  89847. for (i = 0; i < this.vertices.length; ++i) {
  89848. this.vertices[i].triangleCount = 0;
  89849. }
  89850. var t;
  89851. var j;
  89852. for (i = 0; i < this.triangles.length; ++i) {
  89853. if (!this.triangles[i].deleted) {
  89854. t = this.triangles[i];
  89855. for (j = 0; j < 3; ++j) {
  89856. t.vertices[j].triangleCount = 1;
  89857. }
  89858. newTriangles.push(t);
  89859. }
  89860. }
  89861. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  89862. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  89863. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  89864. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  89865. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  89866. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  89867. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  89868. var vertexCount = 0;
  89869. for (i = 0; i < this.vertices.length; ++i) {
  89870. var vertex = this.vertices[i];
  89871. vertex.id = vertexCount;
  89872. if (vertex.triangleCount) {
  89873. vertex.originalOffsets.forEach(function (originalOffset) {
  89874. if (!normalData) {
  89875. return;
  89876. }
  89877. newPositionData.push(vertex.position.x);
  89878. newPositionData.push(vertex.position.y);
  89879. newPositionData.push(vertex.position.z);
  89880. newNormalData.push(normalData[originalOffset * 3]);
  89881. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  89882. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  89883. if (uvs && uvs.length) {
  89884. newUVsData.push(uvs[(originalOffset * 2)]);
  89885. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  89886. }
  89887. else if (colorsData && colorsData.length) {
  89888. newColorsData.push(colorsData[(originalOffset * 4)]);
  89889. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  89890. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  89891. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  89892. }
  89893. ++vertexCount;
  89894. });
  89895. }
  89896. }
  89897. var startingIndex = this._reconstructedMesh.getTotalIndices();
  89898. var startingVertex = this._reconstructedMesh.getTotalVertices();
  89899. var submeshesArray = this._reconstructedMesh.subMeshes;
  89900. this._reconstructedMesh.subMeshes = [];
  89901. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  89902. var originalIndices = this._mesh.getIndices();
  89903. for (i = 0; i < newTriangles.length; ++i) {
  89904. t = newTriangles[i]; //now get the new referencing point for each vertex
  89905. [0, 1, 2].forEach(function (idx) {
  89906. var id = originalIndices[t.originalOffset + idx];
  89907. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  89908. if (offset < 0)
  89909. offset = 0;
  89910. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  89911. });
  89912. }
  89913. //overwriting the old vertex buffers and indices.
  89914. this._reconstructedMesh.setIndices(newIndicesArray);
  89915. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  89916. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  89917. if (newUVsData.length > 0)
  89918. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  89919. if (newColorsData.length > 0)
  89920. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  89921. //create submesh
  89922. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  89923. if (submeshIndex > 0) {
  89924. this._reconstructedMesh.subMeshes = [];
  89925. submeshesArray.forEach(function (submesh) {
  89926. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  89927. });
  89928. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  89929. }
  89930. };
  89931. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  89932. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  89933. this._reconstructedMesh.material = this._mesh.material;
  89934. this._reconstructedMesh.parent = this._mesh.parent;
  89935. this._reconstructedMesh.isVisible = false;
  89936. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  89937. };
  89938. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  89939. for (var i = 0; i < vertex1.triangleCount; ++i) {
  89940. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  89941. if (t.deleted)
  89942. continue;
  89943. var s = this.references[vertex1.triangleStart + i].vertexId;
  89944. var v1 = t.vertices[(s + 1) % 3];
  89945. var v2 = t.vertices[(s + 2) % 3];
  89946. if ((v1 === vertex2 || v2 === vertex2)) {
  89947. deletedArray[i] = true;
  89948. delTr.push(t);
  89949. continue;
  89950. }
  89951. var d1 = v1.position.subtract(point);
  89952. d1 = d1.normalize();
  89953. var d2 = v2.position.subtract(point);
  89954. d2 = d2.normalize();
  89955. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  89956. return true;
  89957. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  89958. deletedArray[i] = false;
  89959. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  89960. return true;
  89961. }
  89962. return false;
  89963. };
  89964. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  89965. var newDeleted = deletedTriangles;
  89966. for (var i = 0; i < vertex.triangleCount; ++i) {
  89967. var ref = this.references[vertex.triangleStart + i];
  89968. var t = this.triangles[ref.triangleId];
  89969. if (t.deleted)
  89970. continue;
  89971. if (deletedArray[i] && t.deletePending) {
  89972. t.deleted = true;
  89973. newDeleted++;
  89974. continue;
  89975. }
  89976. t.vertices[ref.vertexId] = origVertex;
  89977. t.isDirty = true;
  89978. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  89979. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  89980. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  89981. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  89982. this.references.push(ref);
  89983. }
  89984. return newDeleted;
  89985. };
  89986. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  89987. for (var i = 0; i < this.vertices.length; ++i) {
  89988. var vCount = [];
  89989. var vId = [];
  89990. var v = this.vertices[i];
  89991. var j;
  89992. for (j = 0; j < v.triangleCount; ++j) {
  89993. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  89994. for (var ii = 0; ii < 3; ii++) {
  89995. var ofs = 0;
  89996. var vv = triangle.vertices[ii];
  89997. while (ofs < vCount.length) {
  89998. if (vId[ofs] === vv.id)
  89999. break;
  90000. ++ofs;
  90001. }
  90002. if (ofs === vCount.length) {
  90003. vCount.push(1);
  90004. vId.push(vv.id);
  90005. }
  90006. else {
  90007. vCount[ofs]++;
  90008. }
  90009. }
  90010. }
  90011. for (j = 0; j < vCount.length; ++j) {
  90012. if (vCount[j] === 1) {
  90013. this.vertices[vId[j]].isBorder = true;
  90014. }
  90015. else {
  90016. this.vertices[vId[j]].isBorder = false;
  90017. }
  90018. }
  90019. }
  90020. };
  90021. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  90022. if (identifyBorders === void 0) { identifyBorders = false; }
  90023. var i;
  90024. if (!identifyBorders) {
  90025. var newTrianglesVector = [];
  90026. for (i = 0; i < this.triangles.length; ++i) {
  90027. if (!this.triangles[i].deleted) {
  90028. newTrianglesVector.push(this.triangles[i]);
  90029. }
  90030. }
  90031. this.triangles = newTrianglesVector;
  90032. }
  90033. for (i = 0; i < this.vertices.length; ++i) {
  90034. this.vertices[i].triangleCount = 0;
  90035. this.vertices[i].triangleStart = 0;
  90036. }
  90037. var t;
  90038. var j;
  90039. var v;
  90040. for (i = 0; i < this.triangles.length; ++i) {
  90041. t = this.triangles[i];
  90042. for (j = 0; j < 3; ++j) {
  90043. v = t.vertices[j];
  90044. v.triangleCount++;
  90045. }
  90046. }
  90047. var tStart = 0;
  90048. for (i = 0; i < this.vertices.length; ++i) {
  90049. this.vertices[i].triangleStart = tStart;
  90050. tStart += this.vertices[i].triangleCount;
  90051. this.vertices[i].triangleCount = 0;
  90052. }
  90053. var newReferences = new Array(this.triangles.length * 3);
  90054. for (i = 0; i < this.triangles.length; ++i) {
  90055. t = this.triangles[i];
  90056. for (j = 0; j < 3; ++j) {
  90057. v = t.vertices[j];
  90058. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  90059. v.triangleCount++;
  90060. }
  90061. }
  90062. this.references = newReferences;
  90063. if (identifyBorders) {
  90064. this.identifyBorder();
  90065. }
  90066. };
  90067. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  90068. var x = point.x;
  90069. var y = point.y;
  90070. var z = point.z;
  90071. 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
  90072. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  90073. };
  90074. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  90075. var q = vertex1.q.add(vertex2.q);
  90076. var border = vertex1.isBorder && vertex2.isBorder;
  90077. var error = 0;
  90078. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  90079. if (qDet !== 0 && !border) {
  90080. if (!pointResult) {
  90081. pointResult = BABYLON.Vector3.Zero();
  90082. }
  90083. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  90084. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  90085. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  90086. error = this.vertexError(q, pointResult);
  90087. }
  90088. else {
  90089. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  90090. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  90091. var error1 = this.vertexError(q, vertex1.position);
  90092. var error2 = this.vertexError(q, vertex2.position);
  90093. var error3 = this.vertexError(q, p3);
  90094. error = Math.min(error1, error2, error3);
  90095. if (error === error1) {
  90096. if (pointResult) {
  90097. pointResult.copyFrom(vertex1.position);
  90098. }
  90099. }
  90100. else if (error === error2) {
  90101. if (pointResult) {
  90102. pointResult.copyFrom(vertex2.position);
  90103. }
  90104. }
  90105. else {
  90106. if (pointResult) {
  90107. pointResult.copyFrom(p3);
  90108. }
  90109. }
  90110. }
  90111. return error;
  90112. };
  90113. return QuadraticErrorSimplification;
  90114. }());
  90115. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  90116. })(BABYLON || (BABYLON = {}));
  90117. //# sourceMappingURL=babylon.meshSimplification.js.map
  90118. var BABYLON;
  90119. (function (BABYLON) {
  90120. var MeshLODLevel = /** @class */ (function () {
  90121. function MeshLODLevel(distance, mesh) {
  90122. this.distance = distance;
  90123. this.mesh = mesh;
  90124. }
  90125. return MeshLODLevel;
  90126. }());
  90127. BABYLON.MeshLODLevel = MeshLODLevel;
  90128. })(BABYLON || (BABYLON = {}));
  90129. //# sourceMappingURL=babylon.meshLODLevel.js.map
  90130. var BABYLON;
  90131. (function (BABYLON) {
  90132. /**
  90133. * Defines the root class used to create scene optimization to use with SceneOptimizer
  90134. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90135. */
  90136. var SceneOptimization = /** @class */ (function () {
  90137. /**
  90138. * Creates the SceneOptimization object
  90139. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90140. * @param desc defines the description associated with the optimization
  90141. */
  90142. function SceneOptimization(
  90143. /**
  90144. * Defines the priority of this optimization (0 by default which means first in the list)
  90145. */
  90146. priority) {
  90147. if (priority === void 0) { priority = 0; }
  90148. this.priority = priority;
  90149. }
  90150. /**
  90151. * Gets a string describing the action executed by the current optimization
  90152. * @returns description string
  90153. */
  90154. SceneOptimization.prototype.getDescription = function () {
  90155. return "";
  90156. };
  90157. /**
  90158. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90159. * @param scene defines the current scene where to apply this optimization
  90160. * @param optimizer defines the current optimizer
  90161. * @returns true if everything that can be done was applied
  90162. */
  90163. SceneOptimization.prototype.apply = function (scene, optimizer) {
  90164. return true;
  90165. };
  90166. ;
  90167. return SceneOptimization;
  90168. }());
  90169. BABYLON.SceneOptimization = SceneOptimization;
  90170. /**
  90171. * Defines an optimization used to reduce the size of render target textures
  90172. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90173. */
  90174. var TextureOptimization = /** @class */ (function (_super) {
  90175. __extends(TextureOptimization, _super);
  90176. /**
  90177. * Creates the TextureOptimization object
  90178. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90179. * @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
  90180. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90181. */
  90182. function TextureOptimization(
  90183. /**
  90184. * Defines the priority of this optimization (0 by default which means first in the list)
  90185. */
  90186. priority,
  90187. /**
  90188. * 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
  90189. */
  90190. maximumSize,
  90191. /**
  90192. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  90193. */
  90194. step) {
  90195. if (priority === void 0) { priority = 0; }
  90196. if (maximumSize === void 0) { maximumSize = 1024; }
  90197. if (step === void 0) { step = 0.5; }
  90198. var _this = _super.call(this, priority) || this;
  90199. _this.priority = priority;
  90200. _this.maximumSize = maximumSize;
  90201. _this.step = step;
  90202. return _this;
  90203. }
  90204. /**
  90205. * Gets a string describing the action executed by the current optimization
  90206. * @returns description string
  90207. */
  90208. TextureOptimization.prototype.getDescription = function () {
  90209. return "Reducing render target texture size to " + this.maximumSize;
  90210. };
  90211. /**
  90212. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90213. * @param scene defines the current scene where to apply this optimization
  90214. * @param optimizer defines the current optimizer
  90215. * @returns true if everything that can be done was applied
  90216. */
  90217. TextureOptimization.prototype.apply = function (scene, optimizer) {
  90218. var allDone = true;
  90219. for (var index = 0; index < scene.textures.length; index++) {
  90220. var texture = scene.textures[index];
  90221. if (!texture.canRescale || texture.getContext) {
  90222. continue;
  90223. }
  90224. var currentSize = texture.getSize();
  90225. var maxDimension = Math.max(currentSize.width, currentSize.height);
  90226. if (maxDimension > this.maximumSize) {
  90227. texture.scale(this.step);
  90228. allDone = false;
  90229. }
  90230. }
  90231. return allDone;
  90232. };
  90233. return TextureOptimization;
  90234. }(SceneOptimization));
  90235. BABYLON.TextureOptimization = TextureOptimization;
  90236. /**
  90237. * Defines an optimization used to increase or decrease the rendering resolution
  90238. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90239. */
  90240. var HardwareScalingOptimization = /** @class */ (function (_super) {
  90241. __extends(HardwareScalingOptimization, _super);
  90242. /**
  90243. * Creates the HardwareScalingOptimization object
  90244. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90245. * @param maximumScale defines the maximum scale to use (2 by default)
  90246. * @param step defines the step to use between two passes (0.5 by default)
  90247. */
  90248. function HardwareScalingOptimization(
  90249. /**
  90250. * Defines the priority of this optimization (0 by default which means first in the list)
  90251. */
  90252. priority,
  90253. /**
  90254. * Defines the maximum scale to use (2 by default)
  90255. */
  90256. maximumScale,
  90257. /**
  90258. * Defines the step to use between two passes (0.5 by default)
  90259. */
  90260. step) {
  90261. if (priority === void 0) { priority = 0; }
  90262. if (maximumScale === void 0) { maximumScale = 2; }
  90263. if (step === void 0) { step = 0.25; }
  90264. var _this = _super.call(this, priority) || this;
  90265. _this.priority = priority;
  90266. _this.maximumScale = maximumScale;
  90267. _this.step = step;
  90268. _this._currentScale = -1;
  90269. _this._directionOffset = 1;
  90270. return _this;
  90271. }
  90272. /**
  90273. * Gets a string describing the action executed by the current optimization
  90274. * @return description string
  90275. */
  90276. HardwareScalingOptimization.prototype.getDescription = function () {
  90277. return "Setting hardware scaling level to " + this._currentScale;
  90278. };
  90279. /**
  90280. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90281. * @param scene defines the current scene where to apply this optimization
  90282. * @param optimizer defines the current optimizer
  90283. * @returns true if everything that can be done was applied
  90284. */
  90285. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  90286. if (this._currentScale === -1) {
  90287. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  90288. if (this._currentScale > this.maximumScale) {
  90289. this._directionOffset = -1;
  90290. }
  90291. }
  90292. this._currentScale += this._directionOffset * this.step;
  90293. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  90294. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  90295. };
  90296. ;
  90297. return HardwareScalingOptimization;
  90298. }(SceneOptimization));
  90299. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  90300. /**
  90301. * Defines an optimization used to remove shadows
  90302. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90303. */
  90304. var ShadowsOptimization = /** @class */ (function (_super) {
  90305. __extends(ShadowsOptimization, _super);
  90306. function ShadowsOptimization() {
  90307. return _super !== null && _super.apply(this, arguments) || this;
  90308. }
  90309. /**
  90310. * Gets a string describing the action executed by the current optimization
  90311. * @return description string
  90312. */
  90313. ShadowsOptimization.prototype.getDescription = function () {
  90314. return "Turning shadows on/off";
  90315. };
  90316. /**
  90317. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90318. * @param scene defines the current scene where to apply this optimization
  90319. * @param optimizer defines the current optimizer
  90320. * @returns true if everything that can be done was applied
  90321. */
  90322. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  90323. scene.shadowsEnabled = optimizer.isInImprovementMode;
  90324. return true;
  90325. };
  90326. ;
  90327. return ShadowsOptimization;
  90328. }(SceneOptimization));
  90329. BABYLON.ShadowsOptimization = ShadowsOptimization;
  90330. /**
  90331. * Defines an optimization used to turn post-processes off
  90332. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90333. */
  90334. var PostProcessesOptimization = /** @class */ (function (_super) {
  90335. __extends(PostProcessesOptimization, _super);
  90336. function PostProcessesOptimization() {
  90337. return _super !== null && _super.apply(this, arguments) || this;
  90338. }
  90339. /**
  90340. * Gets a string describing the action executed by the current optimization
  90341. * @return description string
  90342. */
  90343. PostProcessesOptimization.prototype.getDescription = function () {
  90344. return "Turning post-processes on/off";
  90345. };
  90346. /**
  90347. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90348. * @param scene defines the current scene where to apply this optimization
  90349. * @param optimizer defines the current optimizer
  90350. * @returns true if everything that can be done was applied
  90351. */
  90352. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  90353. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  90354. return true;
  90355. };
  90356. ;
  90357. return PostProcessesOptimization;
  90358. }(SceneOptimization));
  90359. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  90360. /**
  90361. * Defines an optimization used to turn lens flares off
  90362. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90363. */
  90364. var LensFlaresOptimization = /** @class */ (function (_super) {
  90365. __extends(LensFlaresOptimization, _super);
  90366. function LensFlaresOptimization() {
  90367. return _super !== null && _super.apply(this, arguments) || this;
  90368. }
  90369. /**
  90370. * Gets a string describing the action executed by the current optimization
  90371. * @return description string
  90372. */
  90373. LensFlaresOptimization.prototype.getDescription = function () {
  90374. return "Turning lens flares on/off";
  90375. };
  90376. /**
  90377. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90378. * @param scene defines the current scene where to apply this optimization
  90379. * @param optimizer defines the current optimizer
  90380. * @returns true if everything that can be done was applied
  90381. */
  90382. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  90383. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  90384. return true;
  90385. };
  90386. ;
  90387. return LensFlaresOptimization;
  90388. }(SceneOptimization));
  90389. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  90390. /**
  90391. * Defines an optimization based on user defined callback.
  90392. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90393. */
  90394. var CustomOptimization = /** @class */ (function (_super) {
  90395. __extends(CustomOptimization, _super);
  90396. function CustomOptimization() {
  90397. return _super !== null && _super.apply(this, arguments) || this;
  90398. }
  90399. /**
  90400. * Gets a string describing the action executed by the current optimization
  90401. * @returns description string
  90402. */
  90403. CustomOptimization.prototype.getDescription = function () {
  90404. if (this.onGetDescription) {
  90405. return this.onGetDescription();
  90406. }
  90407. return "Running user defined callback";
  90408. };
  90409. /**
  90410. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90411. * @param scene defines the current scene where to apply this optimization
  90412. * @param optimizer defines the current optimizer
  90413. * @returns true if everything that can be done was applied
  90414. */
  90415. CustomOptimization.prototype.apply = function (scene, optimizer) {
  90416. if (this.onApply) {
  90417. return this.onApply(scene, optimizer);
  90418. }
  90419. return true;
  90420. };
  90421. ;
  90422. return CustomOptimization;
  90423. }(SceneOptimization));
  90424. BABYLON.CustomOptimization = CustomOptimization;
  90425. /**
  90426. * Defines an optimization used to turn particles off
  90427. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90428. */
  90429. var ParticlesOptimization = /** @class */ (function (_super) {
  90430. __extends(ParticlesOptimization, _super);
  90431. function ParticlesOptimization() {
  90432. return _super !== null && _super.apply(this, arguments) || this;
  90433. }
  90434. /**
  90435. * Gets a string describing the action executed by the current optimization
  90436. * @return description string
  90437. */
  90438. ParticlesOptimization.prototype.getDescription = function () {
  90439. return "Turning particles on/off";
  90440. };
  90441. /**
  90442. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90443. * @param scene defines the current scene where to apply this optimization
  90444. * @param optimizer defines the current optimizer
  90445. * @returns true if everything that can be done was applied
  90446. */
  90447. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  90448. scene.particlesEnabled = optimizer.isInImprovementMode;
  90449. return true;
  90450. };
  90451. ;
  90452. return ParticlesOptimization;
  90453. }(SceneOptimization));
  90454. BABYLON.ParticlesOptimization = ParticlesOptimization;
  90455. /**
  90456. * Defines an optimization used to turn render targets off
  90457. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90458. */
  90459. var RenderTargetsOptimization = /** @class */ (function (_super) {
  90460. __extends(RenderTargetsOptimization, _super);
  90461. function RenderTargetsOptimization() {
  90462. return _super !== null && _super.apply(this, arguments) || this;
  90463. }
  90464. /**
  90465. * Gets a string describing the action executed by the current optimization
  90466. * @return description string
  90467. */
  90468. RenderTargetsOptimization.prototype.getDescription = function () {
  90469. return "Turning render targets off";
  90470. };
  90471. /**
  90472. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90473. * @param scene defines the current scene where to apply this optimization
  90474. * @param optimizer defines the current optimizer
  90475. * @returns true if everything that can be done was applied
  90476. */
  90477. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  90478. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  90479. return true;
  90480. };
  90481. ;
  90482. return RenderTargetsOptimization;
  90483. }(SceneOptimization));
  90484. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  90485. /**
  90486. * Defines an optimization used to merge meshes with compatible materials
  90487. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90488. */
  90489. var MergeMeshesOptimization = /** @class */ (function (_super) {
  90490. __extends(MergeMeshesOptimization, _super);
  90491. function MergeMeshesOptimization() {
  90492. var _this = _super !== null && _super.apply(this, arguments) || this;
  90493. _this._canBeMerged = function (abstractMesh) {
  90494. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  90495. return false;
  90496. }
  90497. var mesh = abstractMesh;
  90498. if (!mesh.isVisible || !mesh.isEnabled()) {
  90499. return false;
  90500. }
  90501. if (mesh.instances.length > 0) {
  90502. return false;
  90503. }
  90504. if (mesh.skeleton || mesh.hasLODLevels) {
  90505. return false;
  90506. }
  90507. if (mesh.parent) {
  90508. return false;
  90509. }
  90510. return true;
  90511. };
  90512. return _this;
  90513. }
  90514. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  90515. /**
  90516. * Gets or sets a boolean which defines if optimization octree has to be updated
  90517. */
  90518. get: function () {
  90519. return MergeMeshesOptimization._UpdateSelectionTree;
  90520. },
  90521. /**
  90522. * Gets or sets a boolean which defines if optimization octree has to be updated
  90523. */
  90524. set: function (value) {
  90525. MergeMeshesOptimization._UpdateSelectionTree = value;
  90526. },
  90527. enumerable: true,
  90528. configurable: true
  90529. });
  90530. /**
  90531. * Gets a string describing the action executed by the current optimization
  90532. * @return description string
  90533. */
  90534. MergeMeshesOptimization.prototype.getDescription = function () {
  90535. return "Merging similar meshes together";
  90536. };
  90537. /**
  90538. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  90539. * @param scene defines the current scene where to apply this optimization
  90540. * @param optimizer defines the current optimizer
  90541. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  90542. * @returns true if everything that can be done was applied
  90543. */
  90544. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  90545. var globalPool = scene.meshes.slice(0);
  90546. var globalLength = globalPool.length;
  90547. for (var index = 0; index < globalLength; index++) {
  90548. var currentPool = new Array();
  90549. var current = globalPool[index];
  90550. // Checks
  90551. if (!this._canBeMerged(current)) {
  90552. continue;
  90553. }
  90554. currentPool.push(current);
  90555. // Find compatible meshes
  90556. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  90557. var otherMesh = globalPool[subIndex];
  90558. if (!this._canBeMerged(otherMesh)) {
  90559. continue;
  90560. }
  90561. if (otherMesh.material !== current.material) {
  90562. continue;
  90563. }
  90564. if (otherMesh.checkCollisions !== current.checkCollisions) {
  90565. continue;
  90566. }
  90567. currentPool.push(otherMesh);
  90568. globalLength--;
  90569. globalPool.splice(subIndex, 1);
  90570. subIndex--;
  90571. }
  90572. if (currentPool.length < 2) {
  90573. continue;
  90574. }
  90575. // Merge meshes
  90576. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  90577. }
  90578. if (updateSelectionTree != undefined) {
  90579. if (updateSelectionTree) {
  90580. scene.createOrUpdateSelectionOctree();
  90581. }
  90582. }
  90583. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  90584. scene.createOrUpdateSelectionOctree();
  90585. }
  90586. return true;
  90587. };
  90588. ;
  90589. MergeMeshesOptimization._UpdateSelectionTree = false;
  90590. return MergeMeshesOptimization;
  90591. }(SceneOptimization));
  90592. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  90593. /**
  90594. * Defines a list of options used by SceneOptimizer
  90595. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90596. */
  90597. var SceneOptimizerOptions = /** @class */ (function () {
  90598. /**
  90599. * Creates a new list of options used by SceneOptimizer
  90600. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  90601. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  90602. */
  90603. function SceneOptimizerOptions(
  90604. /**
  90605. * Defines the target frame rate to reach (60 by default)
  90606. */
  90607. targetFrameRate,
  90608. /**
  90609. * Defines the interval between two checkes (2000ms by default)
  90610. */
  90611. trackerDuration) {
  90612. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  90613. if (trackerDuration === void 0) { trackerDuration = 2000; }
  90614. this.targetFrameRate = targetFrameRate;
  90615. this.trackerDuration = trackerDuration;
  90616. /**
  90617. * Gets the list of optimizations to apply
  90618. */
  90619. this.optimizations = new Array();
  90620. }
  90621. /**
  90622. * Add a new optimization
  90623. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  90624. * @returns the current SceneOptimizerOptions
  90625. */
  90626. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  90627. this.optimizations.push(optimization);
  90628. return this;
  90629. };
  90630. /**
  90631. * Add a new custom optimization
  90632. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  90633. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  90634. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  90635. * @returns the current SceneOptimizerOptions
  90636. */
  90637. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  90638. if (priority === void 0) { priority = 0; }
  90639. var optimization = new CustomOptimization(priority);
  90640. optimization.onApply = onApply;
  90641. optimization.onGetDescription = onGetDescription;
  90642. this.optimizations.push(optimization);
  90643. return this;
  90644. };
  90645. /**
  90646. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  90647. * @param targetFrameRate defines the target frame rate (60 by default)
  90648. * @returns a SceneOptimizerOptions object
  90649. */
  90650. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  90651. var result = new SceneOptimizerOptions(targetFrameRate);
  90652. var priority = 0;
  90653. result.addOptimization(new MergeMeshesOptimization(priority));
  90654. result.addOptimization(new ShadowsOptimization(priority));
  90655. result.addOptimization(new LensFlaresOptimization(priority));
  90656. // Next priority
  90657. priority++;
  90658. result.addOptimization(new PostProcessesOptimization(priority));
  90659. result.addOptimization(new ParticlesOptimization(priority));
  90660. // Next priority
  90661. priority++;
  90662. result.addOptimization(new TextureOptimization(priority, 1024));
  90663. return result;
  90664. };
  90665. /**
  90666. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  90667. * @param targetFrameRate defines the target frame rate (60 by default)
  90668. * @returns a SceneOptimizerOptions object
  90669. */
  90670. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  90671. var result = new SceneOptimizerOptions(targetFrameRate);
  90672. var priority = 0;
  90673. result.addOptimization(new MergeMeshesOptimization(priority));
  90674. result.addOptimization(new ShadowsOptimization(priority));
  90675. result.addOptimization(new LensFlaresOptimization(priority));
  90676. // Next priority
  90677. priority++;
  90678. result.addOptimization(new PostProcessesOptimization(priority));
  90679. result.addOptimization(new ParticlesOptimization(priority));
  90680. // Next priority
  90681. priority++;
  90682. result.addOptimization(new TextureOptimization(priority, 512));
  90683. // Next priority
  90684. priority++;
  90685. result.addOptimization(new RenderTargetsOptimization(priority));
  90686. // Next priority
  90687. priority++;
  90688. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  90689. return result;
  90690. };
  90691. /**
  90692. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  90693. * @param targetFrameRate defines the target frame rate (60 by default)
  90694. * @returns a SceneOptimizerOptions object
  90695. */
  90696. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  90697. var result = new SceneOptimizerOptions(targetFrameRate);
  90698. var priority = 0;
  90699. result.addOptimization(new MergeMeshesOptimization(priority));
  90700. result.addOptimization(new ShadowsOptimization(priority));
  90701. result.addOptimization(new LensFlaresOptimization(priority));
  90702. // Next priority
  90703. priority++;
  90704. result.addOptimization(new PostProcessesOptimization(priority));
  90705. result.addOptimization(new ParticlesOptimization(priority));
  90706. // Next priority
  90707. priority++;
  90708. result.addOptimization(new TextureOptimization(priority, 256));
  90709. // Next priority
  90710. priority++;
  90711. result.addOptimization(new RenderTargetsOptimization(priority));
  90712. // Next priority
  90713. priority++;
  90714. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  90715. return result;
  90716. };
  90717. return SceneOptimizerOptions;
  90718. }());
  90719. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  90720. /**
  90721. * Class used to run optimizations in order to reach a target frame rate
  90722. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  90723. */
  90724. var SceneOptimizer = /** @class */ (function () {
  90725. /**
  90726. * Creates a new SceneOptimizer
  90727. * @param scene defines the scene to work on
  90728. * @param options defines the options to use with the SceneOptimizer
  90729. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  90730. * @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)
  90731. */
  90732. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  90733. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  90734. if (improvementMode === void 0) { improvementMode = false; }
  90735. var _this = this;
  90736. this._isRunning = false;
  90737. this._currentPriorityLevel = 0;
  90738. this._targetFrameRate = 60;
  90739. this._trackerDuration = 2000;
  90740. this._currentFrameRate = 0;
  90741. this._improvementMode = false;
  90742. /**
  90743. * Defines an observable called when the optimizer reaches the target frame rate
  90744. */
  90745. this.onSuccessObservable = new BABYLON.Observable();
  90746. /**
  90747. * Defines an observable called when the optimizer enables an optimization
  90748. */
  90749. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  90750. /**
  90751. * Defines an observable called when the optimizer is not able to reach the target frame rate
  90752. */
  90753. this.onFailureObservable = new BABYLON.Observable();
  90754. if (!options) {
  90755. this._options = new SceneOptimizerOptions();
  90756. }
  90757. else {
  90758. this._options = options;
  90759. }
  90760. if (this._options.targetFrameRate) {
  90761. this._targetFrameRate = this._options.targetFrameRate;
  90762. }
  90763. if (this._options.trackerDuration) {
  90764. this._trackerDuration = this._options.trackerDuration;
  90765. }
  90766. if (autoGeneratePriorities) {
  90767. var priority = 0;
  90768. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  90769. var optim = _a[_i];
  90770. optim.priority = priority++;
  90771. }
  90772. }
  90773. this._improvementMode = improvementMode;
  90774. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90775. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  90776. _this._sceneDisposeObserver = null;
  90777. _this.dispose();
  90778. });
  90779. }
  90780. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  90781. /**
  90782. * Gets a boolean indicating if the optimizer is in improvement mode
  90783. */
  90784. get: function () {
  90785. return this._improvementMode;
  90786. },
  90787. enumerable: true,
  90788. configurable: true
  90789. });
  90790. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  90791. /**
  90792. * Gets the current priority level (0 at start)
  90793. */
  90794. get: function () {
  90795. return this._currentPriorityLevel;
  90796. },
  90797. enumerable: true,
  90798. configurable: true
  90799. });
  90800. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  90801. /**
  90802. * Gets the current frame rate checked by the SceneOptimizer
  90803. */
  90804. get: function () {
  90805. return this._currentFrameRate;
  90806. },
  90807. enumerable: true,
  90808. configurable: true
  90809. });
  90810. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  90811. /**
  90812. * Gets or sets the current target frame rate (60 by default)
  90813. */
  90814. get: function () {
  90815. return this._targetFrameRate;
  90816. },
  90817. /**
  90818. * Gets or sets the current target frame rate (60 by default)
  90819. */
  90820. set: function (value) {
  90821. this._targetFrameRate = value;
  90822. },
  90823. enumerable: true,
  90824. configurable: true
  90825. });
  90826. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  90827. /**
  90828. * Gets or sets the current interval between two checks (every 2000ms by default)
  90829. */
  90830. get: function () {
  90831. return this._trackerDuration;
  90832. },
  90833. /**
  90834. * Gets or sets the current interval between two checks (every 2000ms by default)
  90835. */
  90836. set: function (value) {
  90837. this._trackerDuration = value;
  90838. },
  90839. enumerable: true,
  90840. configurable: true
  90841. });
  90842. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  90843. /**
  90844. * Gets the list of active optimizations
  90845. */
  90846. get: function () {
  90847. return this._options.optimizations;
  90848. },
  90849. enumerable: true,
  90850. configurable: true
  90851. });
  90852. /**
  90853. * Stops the current optimizer
  90854. */
  90855. SceneOptimizer.prototype.stop = function () {
  90856. this._isRunning = false;
  90857. };
  90858. /**
  90859. * Reset the optimizer to initial step (current priority level = 0)
  90860. */
  90861. SceneOptimizer.prototype.reset = function () {
  90862. this._currentPriorityLevel = 0;
  90863. };
  90864. /**
  90865. * Start the optimizer. By default it will try to reach a specific framerate
  90866. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  90867. */
  90868. SceneOptimizer.prototype.start = function () {
  90869. var _this = this;
  90870. if (this._isRunning) {
  90871. return;
  90872. }
  90873. this._isRunning = true;
  90874. // Let's wait for the scene to be ready before running our check
  90875. this._scene.executeWhenReady(function () {
  90876. setTimeout(function () {
  90877. _this._checkCurrentState();
  90878. }, _this._trackerDuration);
  90879. });
  90880. };
  90881. SceneOptimizer.prototype._checkCurrentState = function () {
  90882. var _this = this;
  90883. if (!this._isRunning) {
  90884. return;
  90885. }
  90886. var scene = this._scene;
  90887. var options = this._options;
  90888. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  90889. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  90890. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  90891. this._isRunning = false;
  90892. this.onSuccessObservable.notifyObservers(this);
  90893. return;
  90894. }
  90895. // Apply current level of optimizations
  90896. var allDone = true;
  90897. var noOptimizationApplied = true;
  90898. for (var index = 0; index < options.optimizations.length; index++) {
  90899. var optimization = options.optimizations[index];
  90900. if (optimization.priority === this._currentPriorityLevel) {
  90901. noOptimizationApplied = false;
  90902. allDone = allDone && optimization.apply(scene, this);
  90903. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  90904. }
  90905. }
  90906. // If no optimization was applied, this is a failure :(
  90907. if (noOptimizationApplied) {
  90908. this._isRunning = false;
  90909. this.onFailureObservable.notifyObservers(this);
  90910. return;
  90911. }
  90912. // If all optimizations were done, move to next level
  90913. if (allDone) {
  90914. this._currentPriorityLevel++;
  90915. }
  90916. // Let's the system running for a specific amount of time before checking FPS
  90917. scene.executeWhenReady(function () {
  90918. setTimeout(function () {
  90919. _this._checkCurrentState();
  90920. }, _this._trackerDuration);
  90921. });
  90922. };
  90923. /**
  90924. * Release all resources
  90925. */
  90926. SceneOptimizer.prototype.dispose = function () {
  90927. this.stop();
  90928. this.onSuccessObservable.clear();
  90929. this.onFailureObservable.clear();
  90930. this.onNewOptimizationAppliedObservable.clear();
  90931. if (this._sceneDisposeObserver) {
  90932. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  90933. }
  90934. };
  90935. /**
  90936. * Helper function to create a SceneOptimizer with one single line of code
  90937. * @param scene defines the scene to work on
  90938. * @param options defines the options to use with the SceneOptimizer
  90939. * @param onSuccess defines a callback to call on success
  90940. * @param onFailure defines a callback to call on failure
  90941. * @returns the new SceneOptimizer object
  90942. */
  90943. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  90944. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  90945. if (onSuccess) {
  90946. optimizer.onSuccessObservable.add(function () {
  90947. onSuccess();
  90948. });
  90949. }
  90950. if (onFailure) {
  90951. optimizer.onFailureObservable.add(function () {
  90952. onFailure();
  90953. });
  90954. }
  90955. optimizer.start();
  90956. return optimizer;
  90957. };
  90958. return SceneOptimizer;
  90959. }());
  90960. BABYLON.SceneOptimizer = SceneOptimizer;
  90961. })(BABYLON || (BABYLON = {}));
  90962. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  90963. var BABYLON;
  90964. (function (BABYLON) {
  90965. var OutlineRenderer = /** @class */ (function () {
  90966. function OutlineRenderer(scene) {
  90967. this.zOffset = 1;
  90968. this._scene = scene;
  90969. }
  90970. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  90971. var _this = this;
  90972. if (useOverlay === void 0) { useOverlay = false; }
  90973. var scene = this._scene;
  90974. var engine = this._scene.getEngine();
  90975. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  90976. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  90977. return;
  90978. }
  90979. var mesh = subMesh.getRenderingMesh();
  90980. var material = subMesh.getMaterial();
  90981. if (!material || !scene.activeCamera) {
  90982. return;
  90983. }
  90984. engine.enableEffect(this._effect);
  90985. // Logarithmic depth
  90986. if (material.useLogarithmicDepth) {
  90987. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  90988. }
  90989. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  90990. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  90991. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  90992. // Bones
  90993. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  90994. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  90995. }
  90996. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  90997. // Alpha test
  90998. if (material && material.needAlphaTesting()) {
  90999. var alphaTexture = material.getAlphaTestTexture();
  91000. if (alphaTexture) {
  91001. this._effect.setTexture("diffuseSampler", alphaTexture);
  91002. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  91003. }
  91004. }
  91005. engine.setZOffset(-this.zOffset);
  91006. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  91007. engine.setZOffset(0);
  91008. };
  91009. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  91010. var defines = [];
  91011. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  91012. var mesh = subMesh.getMesh();
  91013. var material = subMesh.getMaterial();
  91014. if (material) {
  91015. // Alpha test
  91016. if (material.needAlphaTesting()) {
  91017. defines.push("#define ALPHATEST");
  91018. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91019. attribs.push(BABYLON.VertexBuffer.UVKind);
  91020. defines.push("#define UV1");
  91021. }
  91022. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  91023. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91024. defines.push("#define UV2");
  91025. }
  91026. }
  91027. //Logarithmic depth
  91028. if (material.useLogarithmicDepth) {
  91029. defines.push("#define LOGARITHMICDEPTH");
  91030. }
  91031. }
  91032. // Bones
  91033. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91034. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91035. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91036. if (mesh.numBoneInfluencers > 4) {
  91037. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91038. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91039. }
  91040. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91041. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  91042. }
  91043. else {
  91044. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91045. }
  91046. // Instances
  91047. if (useInstances) {
  91048. defines.push("#define INSTANCES");
  91049. attribs.push("world0");
  91050. attribs.push("world1");
  91051. attribs.push("world2");
  91052. attribs.push("world3");
  91053. }
  91054. // Get correct effect
  91055. var join = defines.join("\n");
  91056. if (this._cachedDefines !== join) {
  91057. this._cachedDefines = join;
  91058. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  91059. }
  91060. return this._effect.isReady();
  91061. };
  91062. return OutlineRenderer;
  91063. }());
  91064. BABYLON.OutlineRenderer = OutlineRenderer;
  91065. })(BABYLON || (BABYLON = {}));
  91066. //# sourceMappingURL=babylon.outlineRenderer.js.map
  91067. var BABYLON;
  91068. (function (BABYLON) {
  91069. var FaceAdjacencies = /** @class */ (function () {
  91070. function FaceAdjacencies() {
  91071. this.edges = new Array();
  91072. this.edgesConnectedCount = 0;
  91073. }
  91074. return FaceAdjacencies;
  91075. }());
  91076. var EdgesRenderer = /** @class */ (function () {
  91077. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  91078. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  91079. if (epsilon === void 0) { epsilon = 0.95; }
  91080. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  91081. this.edgesWidthScalerForOrthographic = 1000.0;
  91082. this.edgesWidthScalerForPerspective = 50.0;
  91083. this._linesPositions = new Array();
  91084. this._linesNormals = new Array();
  91085. this._linesIndices = new Array();
  91086. this._buffers = {};
  91087. this._checkVerticesInsteadOfIndices = false;
  91088. this._source = source;
  91089. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  91090. this._epsilon = epsilon;
  91091. this._prepareRessources();
  91092. this._generateEdgesLines();
  91093. }
  91094. EdgesRenderer.prototype._prepareRessources = function () {
  91095. if (this._lineShader) {
  91096. return;
  91097. }
  91098. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  91099. attributes: ["position", "normal"],
  91100. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  91101. });
  91102. this._lineShader.disableDepthWrite = true;
  91103. this._lineShader.backFaceCulling = false;
  91104. };
  91105. EdgesRenderer.prototype._rebuild = function () {
  91106. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91107. if (buffer) {
  91108. buffer._rebuild();
  91109. }
  91110. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91111. if (buffer) {
  91112. buffer._rebuild();
  91113. }
  91114. var scene = this._source.getScene();
  91115. var engine = scene.getEngine();
  91116. this._ib = engine.createIndexBuffer(this._linesIndices);
  91117. };
  91118. EdgesRenderer.prototype.dispose = function () {
  91119. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  91120. if (buffer) {
  91121. buffer.dispose();
  91122. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  91123. }
  91124. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  91125. if (buffer) {
  91126. buffer.dispose();
  91127. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  91128. }
  91129. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  91130. this._lineShader.dispose();
  91131. };
  91132. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  91133. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  91134. return 0;
  91135. }
  91136. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  91137. return 1;
  91138. }
  91139. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  91140. return 2;
  91141. }
  91142. return -1;
  91143. };
  91144. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  91145. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  91146. return 0;
  91147. }
  91148. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  91149. return 1;
  91150. }
  91151. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  91152. return 2;
  91153. }
  91154. return -1;
  91155. };
  91156. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  91157. var needToCreateLine;
  91158. if (edge === undefined) {
  91159. needToCreateLine = true;
  91160. }
  91161. else {
  91162. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  91163. needToCreateLine = dotProduct < this._epsilon;
  91164. }
  91165. if (needToCreateLine) {
  91166. var offset = this._linesPositions.length / 3;
  91167. var normal = p0.subtract(p1);
  91168. normal.normalize();
  91169. // Positions
  91170. this._linesPositions.push(p0.x);
  91171. this._linesPositions.push(p0.y);
  91172. this._linesPositions.push(p0.z);
  91173. this._linesPositions.push(p0.x);
  91174. this._linesPositions.push(p0.y);
  91175. this._linesPositions.push(p0.z);
  91176. this._linesPositions.push(p1.x);
  91177. this._linesPositions.push(p1.y);
  91178. this._linesPositions.push(p1.z);
  91179. this._linesPositions.push(p1.x);
  91180. this._linesPositions.push(p1.y);
  91181. this._linesPositions.push(p1.z);
  91182. // Normals
  91183. this._linesNormals.push(p1.x);
  91184. this._linesNormals.push(p1.y);
  91185. this._linesNormals.push(p1.z);
  91186. this._linesNormals.push(-1);
  91187. this._linesNormals.push(p1.x);
  91188. this._linesNormals.push(p1.y);
  91189. this._linesNormals.push(p1.z);
  91190. this._linesNormals.push(1);
  91191. this._linesNormals.push(p0.x);
  91192. this._linesNormals.push(p0.y);
  91193. this._linesNormals.push(p0.z);
  91194. this._linesNormals.push(-1);
  91195. this._linesNormals.push(p0.x);
  91196. this._linesNormals.push(p0.y);
  91197. this._linesNormals.push(p0.z);
  91198. this._linesNormals.push(1);
  91199. // Indices
  91200. this._linesIndices.push(offset);
  91201. this._linesIndices.push(offset + 1);
  91202. this._linesIndices.push(offset + 2);
  91203. this._linesIndices.push(offset);
  91204. this._linesIndices.push(offset + 2);
  91205. this._linesIndices.push(offset + 3);
  91206. }
  91207. };
  91208. EdgesRenderer.prototype._generateEdgesLines = function () {
  91209. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  91210. var indices = this._source.getIndices();
  91211. if (!indices || !positions) {
  91212. return;
  91213. }
  91214. // First let's find adjacencies
  91215. var adjacencies = new Array();
  91216. var faceNormals = new Array();
  91217. var index;
  91218. var faceAdjacencies;
  91219. // Prepare faces
  91220. for (index = 0; index < indices.length; index += 3) {
  91221. faceAdjacencies = new FaceAdjacencies();
  91222. var p0Index = indices[index];
  91223. var p1Index = indices[index + 1];
  91224. var p2Index = indices[index + 2];
  91225. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  91226. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  91227. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  91228. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  91229. faceNormal.normalize();
  91230. faceNormals.push(faceNormal);
  91231. adjacencies.push(faceAdjacencies);
  91232. }
  91233. // Scan
  91234. for (index = 0; index < adjacencies.length; index++) {
  91235. faceAdjacencies = adjacencies[index];
  91236. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  91237. var otherFaceAdjacencies = adjacencies[otherIndex];
  91238. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  91239. break;
  91240. }
  91241. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  91242. continue;
  91243. }
  91244. var otherP0 = indices[otherIndex * 3];
  91245. var otherP1 = indices[otherIndex * 3 + 1];
  91246. var otherP2 = indices[otherIndex * 3 + 2];
  91247. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  91248. var otherEdgeIndex = 0;
  91249. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  91250. continue;
  91251. }
  91252. switch (edgeIndex) {
  91253. case 0:
  91254. if (this._checkVerticesInsteadOfIndices) {
  91255. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91256. }
  91257. else {
  91258. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  91259. }
  91260. break;
  91261. case 1:
  91262. if (this._checkVerticesInsteadOfIndices) {
  91263. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91264. }
  91265. else {
  91266. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  91267. }
  91268. break;
  91269. case 2:
  91270. if (this._checkVerticesInsteadOfIndices) {
  91271. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  91272. }
  91273. else {
  91274. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  91275. }
  91276. break;
  91277. }
  91278. if (otherEdgeIndex === -1) {
  91279. continue;
  91280. }
  91281. faceAdjacencies.edges[edgeIndex] = otherIndex;
  91282. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  91283. faceAdjacencies.edgesConnectedCount++;
  91284. otherFaceAdjacencies.edgesConnectedCount++;
  91285. if (faceAdjacencies.edgesConnectedCount === 3) {
  91286. break;
  91287. }
  91288. }
  91289. }
  91290. }
  91291. // Create lines
  91292. for (index = 0; index < adjacencies.length; index++) {
  91293. // 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
  91294. var current = adjacencies[index];
  91295. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  91296. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  91297. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  91298. }
  91299. // Merge into a single mesh
  91300. var engine = this._source.getScene().getEngine();
  91301. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  91302. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  91303. this._ib = engine.createIndexBuffer(this._linesIndices);
  91304. this._indicesCount = this._linesIndices.length;
  91305. };
  91306. EdgesRenderer.prototype.render = function () {
  91307. var scene = this._source.getScene();
  91308. if (!this._lineShader.isReady() || !scene.activeCamera) {
  91309. return;
  91310. }
  91311. var engine = scene.getEngine();
  91312. this._lineShader._preBind();
  91313. // VBOs
  91314. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  91315. scene.resetCachedMaterial();
  91316. this._lineShader.setColor4("color", this._source.edgesColor);
  91317. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  91318. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  91319. }
  91320. else {
  91321. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  91322. }
  91323. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  91324. this._lineShader.bind(this._source.getWorldMatrix());
  91325. // Draw order
  91326. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  91327. this._lineShader.unbind();
  91328. engine.setDepthWrite(true);
  91329. };
  91330. return EdgesRenderer;
  91331. }());
  91332. BABYLON.EdgesRenderer = EdgesRenderer;
  91333. })(BABYLON || (BABYLON = {}));
  91334. //# sourceMappingURL=babylon.edgesRenderer.js.map
  91335. var __assign = (this && this.__assign) || Object.assign || function(t) {
  91336. for (var s, i = 1, n = arguments.length; i < n; i++) {
  91337. s = arguments[i];
  91338. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  91339. t[p] = s[p];
  91340. }
  91341. return t;
  91342. };
  91343. var BABYLON;
  91344. (function (BABYLON) {
  91345. /**
  91346. * The effect layer Helps adding post process effect blended with the main pass.
  91347. *
  91348. * This can be for instance use to generate glow or higlight effects on the scene.
  91349. *
  91350. * The effect layer class can not be used directly and is intented to inherited from to be
  91351. * customized per effects.
  91352. */
  91353. var EffectLayer = /** @class */ (function () {
  91354. /**
  91355. * Instantiates a new effect Layer and references it in the scene.
  91356. * @param name The name of the layer
  91357. * @param scene The scene to use the layer in
  91358. */
  91359. function EffectLayer(
  91360. /** The Friendly of the effect in the scene */
  91361. name, scene) {
  91362. this._vertexBuffers = {};
  91363. this._maxSize = 0;
  91364. this._mainTextureDesiredSize = { width: 0, height: 0 };
  91365. this._shouldRender = true;
  91366. this._postProcesses = [];
  91367. this._textures = [];
  91368. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  91369. /**
  91370. * The clear color of the texture used to generate the glow map.
  91371. */
  91372. this.neutralColor = new BABYLON.Color4();
  91373. /**
  91374. * Specifies wether the highlight layer is enabled or not.
  91375. */
  91376. this.isEnabled = true;
  91377. /**
  91378. * An event triggered when the effect layer has been disposed.
  91379. */
  91380. this.onDisposeObservable = new BABYLON.Observable();
  91381. /**
  91382. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  91383. */
  91384. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  91385. /**
  91386. * An event triggered when the generated texture is being merged in the scene.
  91387. */
  91388. this.onBeforeComposeObservable = new BABYLON.Observable();
  91389. /**
  91390. * An event triggered when the generated texture has been merged in the scene.
  91391. */
  91392. this.onAfterComposeObservable = new BABYLON.Observable();
  91393. /**
  91394. * An event triggered when the efffect layer changes its size.
  91395. */
  91396. this.onSizeChangedObservable = new BABYLON.Observable();
  91397. this.name = name;
  91398. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  91399. this._engine = scene.getEngine();
  91400. this._maxSize = this._engine.getCaps().maxTextureSize;
  91401. this._scene.effectLayers.push(this);
  91402. // Generate Buffers
  91403. this._generateIndexBuffer();
  91404. this._genrateVertexBuffer();
  91405. }
  91406. Object.defineProperty(EffectLayer.prototype, "camera", {
  91407. /**
  91408. * Gets the camera attached to the layer.
  91409. */
  91410. get: function () {
  91411. return this._effectLayerOptions.camera;
  91412. },
  91413. enumerable: true,
  91414. configurable: true
  91415. });
  91416. /**
  91417. * Initializes the effect layer with the required options.
  91418. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  91419. */
  91420. EffectLayer.prototype._init = function (options) {
  91421. // Adapt options
  91422. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91423. this._setMainTextureSize();
  91424. this._createMainTexture();
  91425. this._createTextureAndPostProcesses();
  91426. this._mergeEffect = this._createMergeEffect();
  91427. };
  91428. /**
  91429. * Generates the index buffer of the full screen quad blending to the main canvas.
  91430. */
  91431. EffectLayer.prototype._generateIndexBuffer = function () {
  91432. // Indices
  91433. var indices = [];
  91434. indices.push(0);
  91435. indices.push(1);
  91436. indices.push(2);
  91437. indices.push(0);
  91438. indices.push(2);
  91439. indices.push(3);
  91440. this._indexBuffer = this._engine.createIndexBuffer(indices);
  91441. };
  91442. /**
  91443. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  91444. */
  91445. EffectLayer.prototype._genrateVertexBuffer = function () {
  91446. // VBO
  91447. var vertices = [];
  91448. vertices.push(1, 1);
  91449. vertices.push(-1, 1);
  91450. vertices.push(-1, -1);
  91451. vertices.push(1, -1);
  91452. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  91453. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  91454. };
  91455. /**
  91456. * Sets the main texture desired size which is the closest power of two
  91457. * of the engine canvas size.
  91458. */
  91459. EffectLayer.prototype._setMainTextureSize = function () {
  91460. if (this._effectLayerOptions.mainTextureFixedSize) {
  91461. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  91462. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  91463. }
  91464. else {
  91465. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  91466. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  91467. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  91468. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  91469. }
  91470. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  91471. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  91472. };
  91473. /**
  91474. * Creates the main texture for the effect layer.
  91475. */
  91476. EffectLayer.prototype._createMainTexture = function () {
  91477. var _this = this;
  91478. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  91479. width: this._mainTextureDesiredSize.width,
  91480. height: this._mainTextureDesiredSize.height
  91481. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  91482. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  91483. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91484. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91485. this._mainTexture.anisotropicFilteringLevel = 1;
  91486. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  91487. this._mainTexture.renderParticles = false;
  91488. this._mainTexture.renderList = null;
  91489. this._mainTexture.ignoreCameraViewport = true;
  91490. // Custom render function
  91491. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  91492. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  91493. var index;
  91494. var engine = _this._scene.getEngine();
  91495. if (depthOnlySubMeshes.length) {
  91496. engine.setColorWrite(false);
  91497. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  91498. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  91499. }
  91500. engine.setColorWrite(true);
  91501. }
  91502. for (index = 0; index < opaqueSubMeshes.length; index++) {
  91503. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  91504. }
  91505. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  91506. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  91507. }
  91508. for (index = 0; index < transparentSubMeshes.length; index++) {
  91509. _this._renderSubMesh(transparentSubMeshes.data[index]);
  91510. }
  91511. };
  91512. this._mainTexture.onClearObservable.add(function (engine) {
  91513. engine.clear(_this.neutralColor, true, true, true);
  91514. });
  91515. };
  91516. /**
  91517. * Checks for the readiness of the element composing the layer.
  91518. * @param subMesh the mesh to check for
  91519. * @param useInstances specify wether or not to use instances to render the mesh
  91520. * @param emissiveTexture the associated emissive texture used to generate the glow
  91521. * @return true if ready otherwise, false
  91522. */
  91523. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  91524. var material = subMesh.getMaterial();
  91525. if (!material) {
  91526. return false;
  91527. }
  91528. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  91529. return false;
  91530. }
  91531. var defines = [];
  91532. var attribs = [BABYLON.VertexBuffer.PositionKind];
  91533. var mesh = subMesh.getMesh();
  91534. var uv1 = false;
  91535. var uv2 = false;
  91536. // Alpha test
  91537. if (material && material.needAlphaTesting()) {
  91538. var alphaTexture = material.getAlphaTestTexture();
  91539. if (alphaTexture) {
  91540. defines.push("#define ALPHATEST");
  91541. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91542. alphaTexture.coordinatesIndex === 1) {
  91543. defines.push("#define DIFFUSEUV2");
  91544. uv2 = true;
  91545. }
  91546. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91547. defines.push("#define DIFFUSEUV1");
  91548. uv1 = true;
  91549. }
  91550. }
  91551. }
  91552. // Emissive
  91553. if (emissiveTexture) {
  91554. defines.push("#define EMISSIVE");
  91555. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  91556. emissiveTexture.coordinatesIndex === 1) {
  91557. defines.push("#define EMISSIVEUV2");
  91558. uv2 = true;
  91559. }
  91560. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  91561. defines.push("#define EMISSIVEUV1");
  91562. uv1 = true;
  91563. }
  91564. }
  91565. if (uv1) {
  91566. attribs.push(BABYLON.VertexBuffer.UVKind);
  91567. defines.push("#define UV1");
  91568. }
  91569. if (uv2) {
  91570. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  91571. defines.push("#define UV2");
  91572. }
  91573. // Bones
  91574. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  91575. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  91576. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  91577. if (mesh.numBoneInfluencers > 4) {
  91578. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  91579. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  91580. }
  91581. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  91582. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  91583. }
  91584. else {
  91585. defines.push("#define NUM_BONE_INFLUENCERS 0");
  91586. }
  91587. // Morph targets
  91588. var manager = mesh.morphTargetManager;
  91589. var morphInfluencers = 0;
  91590. if (manager) {
  91591. if (manager.numInfluencers > 0) {
  91592. defines.push("#define MORPHTARGETS");
  91593. morphInfluencers = manager.numInfluencers;
  91594. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  91595. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  91596. }
  91597. }
  91598. // Instances
  91599. if (useInstances) {
  91600. defines.push("#define INSTANCES");
  91601. attribs.push("world0");
  91602. attribs.push("world1");
  91603. attribs.push("world2");
  91604. attribs.push("world3");
  91605. }
  91606. // Get correct effect
  91607. var join = defines.join("\n");
  91608. if (this._cachedDefines !== join) {
  91609. this._cachedDefines = join;
  91610. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  91611. }
  91612. return this._effectLayerMapGenerationEffect.isReady();
  91613. };
  91614. /**
  91615. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  91616. */
  91617. EffectLayer.prototype.render = function () {
  91618. var currentEffect = this._mergeEffect;
  91619. // Check
  91620. if (!currentEffect.isReady())
  91621. return;
  91622. for (var i = 0; i < this._postProcesses.length; i++) {
  91623. if (!this._postProcesses[i].isReady()) {
  91624. return;
  91625. }
  91626. }
  91627. var engine = this._scene.getEngine();
  91628. this.onBeforeComposeObservable.notifyObservers(this);
  91629. // Render
  91630. engine.enableEffect(currentEffect);
  91631. engine.setState(false);
  91632. // VBOs
  91633. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  91634. // Cache
  91635. var previousAlphaMode = engine.getAlphaMode();
  91636. // Go Blend.
  91637. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  91638. // Blends the map on the main canvas.
  91639. this._internalRender(currentEffect);
  91640. // Restore Alpha
  91641. engine.setAlphaMode(previousAlphaMode);
  91642. this.onAfterComposeObservable.notifyObservers(this);
  91643. // Handle size changes.
  91644. var size = this._mainTexture.getSize();
  91645. this._setMainTextureSize();
  91646. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  91647. // Recreate RTT and post processes on size change.
  91648. this.onSizeChangedObservable.notifyObservers(this);
  91649. this._disposeTextureAndPostProcesses();
  91650. this._createMainTexture();
  91651. this._createTextureAndPostProcesses();
  91652. }
  91653. };
  91654. /**
  91655. * Determine if a given mesh will be used in the current effect.
  91656. * @param mesh mesh to test
  91657. * @returns true if the mesh will be used
  91658. */
  91659. EffectLayer.prototype.hasMesh = function (mesh) {
  91660. return true;
  91661. };
  91662. /**
  91663. * Returns true if the layer contains information to display, otherwise false.
  91664. * @returns true if the glow layer should be rendered
  91665. */
  91666. EffectLayer.prototype.shouldRender = function () {
  91667. return this.isEnabled && this._shouldRender;
  91668. };
  91669. /**
  91670. * Returns true if the mesh should render, otherwise false.
  91671. * @param mesh The mesh to render
  91672. * @returns true if it should render otherwise false
  91673. */
  91674. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  91675. return true;
  91676. };
  91677. /**
  91678. * Returns true if the mesh should render, otherwise false.
  91679. * @param mesh The mesh to render
  91680. * @returns true if it should render otherwise false
  91681. */
  91682. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  91683. return true;
  91684. };
  91685. /**
  91686. * Renders the submesh passed in parameter to the generation map.
  91687. */
  91688. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  91689. var _this = this;
  91690. if (!this.shouldRender()) {
  91691. return;
  91692. }
  91693. var material = subMesh.getMaterial();
  91694. var mesh = subMesh.getRenderingMesh();
  91695. var scene = this._scene;
  91696. var engine = scene.getEngine();
  91697. if (!material) {
  91698. return;
  91699. }
  91700. // Do not block in blend mode.
  91701. if (material.needAlphaBlendingForMesh(mesh)) {
  91702. return;
  91703. }
  91704. // Culling
  91705. engine.setState(material.backFaceCulling);
  91706. // Managing instances
  91707. var batch = mesh._getInstancesRenderList(subMesh._id);
  91708. if (batch.mustReturn) {
  91709. return;
  91710. }
  91711. // Early Exit per mesh
  91712. if (!this._shouldRenderMesh(mesh)) {
  91713. return;
  91714. }
  91715. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  91716. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  91717. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  91718. engine.enableEffect(this._effectLayerMapGenerationEffect);
  91719. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  91720. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  91721. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  91722. // Alpha test
  91723. if (material && material.needAlphaTesting()) {
  91724. var alphaTexture = material.getAlphaTestTexture();
  91725. if (alphaTexture) {
  91726. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  91727. var textureMatrix = alphaTexture.getTextureMatrix();
  91728. if (textureMatrix) {
  91729. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  91730. }
  91731. }
  91732. }
  91733. // Glow emissive only
  91734. if (this._emissiveTextureAndColor.texture) {
  91735. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  91736. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  91737. }
  91738. // Bones
  91739. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  91740. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  91741. }
  91742. // Morph targets
  91743. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  91744. // Draw
  91745. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  91746. }
  91747. else {
  91748. // Need to reset refresh rate of the shadowMap
  91749. this._mainTexture.resetRefreshCounter();
  91750. }
  91751. };
  91752. /**
  91753. * Rebuild the required buffers.
  91754. * @hidden Internal use only.
  91755. */
  91756. EffectLayer.prototype._rebuild = function () {
  91757. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91758. if (vb) {
  91759. vb._rebuild();
  91760. }
  91761. this._generateIndexBuffer();
  91762. };
  91763. /**
  91764. * Dispose only the render target textures and post process.
  91765. */
  91766. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  91767. this._mainTexture.dispose();
  91768. for (var i = 0; i < this._postProcesses.length; i++) {
  91769. if (this._postProcesses[i]) {
  91770. this._postProcesses[i].dispose();
  91771. }
  91772. }
  91773. this._postProcesses = [];
  91774. for (var i = 0; i < this._textures.length; i++) {
  91775. if (this._textures[i]) {
  91776. this._textures[i].dispose();
  91777. }
  91778. }
  91779. this._textures = [];
  91780. };
  91781. /**
  91782. * Dispose the highlight layer and free resources.
  91783. */
  91784. EffectLayer.prototype.dispose = function () {
  91785. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  91786. if (vertexBuffer) {
  91787. vertexBuffer.dispose();
  91788. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  91789. }
  91790. if (this._indexBuffer) {
  91791. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  91792. this._indexBuffer = null;
  91793. }
  91794. // Clean textures and post processes
  91795. this._disposeTextureAndPostProcesses();
  91796. // Remove from scene
  91797. var index = this._scene.effectLayers.indexOf(this, 0);
  91798. if (index > -1) {
  91799. this._scene.effectLayers.splice(index, 1);
  91800. }
  91801. // Callback
  91802. this.onDisposeObservable.notifyObservers(this);
  91803. this.onDisposeObservable.clear();
  91804. this.onBeforeRenderMainTextureObservable.clear();
  91805. this.onBeforeComposeObservable.clear();
  91806. this.onAfterComposeObservable.clear();
  91807. this.onSizeChangedObservable.clear();
  91808. };
  91809. /**
  91810. * Gets the class name of the effect layer
  91811. * @returns the string with the class name of the effect layer
  91812. */
  91813. EffectLayer.prototype.getClassName = function () {
  91814. return "EffectLayer";
  91815. };
  91816. /**
  91817. * Creates an effect layer from parsed effect layer data
  91818. * @param parsedEffectLayer defines effect layer data
  91819. * @param scene defines the current scene
  91820. * @param rootUrl defines the root URL containing the effect layer information
  91821. * @returns a parsed effect Layer
  91822. */
  91823. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  91824. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  91825. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  91826. };
  91827. __decorate([
  91828. BABYLON.serialize()
  91829. ], EffectLayer.prototype, "name", void 0);
  91830. __decorate([
  91831. BABYLON.serializeAsColor4()
  91832. ], EffectLayer.prototype, "neutralColor", void 0);
  91833. __decorate([
  91834. BABYLON.serialize()
  91835. ], EffectLayer.prototype, "isEnabled", void 0);
  91836. __decorate([
  91837. BABYLON.serializeAsCameraReference()
  91838. ], EffectLayer.prototype, "camera", null);
  91839. return EffectLayer;
  91840. }());
  91841. BABYLON.EffectLayer = EffectLayer;
  91842. })(BABYLON || (BABYLON = {}));
  91843. //# sourceMappingURL=babylon.effectLayer.js.map
  91844. var BABYLON;
  91845. (function (BABYLON) {
  91846. /**
  91847. * Special Glow Blur post process only blurring the alpha channel
  91848. * It enforces keeping the most luminous color in the color channel.
  91849. */
  91850. var GlowBlurPostProcess = /** @class */ (function (_super) {
  91851. __extends(GlowBlurPostProcess, _super);
  91852. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  91853. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  91854. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  91855. _this.direction = direction;
  91856. _this.kernel = kernel;
  91857. _this.onApplyObservable.add(function (effect) {
  91858. effect.setFloat2("screenSize", _this.width, _this.height);
  91859. effect.setVector2("direction", _this.direction);
  91860. effect.setFloat("blurWidth", _this.kernel);
  91861. });
  91862. return _this;
  91863. }
  91864. return GlowBlurPostProcess;
  91865. }(BABYLON.PostProcess));
  91866. /**
  91867. * The highlight layer Helps adding a glow effect around a mesh.
  91868. *
  91869. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  91870. * glowy meshes to your scene.
  91871. *
  91872. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  91873. */
  91874. var HighlightLayer = /** @class */ (function (_super) {
  91875. __extends(HighlightLayer, _super);
  91876. /**
  91877. * Instantiates a new highlight Layer and references it to the scene..
  91878. * @param name The name of the layer
  91879. * @param scene The scene to use the layer in
  91880. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  91881. */
  91882. function HighlightLayer(name, scene, options) {
  91883. var _this = _super.call(this, name, scene) || this;
  91884. _this.name = name;
  91885. /**
  91886. * Specifies whether or not the inner glow is ACTIVE in the layer.
  91887. */
  91888. _this.innerGlow = true;
  91889. /**
  91890. * Specifies whether or not the outer glow is ACTIVE in the layer.
  91891. */
  91892. _this.outerGlow = true;
  91893. /**
  91894. * An event triggered when the highlight layer is being blurred.
  91895. */
  91896. _this.onBeforeBlurObservable = new BABYLON.Observable();
  91897. /**
  91898. * An event triggered when the highlight layer has been blurred.
  91899. */
  91900. _this.onAfterBlurObservable = new BABYLON.Observable();
  91901. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  91902. _this._meshes = {};
  91903. _this._excludedMeshes = {};
  91904. _this.neutralColor = HighlightLayer.NeutralColor;
  91905. // Warn on stencil
  91906. if (!_this._engine.isStencilEnable) {
  91907. 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 }");
  91908. }
  91909. // Adapt options
  91910. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  91911. // Initialize the layer
  91912. _this._init({
  91913. alphaBlendingMode: _this._options.alphaBlendingMode,
  91914. camera: _this._options.camera,
  91915. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  91916. mainTextureRatio: _this._options.mainTextureRatio
  91917. });
  91918. // Do not render as long as no meshes have been added
  91919. _this._shouldRender = false;
  91920. return _this;
  91921. }
  91922. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  91923. /**
  91924. * Gets the horizontal size of the blur.
  91925. */
  91926. get: function () {
  91927. return this._horizontalBlurPostprocess.kernel;
  91928. },
  91929. /**
  91930. * Specifies the horizontal size of the blur.
  91931. */
  91932. set: function (value) {
  91933. this._horizontalBlurPostprocess.kernel = value;
  91934. },
  91935. enumerable: true,
  91936. configurable: true
  91937. });
  91938. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  91939. /**
  91940. * Gets the vertical size of the blur.
  91941. */
  91942. get: function () {
  91943. return this._verticalBlurPostprocess.kernel;
  91944. },
  91945. /**
  91946. * Specifies the vertical size of the blur.
  91947. */
  91948. set: function (value) {
  91949. this._verticalBlurPostprocess.kernel = value;
  91950. },
  91951. enumerable: true,
  91952. configurable: true
  91953. });
  91954. /**
  91955. * Get the effect name of the layer.
  91956. * @return The effect name
  91957. */
  91958. HighlightLayer.prototype.getEffectName = function () {
  91959. return HighlightLayer.EffectName;
  91960. };
  91961. /**
  91962. * Create the merge effect. This is the shader use to blit the information back
  91963. * to the main canvas at the end of the scene rendering.
  91964. */
  91965. HighlightLayer.prototype._createMergeEffect = function () {
  91966. // Effect
  91967. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  91968. };
  91969. /**
  91970. * Creates the render target textures and post processes used in the highlight layer.
  91971. */
  91972. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  91973. var _this = this;
  91974. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  91975. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  91976. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  91977. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  91978. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  91979. width: blurTextureWidth,
  91980. height: blurTextureHeight
  91981. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  91982. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91983. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  91984. this._blurTexture.anisotropicFilteringLevel = 16;
  91985. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  91986. this._blurTexture.renderParticles = false;
  91987. this._blurTexture.ignoreCameraViewport = true;
  91988. this._textures = [this._blurTexture];
  91989. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  91990. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91991. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  91992. effect.setTexture("textureSampler", _this._mainTexture);
  91993. });
  91994. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91995. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  91996. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  91997. });
  91998. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  91999. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  92000. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  92001. });
  92002. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92003. }
  92004. else {
  92005. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  92006. width: blurTextureWidth,
  92007. height: blurTextureHeight
  92008. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92009. this._horizontalBlurPostprocess.width = blurTextureWidth;
  92010. this._horizontalBlurPostprocess.height = blurTextureHeight;
  92011. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  92012. effect.setTexture("textureSampler", _this._mainTexture);
  92013. });
  92014. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  92015. width: blurTextureWidth,
  92016. height: blurTextureHeight
  92017. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, BABYLON.Engine.TEXTURETYPE_HALF_FLOAT);
  92018. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  92019. }
  92020. this._mainTexture.onAfterUnbindObservable.add(function () {
  92021. _this.onBeforeBlurObservable.notifyObservers(_this);
  92022. var internalTexture = _this._blurTexture.getInternalTexture();
  92023. if (internalTexture) {
  92024. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  92025. }
  92026. _this.onAfterBlurObservable.notifyObservers(_this);
  92027. });
  92028. // Prevent autoClear.
  92029. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92030. };
  92031. /**
  92032. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92033. */
  92034. HighlightLayer.prototype.needStencil = function () {
  92035. return true;
  92036. };
  92037. /**
  92038. * Checks for the readiness of the element composing the layer.
  92039. * @param subMesh the mesh to check for
  92040. * @param useInstances specify wether or not to use instances to render the mesh
  92041. * @param emissiveTexture the associated emissive texture used to generate the glow
  92042. * @return true if ready otherwise, false
  92043. */
  92044. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  92045. var material = subMesh.getMaterial();
  92046. var mesh = subMesh.getRenderingMesh();
  92047. if (!material || !mesh || !this._meshes) {
  92048. return false;
  92049. }
  92050. var emissiveTexture = null;
  92051. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92052. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92053. emissiveTexture = material.emissiveTexture;
  92054. }
  92055. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92056. };
  92057. /**
  92058. * Implementation specific of rendering the generating effect on the main canvas.
  92059. * @param effect The effect used to render through
  92060. */
  92061. HighlightLayer.prototype._internalRender = function (effect) {
  92062. // Texture
  92063. effect.setTexture("textureSampler", this._blurTexture);
  92064. // Cache
  92065. var engine = this._engine;
  92066. var previousStencilBuffer = engine.getStencilBuffer();
  92067. var previousStencilFunction = engine.getStencilFunction();
  92068. var previousStencilMask = engine.getStencilMask();
  92069. var previousStencilOperationPass = engine.getStencilOperationPass();
  92070. var previousStencilOperationFail = engine.getStencilOperationFail();
  92071. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  92072. var previousStencilReference = engine.getStencilFunctionReference();
  92073. // Stencil operations
  92074. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  92075. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  92076. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  92077. // Draw order
  92078. engine.setStencilMask(0x00);
  92079. engine.setStencilBuffer(true);
  92080. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  92081. // 2 passes inner outer
  92082. if (this.outerGlow) {
  92083. effect.setFloat("offset", 0);
  92084. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  92085. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92086. }
  92087. if (this.innerGlow) {
  92088. effect.setFloat("offset", 1);
  92089. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  92090. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92091. }
  92092. // Restore Cache
  92093. engine.setStencilFunction(previousStencilFunction);
  92094. engine.setStencilMask(previousStencilMask);
  92095. engine.setStencilBuffer(previousStencilBuffer);
  92096. engine.setStencilOperationPass(previousStencilOperationPass);
  92097. engine.setStencilOperationFail(previousStencilOperationFail);
  92098. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  92099. engine.setStencilFunctionReference(previousStencilReference);
  92100. };
  92101. /**
  92102. * Returns true if the layer contains information to display, otherwise false.
  92103. */
  92104. HighlightLayer.prototype.shouldRender = function () {
  92105. if (_super.prototype.shouldRender.call(this)) {
  92106. return this._meshes ? true : false;
  92107. }
  92108. return false;
  92109. };
  92110. /**
  92111. * Returns true if the mesh should render, otherwise false.
  92112. * @param mesh The mesh to render
  92113. * @returns true if it should render otherwise false
  92114. */
  92115. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  92116. // Excluded Mesh
  92117. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  92118. return false;
  92119. }
  92120. ;
  92121. return true;
  92122. };
  92123. /**
  92124. * Sets the required values for both the emissive texture and and the main color.
  92125. */
  92126. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92127. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  92128. if (highlightLayerMesh) {
  92129. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  92130. }
  92131. else {
  92132. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92133. }
  92134. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  92135. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92136. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  92137. }
  92138. else {
  92139. this._emissiveTextureAndColor.texture = null;
  92140. }
  92141. };
  92142. /**
  92143. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  92144. * @param mesh The mesh to exclude from the highlight layer
  92145. */
  92146. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  92147. if (!this._excludedMeshes) {
  92148. return;
  92149. }
  92150. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92151. if (!meshExcluded) {
  92152. this._excludedMeshes[mesh.uniqueId] = {
  92153. mesh: mesh,
  92154. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  92155. mesh.getEngine().setStencilBuffer(false);
  92156. }),
  92157. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  92158. mesh.getEngine().setStencilBuffer(true);
  92159. }),
  92160. };
  92161. }
  92162. };
  92163. /**
  92164. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  92165. * @param mesh The mesh to highlight
  92166. */
  92167. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  92168. if (!this._excludedMeshes) {
  92169. return;
  92170. }
  92171. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  92172. if (meshExcluded) {
  92173. if (meshExcluded.beforeRender) {
  92174. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  92175. }
  92176. if (meshExcluded.afterRender) {
  92177. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  92178. }
  92179. }
  92180. this._excludedMeshes[mesh.uniqueId] = null;
  92181. };
  92182. /**
  92183. * Determine if a given mesh will be highlighted by the current HighlightLayer
  92184. * @param mesh mesh to test
  92185. * @returns true if the mesh will be highlighted by the current HighlightLayer
  92186. */
  92187. HighlightLayer.prototype.hasMesh = function (mesh) {
  92188. if (!this._meshes) {
  92189. return false;
  92190. }
  92191. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  92192. };
  92193. /**
  92194. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  92195. * @param mesh The mesh to highlight
  92196. * @param color The color of the highlight
  92197. * @param glowEmissiveOnly Extract the glow from the emissive texture
  92198. */
  92199. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  92200. var _this = this;
  92201. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  92202. if (!this._meshes) {
  92203. return;
  92204. }
  92205. var meshHighlight = this._meshes[mesh.uniqueId];
  92206. if (meshHighlight) {
  92207. meshHighlight.color = color;
  92208. }
  92209. else {
  92210. this._meshes[mesh.uniqueId] = {
  92211. mesh: mesh,
  92212. color: color,
  92213. // Lambda required for capture due to Observable this context
  92214. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  92215. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  92216. _this._defaultStencilReference(mesh);
  92217. }
  92218. else {
  92219. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  92220. }
  92221. }),
  92222. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  92223. glowEmissiveOnly: glowEmissiveOnly
  92224. };
  92225. }
  92226. this._shouldRender = true;
  92227. };
  92228. /**
  92229. * Remove a mesh from the highlight layer in order to make it stop glowing.
  92230. * @param mesh The mesh to highlight
  92231. */
  92232. HighlightLayer.prototype.removeMesh = function (mesh) {
  92233. if (!this._meshes) {
  92234. return;
  92235. }
  92236. var meshHighlight = this._meshes[mesh.uniqueId];
  92237. if (meshHighlight) {
  92238. if (meshHighlight.observerHighlight) {
  92239. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92240. }
  92241. if (meshHighlight.observerDefault) {
  92242. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92243. }
  92244. delete this._meshes[mesh.uniqueId];
  92245. }
  92246. this._shouldRender = false;
  92247. for (var meshHighlightToCheck in this._meshes) {
  92248. if (this._meshes[meshHighlightToCheck]) {
  92249. this._shouldRender = true;
  92250. break;
  92251. }
  92252. }
  92253. };
  92254. /**
  92255. * Force the stencil to the normal expected value for none glowing parts
  92256. */
  92257. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  92258. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  92259. };
  92260. /**
  92261. * Free any resources and references associated to a mesh.
  92262. * Internal use
  92263. * @param mesh The mesh to free.
  92264. */
  92265. HighlightLayer.prototype._disposeMesh = function (mesh) {
  92266. this.removeMesh(mesh);
  92267. this.removeExcludedMesh(mesh);
  92268. };
  92269. /**
  92270. * Dispose the highlight layer and free resources.
  92271. */
  92272. HighlightLayer.prototype.dispose = function () {
  92273. if (this._meshes) {
  92274. // Clean mesh references
  92275. for (var id in this._meshes) {
  92276. var meshHighlight = this._meshes[id];
  92277. if (meshHighlight && meshHighlight.mesh) {
  92278. if (meshHighlight.observerHighlight) {
  92279. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  92280. }
  92281. if (meshHighlight.observerDefault) {
  92282. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  92283. }
  92284. }
  92285. }
  92286. this._meshes = null;
  92287. }
  92288. if (this._excludedMeshes) {
  92289. for (var id in this._excludedMeshes) {
  92290. var meshHighlight = this._excludedMeshes[id];
  92291. if (meshHighlight) {
  92292. if (meshHighlight.beforeRender) {
  92293. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  92294. }
  92295. if (meshHighlight.afterRender) {
  92296. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  92297. }
  92298. }
  92299. }
  92300. this._excludedMeshes = null;
  92301. }
  92302. _super.prototype.dispose.call(this);
  92303. };
  92304. /**
  92305. * Gets the class name of the effect layer
  92306. * @returns the string with the class name of the effect layer
  92307. */
  92308. HighlightLayer.prototype.getClassName = function () {
  92309. return "HighlightLayer";
  92310. };
  92311. /**
  92312. * Serializes this Highlight layer
  92313. * @returns a serialized Highlight layer object
  92314. */
  92315. HighlightLayer.prototype.serialize = function () {
  92316. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92317. serializationObject.customType = "BABYLON.HighlightLayer";
  92318. // Highlighted meshes
  92319. serializationObject.meshes = [];
  92320. if (this._meshes) {
  92321. for (var m in this._meshes) {
  92322. var mesh = this._meshes[m];
  92323. if (mesh) {
  92324. serializationObject.meshes.push({
  92325. glowEmissiveOnly: mesh.glowEmissiveOnly,
  92326. color: mesh.color.asArray(),
  92327. meshId: mesh.mesh.id
  92328. });
  92329. }
  92330. }
  92331. }
  92332. // Excluded meshes
  92333. serializationObject.excludedMeshes = [];
  92334. if (this._excludedMeshes) {
  92335. for (var e in this._excludedMeshes) {
  92336. var excludedMesh = this._excludedMeshes[e];
  92337. if (excludedMesh) {
  92338. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  92339. }
  92340. }
  92341. }
  92342. return serializationObject;
  92343. };
  92344. /**
  92345. * Creates a Highlight layer from parsed Highlight layer data
  92346. * @param parsedHightlightLayer defines the Highlight layer data
  92347. * @param scene defines the current scene
  92348. * @param rootUrl defines the root URL containing the Highlight layer information
  92349. * @returns a parsed Highlight layer
  92350. */
  92351. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  92352. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  92353. var index;
  92354. // Excluded meshes
  92355. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  92356. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  92357. if (mesh) {
  92358. hl.addExcludedMesh(mesh);
  92359. }
  92360. }
  92361. // Included meshes
  92362. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  92363. var highlightedMesh = parsedHightlightLayer.meshes[index];
  92364. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  92365. if (mesh) {
  92366. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  92367. }
  92368. }
  92369. return hl;
  92370. };
  92371. /**
  92372. * Effect Name of the highlight layer.
  92373. */
  92374. HighlightLayer.EffectName = "HighlightLayer";
  92375. /**
  92376. * The neutral color used during the preparation of the glow effect.
  92377. * This is black by default as the blend operation is a blend operation.
  92378. */
  92379. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  92380. /**
  92381. * Stencil value used for glowing meshes.
  92382. */
  92383. HighlightLayer.GlowingMeshStencilReference = 0x02;
  92384. /**
  92385. * Stencil value used for the other meshes in the scene.
  92386. */
  92387. HighlightLayer.NormalMeshStencilReference = 0x01;
  92388. __decorate([
  92389. BABYLON.serialize()
  92390. ], HighlightLayer.prototype, "innerGlow", void 0);
  92391. __decorate([
  92392. BABYLON.serialize()
  92393. ], HighlightLayer.prototype, "outerGlow", void 0);
  92394. __decorate([
  92395. BABYLON.serialize()
  92396. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  92397. __decorate([
  92398. BABYLON.serialize()
  92399. ], HighlightLayer.prototype, "blurVerticalSize", null);
  92400. __decorate([
  92401. BABYLON.serialize("options")
  92402. ], HighlightLayer.prototype, "_options", void 0);
  92403. return HighlightLayer;
  92404. }(BABYLON.EffectLayer));
  92405. BABYLON.HighlightLayer = HighlightLayer;
  92406. })(BABYLON || (BABYLON = {}));
  92407. //# sourceMappingURL=babylon.highlightLayer.js.map
  92408. var BABYLON;
  92409. (function (BABYLON) {
  92410. /**
  92411. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  92412. *
  92413. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  92414. * glowy meshes to your scene.
  92415. *
  92416. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  92417. */
  92418. var GlowLayer = /** @class */ (function (_super) {
  92419. __extends(GlowLayer, _super);
  92420. /**
  92421. * Instantiates a new glow Layer and references it to the scene.
  92422. * @param name The name of the layer
  92423. * @param scene The scene to use the layer in
  92424. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  92425. */
  92426. function GlowLayer(name, scene, options) {
  92427. var _this = _super.call(this, name, scene) || this;
  92428. _this._intensity = 1.0;
  92429. _this._includedOnlyMeshes = [];
  92430. _this._excludedMeshes = [];
  92431. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  92432. // Adapt options
  92433. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  92434. // Initialize the layer
  92435. _this._init({
  92436. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  92437. camera: _this._options.camera,
  92438. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  92439. mainTextureRatio: _this._options.mainTextureRatio
  92440. });
  92441. return _this;
  92442. }
  92443. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  92444. /**
  92445. * Gets the kernel size of the blur.
  92446. */
  92447. get: function () {
  92448. return this._horizontalBlurPostprocess1.kernel;
  92449. },
  92450. /**
  92451. * Sets the kernel size of the blur.
  92452. */
  92453. set: function (value) {
  92454. this._horizontalBlurPostprocess1.kernel = value;
  92455. this._verticalBlurPostprocess1.kernel = value;
  92456. this._horizontalBlurPostprocess2.kernel = value;
  92457. this._verticalBlurPostprocess2.kernel = value;
  92458. },
  92459. enumerable: true,
  92460. configurable: true
  92461. });
  92462. Object.defineProperty(GlowLayer.prototype, "intensity", {
  92463. /**
  92464. * Gets the glow intensity.
  92465. */
  92466. get: function () {
  92467. return this._intensity;
  92468. },
  92469. /**
  92470. * Sets the glow intensity.
  92471. */
  92472. set: function (value) {
  92473. this._intensity = value;
  92474. },
  92475. enumerable: true,
  92476. configurable: true
  92477. });
  92478. /**
  92479. * Get the effect name of the layer.
  92480. * @return The effect name
  92481. */
  92482. GlowLayer.prototype.getEffectName = function () {
  92483. return GlowLayer.EffectName;
  92484. };
  92485. /**
  92486. * Create the merge effect. This is the shader use to blit the information back
  92487. * to the main canvas at the end of the scene rendering.
  92488. */
  92489. GlowLayer.prototype._createMergeEffect = function () {
  92490. // Effect
  92491. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  92492. };
  92493. /**
  92494. * Creates the render target textures and post processes used in the glow layer.
  92495. */
  92496. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  92497. var _this = this;
  92498. var blurTextureWidth = this._mainTextureDesiredSize.width;
  92499. var blurTextureHeight = this._mainTextureDesiredSize.height;
  92500. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  92501. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  92502. var textureType = 0;
  92503. if (this._engine.getCaps().textureHalfFloatRender) {
  92504. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  92505. }
  92506. else {
  92507. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  92508. }
  92509. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  92510. width: blurTextureWidth,
  92511. height: blurTextureHeight
  92512. }, this._scene, false, true, textureType);
  92513. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92514. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92515. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92516. this._blurTexture1.renderParticles = false;
  92517. this._blurTexture1.ignoreCameraViewport = true;
  92518. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  92519. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  92520. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  92521. width: blurTextureWidth2,
  92522. height: blurTextureHeight2
  92523. }, this._scene, false, true, textureType);
  92524. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92525. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  92526. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  92527. this._blurTexture2.renderParticles = false;
  92528. this._blurTexture2.ignoreCameraViewport = true;
  92529. this._textures = [this._blurTexture1, this._blurTexture2];
  92530. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92531. width: blurTextureWidth,
  92532. height: blurTextureHeight
  92533. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92534. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  92535. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  92536. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  92537. effect.setTexture("textureSampler", _this._mainTexture);
  92538. });
  92539. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92540. width: blurTextureWidth,
  92541. height: blurTextureHeight
  92542. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92543. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  92544. width: blurTextureWidth2,
  92545. height: blurTextureHeight2
  92546. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92547. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  92548. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  92549. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  92550. effect.setTexture("textureSampler", _this._blurTexture1);
  92551. });
  92552. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  92553. width: blurTextureWidth2,
  92554. height: blurTextureHeight2
  92555. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  92556. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92557. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  92558. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  92559. this._mainTexture.samples = this._options.mainTextureSamples;
  92560. this._mainTexture.onAfterUnbindObservable.add(function () {
  92561. var internalTexture = _this._blurTexture1.getInternalTexture();
  92562. if (internalTexture) {
  92563. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  92564. internalTexture = _this._blurTexture2.getInternalTexture();
  92565. if (internalTexture) {
  92566. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  92567. }
  92568. }
  92569. });
  92570. // Prevent autoClear.
  92571. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  92572. };
  92573. /**
  92574. * Checks for the readiness of the element composing the layer.
  92575. * @param subMesh the mesh to check for
  92576. * @param useInstances specify wether or not to use instances to render the mesh
  92577. * @param emissiveTexture the associated emissive texture used to generate the glow
  92578. * @return true if ready otherwise, false
  92579. */
  92580. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  92581. var material = subMesh.getMaterial();
  92582. var mesh = subMesh.getRenderingMesh();
  92583. if (!material || !mesh) {
  92584. return false;
  92585. }
  92586. var emissiveTexture = material.emissiveTexture;
  92587. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  92588. };
  92589. /**
  92590. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  92591. */
  92592. GlowLayer.prototype.needStencil = function () {
  92593. return false;
  92594. };
  92595. /**
  92596. * Implementation specific of rendering the generating effect on the main canvas.
  92597. * @param effect The effect used to render through
  92598. */
  92599. GlowLayer.prototype._internalRender = function (effect) {
  92600. // Texture
  92601. effect.setTexture("textureSampler", this._blurTexture1);
  92602. effect.setTexture("textureSampler2", this._blurTexture2);
  92603. effect.setFloat("offset", this._intensity);
  92604. // Cache
  92605. var engine = this._engine;
  92606. var previousStencilBuffer = engine.getStencilBuffer();
  92607. // Draw order
  92608. engine.setStencilBuffer(false);
  92609. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  92610. // Draw order
  92611. engine.setStencilBuffer(previousStencilBuffer);
  92612. };
  92613. /**
  92614. * Sets the required values for both the emissive texture and and the main color.
  92615. */
  92616. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  92617. var textureLevel = 1.0;
  92618. if (this.customEmissiveTextureSelector) {
  92619. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  92620. }
  92621. else {
  92622. if (material) {
  92623. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  92624. if (this._emissiveTextureAndColor.texture) {
  92625. textureLevel = this._emissiveTextureAndColor.texture.level;
  92626. }
  92627. }
  92628. else {
  92629. this._emissiveTextureAndColor.texture = null;
  92630. }
  92631. }
  92632. if (this.customEmissiveColorSelector) {
  92633. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  92634. }
  92635. else {
  92636. if (material.emissiveColor) {
  92637. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  92638. }
  92639. else {
  92640. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  92641. }
  92642. }
  92643. };
  92644. /**
  92645. * Returns true if the mesh should render, otherwise false.
  92646. * @param mesh The mesh to render
  92647. * @returns true if it should render otherwise false
  92648. */
  92649. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  92650. return this.hasMesh(mesh);
  92651. };
  92652. /**
  92653. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  92654. * @param mesh The mesh to exclude from the glow layer
  92655. */
  92656. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  92657. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  92658. this._excludedMeshes.push(mesh.uniqueId);
  92659. }
  92660. };
  92661. /**
  92662. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  92663. * @param mesh The mesh to remove
  92664. */
  92665. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  92666. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  92667. if (index !== -1) {
  92668. this._excludedMeshes.splice(index, 1);
  92669. }
  92670. };
  92671. /**
  92672. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  92673. * @param mesh The mesh to include in the glow layer
  92674. */
  92675. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  92676. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  92677. this._includedOnlyMeshes.push(mesh.uniqueId);
  92678. }
  92679. };
  92680. /**
  92681. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  92682. * @param mesh The mesh to remove
  92683. */
  92684. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  92685. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  92686. if (index !== -1) {
  92687. this._includedOnlyMeshes.splice(index, 1);
  92688. }
  92689. };
  92690. /**
  92691. * Determine if a given mesh will be used in the glow layer
  92692. * @param mesh The mesh to test
  92693. * @returns true if the mesh will be highlighted by the current glow layer
  92694. */
  92695. GlowLayer.prototype.hasMesh = function (mesh) {
  92696. // Included Mesh
  92697. if (this._includedOnlyMeshes.length) {
  92698. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  92699. }
  92700. ;
  92701. // Excluded Mesh
  92702. if (this._excludedMeshes.length) {
  92703. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  92704. }
  92705. ;
  92706. return true;
  92707. };
  92708. /**
  92709. * Free any resources and references associated to a mesh.
  92710. * Internal use
  92711. * @param mesh The mesh to free.
  92712. */
  92713. GlowLayer.prototype._disposeMesh = function (mesh) {
  92714. this.removeIncludedOnlyMesh(mesh);
  92715. this.removeExcludedMesh(mesh);
  92716. };
  92717. /**
  92718. * Gets the class name of the effect layer
  92719. * @returns the string with the class name of the effect layer
  92720. */
  92721. GlowLayer.prototype.getClassName = function () {
  92722. return "GlowLayer";
  92723. };
  92724. /**
  92725. * Serializes this glow layer
  92726. * @returns a serialized glow layer object
  92727. */
  92728. GlowLayer.prototype.serialize = function () {
  92729. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  92730. serializationObject.customType = "BABYLON.GlowLayer";
  92731. var index;
  92732. // Included meshes
  92733. serializationObject.includedMeshes = [];
  92734. if (this._includedOnlyMeshes.length) {
  92735. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  92736. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  92737. if (mesh) {
  92738. serializationObject.includedMeshes.push(mesh.id);
  92739. }
  92740. }
  92741. }
  92742. // Excluded meshes
  92743. serializationObject.excludedMeshes = [];
  92744. if (this._excludedMeshes.length) {
  92745. for (index = 0; index < this._excludedMeshes.length; index++) {
  92746. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  92747. if (mesh) {
  92748. serializationObject.excludedMeshes.push(mesh.id);
  92749. }
  92750. }
  92751. }
  92752. return serializationObject;
  92753. };
  92754. /**
  92755. * Creates a Glow Layer from parsed glow layer data
  92756. * @param parsedGlowLayer defines glow layer data
  92757. * @param scene defines the current scene
  92758. * @param rootUrl defines the root URL containing the glow layer information
  92759. * @returns a parsed Glow Layer
  92760. */
  92761. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  92762. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  92763. var index;
  92764. // Excluded meshes
  92765. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  92766. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  92767. if (mesh) {
  92768. gl.addExcludedMesh(mesh);
  92769. }
  92770. }
  92771. // Included meshes
  92772. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  92773. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  92774. if (mesh) {
  92775. gl.addIncludedOnlyMesh(mesh);
  92776. }
  92777. }
  92778. return gl;
  92779. };
  92780. /**
  92781. * Effect Name of the layer.
  92782. */
  92783. GlowLayer.EffectName = "GlowLayer";
  92784. /**
  92785. * The default blur kernel size used for the glow.
  92786. */
  92787. GlowLayer.DefaultBlurKernelSize = 32;
  92788. /**
  92789. * The default texture size ratio used for the glow.
  92790. */
  92791. GlowLayer.DefaultTextureRatio = 0.5;
  92792. __decorate([
  92793. BABYLON.serialize()
  92794. ], GlowLayer.prototype, "blurKernelSize", null);
  92795. __decorate([
  92796. BABYLON.serialize()
  92797. ], GlowLayer.prototype, "intensity", null);
  92798. __decorate([
  92799. BABYLON.serialize("options")
  92800. ], GlowLayer.prototype, "_options", void 0);
  92801. return GlowLayer;
  92802. }(BABYLON.EffectLayer));
  92803. BABYLON.GlowLayer = GlowLayer;
  92804. })(BABYLON || (BABYLON = {}));
  92805. //# sourceMappingURL=babylon.glowLayer.js.map
  92806. var BABYLON;
  92807. (function (BABYLON) {
  92808. /**
  92809. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  92810. */
  92811. var AssetTaskState;
  92812. (function (AssetTaskState) {
  92813. /**
  92814. * Initialization
  92815. */
  92816. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  92817. /**
  92818. * Running
  92819. */
  92820. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  92821. /**
  92822. * Done
  92823. */
  92824. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  92825. /**
  92826. * Error
  92827. */
  92828. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  92829. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  92830. /**
  92831. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  92832. */
  92833. var AbstractAssetTask = /** @class */ (function () {
  92834. /**
  92835. * Creates a new {BABYLON.AssetsManager}
  92836. * @param name defines the name of the task
  92837. */
  92838. function AbstractAssetTask(
  92839. /**
  92840. * Task name
  92841. */ name) {
  92842. this.name = name;
  92843. this._isCompleted = false;
  92844. this._taskState = AssetTaskState.INIT;
  92845. }
  92846. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  92847. /**
  92848. * Get if the task is completed
  92849. */
  92850. get: function () {
  92851. return this._isCompleted;
  92852. },
  92853. enumerable: true,
  92854. configurable: true
  92855. });
  92856. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  92857. /**
  92858. * Gets the current state of the task
  92859. */
  92860. get: function () {
  92861. return this._taskState;
  92862. },
  92863. enumerable: true,
  92864. configurable: true
  92865. });
  92866. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  92867. /**
  92868. * Gets the current error object (if task is in error)
  92869. */
  92870. get: function () {
  92871. return this._errorObject;
  92872. },
  92873. enumerable: true,
  92874. configurable: true
  92875. });
  92876. /**
  92877. * Internal only
  92878. * @hidden
  92879. */
  92880. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  92881. if (this._errorObject) {
  92882. return;
  92883. }
  92884. this._errorObject = {
  92885. message: message,
  92886. exception: exception
  92887. };
  92888. };
  92889. /**
  92890. * Execute the current task
  92891. * @param scene defines the scene where you want your assets to be loaded
  92892. * @param onSuccess is a callback called when the task is successfully executed
  92893. * @param onError is a callback called if an error occurs
  92894. */
  92895. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  92896. var _this = this;
  92897. this._taskState = AssetTaskState.RUNNING;
  92898. this.runTask(scene, function () {
  92899. _this.onDoneCallback(onSuccess, onError);
  92900. }, function (msg, exception) {
  92901. _this.onErrorCallback(onError, msg, exception);
  92902. });
  92903. };
  92904. /**
  92905. * Execute the current task
  92906. * @param scene defines the scene where you want your assets to be loaded
  92907. * @param onSuccess is a callback called when the task is successfully executed
  92908. * @param onError is a callback called if an error occurs
  92909. */
  92910. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  92911. throw new Error("runTask is not implemented");
  92912. };
  92913. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  92914. this._taskState = AssetTaskState.ERROR;
  92915. this._errorObject = {
  92916. message: message,
  92917. exception: exception
  92918. };
  92919. if (this.onError) {
  92920. this.onError(this, message, exception);
  92921. }
  92922. onError();
  92923. };
  92924. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  92925. try {
  92926. this._taskState = AssetTaskState.DONE;
  92927. this._isCompleted = true;
  92928. if (this.onSuccess) {
  92929. this.onSuccess(this);
  92930. }
  92931. onSuccess();
  92932. }
  92933. catch (e) {
  92934. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  92935. }
  92936. };
  92937. return AbstractAssetTask;
  92938. }());
  92939. BABYLON.AbstractAssetTask = AbstractAssetTask;
  92940. /**
  92941. * Class used to share progress information about assets loading
  92942. */
  92943. var AssetsProgressEvent = /** @class */ (function () {
  92944. /**
  92945. * Creates a {BABYLON.AssetsProgressEvent}
  92946. * @param remainingCount defines the number of remaining tasks to process
  92947. * @param totalCount defines the total number of tasks
  92948. * @param task defines the task that was just processed
  92949. */
  92950. function AssetsProgressEvent(remainingCount, totalCount, task) {
  92951. this.remainingCount = remainingCount;
  92952. this.totalCount = totalCount;
  92953. this.task = task;
  92954. }
  92955. return AssetsProgressEvent;
  92956. }());
  92957. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  92958. /**
  92959. * Define a task used by {BABYLON.AssetsManager} to load meshes
  92960. */
  92961. var MeshAssetTask = /** @class */ (function (_super) {
  92962. __extends(MeshAssetTask, _super);
  92963. /**
  92964. * Creates a new {BABYLON.MeshAssetTask}
  92965. * @param name defines the name of the task
  92966. * @param meshesNames defines the list of mesh's names you want to load
  92967. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  92968. * @param sceneFilename defines the filename of the scene to load from
  92969. */
  92970. function MeshAssetTask(
  92971. /**
  92972. * Defines the name of the task
  92973. */
  92974. name,
  92975. /**
  92976. * Defines the list of mesh's names you want to load
  92977. */
  92978. meshesNames,
  92979. /**
  92980. * Defines the root url to use as a base to load your meshes and associated resources
  92981. */
  92982. rootUrl,
  92983. /**
  92984. * Defines the filename of the scene to load from
  92985. */
  92986. sceneFilename) {
  92987. var _this = _super.call(this, name) || this;
  92988. _this.name = name;
  92989. _this.meshesNames = meshesNames;
  92990. _this.rootUrl = rootUrl;
  92991. _this.sceneFilename = sceneFilename;
  92992. return _this;
  92993. }
  92994. /**
  92995. * Execute the current task
  92996. * @param scene defines the scene where you want your assets to be loaded
  92997. * @param onSuccess is a callback called when the task is successfully executed
  92998. * @param onError is a callback called if an error occurs
  92999. */
  93000. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93001. var _this = this;
  93002. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  93003. _this.loadedMeshes = meshes;
  93004. _this.loadedParticleSystems = particleSystems;
  93005. _this.loadedSkeletons = skeletons;
  93006. onSuccess();
  93007. }, null, function (scene, message, exception) {
  93008. onError(message, exception);
  93009. });
  93010. };
  93011. return MeshAssetTask;
  93012. }(AbstractAssetTask));
  93013. BABYLON.MeshAssetTask = MeshAssetTask;
  93014. /**
  93015. * Define a task used by {BABYLON.AssetsManager} to load text content
  93016. */
  93017. var TextFileAssetTask = /** @class */ (function (_super) {
  93018. __extends(TextFileAssetTask, _super);
  93019. /**
  93020. * Creates a new TextFileAssetTask object
  93021. * @param name defines the name of the task
  93022. * @param url defines the location of the file to load
  93023. */
  93024. function TextFileAssetTask(
  93025. /**
  93026. * Defines the name of the task
  93027. */
  93028. name,
  93029. /**
  93030. * Defines the location of the file to load
  93031. */
  93032. url) {
  93033. var _this = _super.call(this, name) || this;
  93034. _this.name = name;
  93035. _this.url = url;
  93036. return _this;
  93037. }
  93038. /**
  93039. * Execute the current task
  93040. * @param scene defines the scene where you want your assets to be loaded
  93041. * @param onSuccess is a callback called when the task is successfully executed
  93042. * @param onError is a callback called if an error occurs
  93043. */
  93044. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93045. var _this = this;
  93046. scene._loadFile(this.url, function (data) {
  93047. _this.text = data;
  93048. onSuccess();
  93049. }, undefined, false, false, function (request, exception) {
  93050. if (request) {
  93051. onError(request.status + " " + request.statusText, exception);
  93052. }
  93053. });
  93054. };
  93055. return TextFileAssetTask;
  93056. }(AbstractAssetTask));
  93057. BABYLON.TextFileAssetTask = TextFileAssetTask;
  93058. /**
  93059. * Define a task used by {BABYLON.AssetsManager} to load binary data
  93060. */
  93061. var BinaryFileAssetTask = /** @class */ (function (_super) {
  93062. __extends(BinaryFileAssetTask, _super);
  93063. /**
  93064. * Creates a new BinaryFileAssetTask object
  93065. * @param name defines the name of the new task
  93066. * @param url defines the location of the file to load
  93067. */
  93068. function BinaryFileAssetTask(
  93069. /**
  93070. * Defines the name of the task
  93071. */
  93072. name,
  93073. /**
  93074. * Defines the location of the file to load
  93075. */
  93076. url) {
  93077. var _this = _super.call(this, name) || this;
  93078. _this.name = name;
  93079. _this.url = url;
  93080. return _this;
  93081. }
  93082. /**
  93083. * Execute the current task
  93084. * @param scene defines the scene where you want your assets to be loaded
  93085. * @param onSuccess is a callback called when the task is successfully executed
  93086. * @param onError is a callback called if an error occurs
  93087. */
  93088. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93089. var _this = this;
  93090. scene._loadFile(this.url, function (data) {
  93091. _this.data = data;
  93092. onSuccess();
  93093. }, undefined, true, true, function (request, exception) {
  93094. if (request) {
  93095. onError(request.status + " " + request.statusText, exception);
  93096. }
  93097. });
  93098. };
  93099. return BinaryFileAssetTask;
  93100. }(AbstractAssetTask));
  93101. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  93102. /**
  93103. * Define a task used by {BABYLON.AssetsManager} to load images
  93104. */
  93105. var ImageAssetTask = /** @class */ (function (_super) {
  93106. __extends(ImageAssetTask, _super);
  93107. /**
  93108. * Creates a new ImageAssetTask
  93109. * @param name defines the name of the task
  93110. * @param url defines the location of the image to load
  93111. */
  93112. function ImageAssetTask(
  93113. /**
  93114. * Defines the name of the task
  93115. */
  93116. name,
  93117. /**
  93118. * Defines the location of the image to load
  93119. */
  93120. url) {
  93121. var _this = _super.call(this, name) || this;
  93122. _this.name = name;
  93123. _this.url = url;
  93124. return _this;
  93125. }
  93126. /**
  93127. * Execute the current task
  93128. * @param scene defines the scene where you want your assets to be loaded
  93129. * @param onSuccess is a callback called when the task is successfully executed
  93130. * @param onError is a callback called if an error occurs
  93131. */
  93132. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93133. var _this = this;
  93134. var img = new Image();
  93135. BABYLON.Tools.SetCorsBehavior(this.url, img);
  93136. img.onload = function () {
  93137. _this.image = img;
  93138. onSuccess();
  93139. };
  93140. img.onerror = function (err) {
  93141. onError("Error loading image", err);
  93142. };
  93143. img.src = this.url;
  93144. };
  93145. return ImageAssetTask;
  93146. }(AbstractAssetTask));
  93147. BABYLON.ImageAssetTask = ImageAssetTask;
  93148. /**
  93149. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  93150. */
  93151. var TextureAssetTask = /** @class */ (function (_super) {
  93152. __extends(TextureAssetTask, _super);
  93153. /**
  93154. * Creates a new TextureAssetTask object
  93155. * @param name defines the name of the task
  93156. * @param url defines the location of the file to load
  93157. * @param noMipmap defines if mipmap should not be generated (default is false)
  93158. * @param invertY defines if texture must be inverted on Y axis (default is false)
  93159. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93160. */
  93161. function TextureAssetTask(
  93162. /**
  93163. * Defines the name of the task
  93164. */
  93165. name,
  93166. /**
  93167. * Defines the location of the file to load
  93168. */
  93169. url,
  93170. /**
  93171. * Defines if mipmap should not be generated (default is false)
  93172. */
  93173. noMipmap,
  93174. /**
  93175. * Defines if texture must be inverted on Y axis (default is false)
  93176. */
  93177. invertY,
  93178. /**
  93179. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  93180. */
  93181. samplingMode) {
  93182. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93183. var _this = _super.call(this, name) || this;
  93184. _this.name = name;
  93185. _this.url = url;
  93186. _this.noMipmap = noMipmap;
  93187. _this.invertY = invertY;
  93188. _this.samplingMode = samplingMode;
  93189. return _this;
  93190. }
  93191. /**
  93192. * Execute the current task
  93193. * @param scene defines the scene where you want your assets to be loaded
  93194. * @param onSuccess is a callback called when the task is successfully executed
  93195. * @param onError is a callback called if an error occurs
  93196. */
  93197. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93198. var onload = function () {
  93199. onSuccess();
  93200. };
  93201. var onerror = function (message, exception) {
  93202. onError(message, exception);
  93203. };
  93204. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  93205. };
  93206. return TextureAssetTask;
  93207. }(AbstractAssetTask));
  93208. BABYLON.TextureAssetTask = TextureAssetTask;
  93209. /**
  93210. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  93211. */
  93212. var CubeTextureAssetTask = /** @class */ (function (_super) {
  93213. __extends(CubeTextureAssetTask, _super);
  93214. /**
  93215. * Creates a new CubeTextureAssetTask
  93216. * @param name defines the name of the task
  93217. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93218. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93219. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93220. * @param files defines the explicit list of files (undefined by default)
  93221. */
  93222. function CubeTextureAssetTask(
  93223. /**
  93224. * Defines the name of the task
  93225. */
  93226. name,
  93227. /**
  93228. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  93229. */
  93230. url,
  93231. /**
  93232. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  93233. */
  93234. extensions,
  93235. /**
  93236. * Defines if mipmaps should not be generated (default is false)
  93237. */
  93238. noMipmap,
  93239. /**
  93240. * Defines the explicit list of files (undefined by default)
  93241. */
  93242. files) {
  93243. var _this = _super.call(this, name) || this;
  93244. _this.name = name;
  93245. _this.url = url;
  93246. _this.extensions = extensions;
  93247. _this.noMipmap = noMipmap;
  93248. _this.files = files;
  93249. return _this;
  93250. }
  93251. /**
  93252. * Execute the current task
  93253. * @param scene defines the scene where you want your assets to be loaded
  93254. * @param onSuccess is a callback called when the task is successfully executed
  93255. * @param onError is a callback called if an error occurs
  93256. */
  93257. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  93258. var onload = function () {
  93259. onSuccess();
  93260. };
  93261. var onerror = function (message, exception) {
  93262. onError(message, exception);
  93263. };
  93264. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  93265. };
  93266. return CubeTextureAssetTask;
  93267. }(AbstractAssetTask));
  93268. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  93269. /**
  93270. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  93271. */
  93272. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  93273. __extends(HDRCubeTextureAssetTask, _super);
  93274. /**
  93275. * Creates a new HDRCubeTextureAssetTask object
  93276. * @param name defines the name of the task
  93277. * @param url defines the location of the file to load
  93278. * @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.
  93279. * @param noMipmap defines if mipmaps should not be generated (default is false)
  93280. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93281. * @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)
  93282. * @param reserved Internal use only
  93283. */
  93284. function HDRCubeTextureAssetTask(
  93285. /**
  93286. * Defines the name of the task
  93287. */
  93288. name,
  93289. /**
  93290. * Defines the location of the file to load
  93291. */
  93292. url,
  93293. /**
  93294. * Defines the desired size (the more it increases the longer the generation will be)
  93295. */
  93296. size,
  93297. /**
  93298. * Defines if mipmaps should not be generated (default is false)
  93299. */
  93300. noMipmap,
  93301. /**
  93302. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  93303. */
  93304. generateHarmonics,
  93305. /**
  93306. * 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)
  93307. */
  93308. gammaSpace,
  93309. /**
  93310. * Internal Use Only
  93311. */
  93312. reserved) {
  93313. if (noMipmap === void 0) { noMipmap = false; }
  93314. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93315. if (gammaSpace === void 0) { gammaSpace = false; }
  93316. if (reserved === void 0) { reserved = false; }
  93317. var _this = _super.call(this, name) || this;
  93318. _this.name = name;
  93319. _this.url = url;
  93320. _this.size = size;
  93321. _this.noMipmap = noMipmap;
  93322. _this.generateHarmonics = generateHarmonics;
  93323. _this.gammaSpace = gammaSpace;
  93324. _this.reserved = reserved;
  93325. return _this;
  93326. }
  93327. /**
  93328. * Execute the current task
  93329. * @param scene defines the scene where you want your assets to be loaded
  93330. * @param onSuccess is a callback called when the task is successfully executed
  93331. * @param onError is a callback called if an error occurs
  93332. */
  93333. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  93334. var onload = function () {
  93335. onSuccess();
  93336. };
  93337. var onerror = function (message, exception) {
  93338. onError(message, exception);
  93339. };
  93340. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  93341. };
  93342. return HDRCubeTextureAssetTask;
  93343. }(AbstractAssetTask));
  93344. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  93345. /**
  93346. * This class can be used to easily import assets into a scene
  93347. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  93348. */
  93349. var AssetsManager = /** @class */ (function () {
  93350. /**
  93351. * Creates a new AssetsManager
  93352. * @param scene defines the scene to work on
  93353. */
  93354. function AssetsManager(scene) {
  93355. this._isLoading = false;
  93356. this._tasks = new Array();
  93357. this._waitingTasksCount = 0;
  93358. this._totalTasksCount = 0;
  93359. /**
  93360. * Observable called when all tasks are processed
  93361. */
  93362. this.onTaskSuccessObservable = new BABYLON.Observable();
  93363. /**
  93364. * Observable called when a task had an error
  93365. */
  93366. this.onTaskErrorObservable = new BABYLON.Observable();
  93367. /**
  93368. * Observable called when a task is successful
  93369. */
  93370. this.onTasksDoneObservable = new BABYLON.Observable();
  93371. /**
  93372. * Observable called when a task is done (whatever the result is)
  93373. */
  93374. this.onProgressObservable = new BABYLON.Observable();
  93375. /**
  93376. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  93377. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  93378. */
  93379. this.useDefaultLoadingScreen = true;
  93380. this._scene = scene;
  93381. }
  93382. /**
  93383. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  93384. * @param taskName defines the name of the new task
  93385. * @param meshesNames defines the name of meshes to load
  93386. * @param rootUrl defines the root url to use to locate files
  93387. * @param sceneFilename defines the filename of the scene file
  93388. * @returns a new {BABYLON.MeshAssetTask} object
  93389. */
  93390. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  93391. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  93392. this._tasks.push(task);
  93393. return task;
  93394. };
  93395. /**
  93396. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  93397. * @param taskName defines the name of the new task
  93398. * @param url defines the url of the file to load
  93399. * @returns a new {BABYLON.TextFileAssetTask} object
  93400. */
  93401. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  93402. var task = new TextFileAssetTask(taskName, url);
  93403. this._tasks.push(task);
  93404. return task;
  93405. };
  93406. /**
  93407. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  93408. * @param taskName defines the name of the new task
  93409. * @param url defines the url of the file to load
  93410. * @returns a new {BABYLON.BinaryFileAssetTask} object
  93411. */
  93412. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  93413. var task = new BinaryFileAssetTask(taskName, url);
  93414. this._tasks.push(task);
  93415. return task;
  93416. };
  93417. /**
  93418. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  93419. * @param taskName defines the name of the new task
  93420. * @param url defines the url of the file to load
  93421. * @returns a new {BABYLON.ImageAssetTask} object
  93422. */
  93423. AssetsManager.prototype.addImageTask = function (taskName, url) {
  93424. var task = new ImageAssetTask(taskName, url);
  93425. this._tasks.push(task);
  93426. return task;
  93427. };
  93428. /**
  93429. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  93430. * @param taskName defines the name of the new task
  93431. * @param url defines the url of the file to load
  93432. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93433. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  93434. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  93435. * @returns a new {BABYLON.TextureAssetTask} object
  93436. */
  93437. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  93438. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  93439. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  93440. this._tasks.push(task);
  93441. return task;
  93442. };
  93443. /**
  93444. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  93445. * @param taskName defines the name of the new task
  93446. * @param url defines the url of the file to load
  93447. * @param extensions defines the extension to use to load the cube map (can be null)
  93448. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93449. * @param files defines the list of files to load (can be null)
  93450. * @returns a new {BABYLON.CubeTextureAssetTask} object
  93451. */
  93452. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  93453. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  93454. this._tasks.push(task);
  93455. return task;
  93456. };
  93457. /**
  93458. *
  93459. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  93460. * @param taskName defines the name of the new task
  93461. * @param url defines the url of the file to load
  93462. * @param size defines the size you want for the cubemap (can be null)
  93463. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  93464. * @param generateHarmonics defines if you want to automatically generate (true by default)
  93465. * @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)
  93466. * @param reserved Internal use only
  93467. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  93468. */
  93469. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  93470. if (noMipmap === void 0) { noMipmap = false; }
  93471. if (generateHarmonics === void 0) { generateHarmonics = true; }
  93472. if (gammaSpace === void 0) { gammaSpace = false; }
  93473. if (reserved === void 0) { reserved = false; }
  93474. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  93475. this._tasks.push(task);
  93476. return task;
  93477. };
  93478. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  93479. var _this = this;
  93480. this._waitingTasksCount--;
  93481. try {
  93482. if (task.taskState === AssetTaskState.DONE) {
  93483. // Let's remove successfull tasks
  93484. BABYLON.Tools.SetImmediate(function () {
  93485. var index = _this._tasks.indexOf(task);
  93486. if (index > -1) {
  93487. _this._tasks.splice(index, 1);
  93488. }
  93489. });
  93490. }
  93491. if (this.onProgress) {
  93492. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  93493. }
  93494. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  93495. }
  93496. catch (e) {
  93497. BABYLON.Tools.Error("Error running progress callbacks.");
  93498. console.log(e);
  93499. }
  93500. if (this._waitingTasksCount === 0) {
  93501. try {
  93502. if (this.onFinish) {
  93503. this.onFinish(this._tasks);
  93504. }
  93505. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93506. }
  93507. catch (e) {
  93508. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  93509. console.log(e);
  93510. }
  93511. this._isLoading = false;
  93512. this._scene.getEngine().hideLoadingUI();
  93513. }
  93514. };
  93515. AssetsManager.prototype._runTask = function (task) {
  93516. var _this = this;
  93517. var done = function () {
  93518. try {
  93519. if (_this.onTaskSuccess) {
  93520. _this.onTaskSuccess(task);
  93521. }
  93522. _this.onTaskSuccessObservable.notifyObservers(task);
  93523. _this._decreaseWaitingTasksCount(task);
  93524. }
  93525. catch (e) {
  93526. error("Error executing task success callbacks", e);
  93527. }
  93528. };
  93529. var error = function (message, exception) {
  93530. task._setErrorObject(message, exception);
  93531. if (_this.onTaskError) {
  93532. _this.onTaskError(task);
  93533. }
  93534. _this.onTaskErrorObservable.notifyObservers(task);
  93535. _this._decreaseWaitingTasksCount(task);
  93536. };
  93537. task.run(this._scene, done, error);
  93538. };
  93539. /**
  93540. * Reset the {BABYLON.AssetsManager} and remove all tasks
  93541. * @return the current instance of the {BABYLON.AssetsManager}
  93542. */
  93543. AssetsManager.prototype.reset = function () {
  93544. this._isLoading = false;
  93545. this._tasks = new Array();
  93546. return this;
  93547. };
  93548. /**
  93549. * Start the loading process
  93550. * @return the current instance of the {BABYLON.AssetsManager}
  93551. */
  93552. AssetsManager.prototype.load = function () {
  93553. if (this._isLoading) {
  93554. return this;
  93555. }
  93556. this._isLoading = true;
  93557. this._waitingTasksCount = this._tasks.length;
  93558. this._totalTasksCount = this._tasks.length;
  93559. if (this._waitingTasksCount === 0) {
  93560. this._isLoading = false;
  93561. if (this.onFinish) {
  93562. this.onFinish(this._tasks);
  93563. }
  93564. this.onTasksDoneObservable.notifyObservers(this._tasks);
  93565. return this;
  93566. }
  93567. if (this.useDefaultLoadingScreen) {
  93568. this._scene.getEngine().displayLoadingUI();
  93569. }
  93570. for (var index = 0; index < this._tasks.length; index++) {
  93571. var task = this._tasks[index];
  93572. this._runTask(task);
  93573. }
  93574. return this;
  93575. };
  93576. return AssetsManager;
  93577. }());
  93578. BABYLON.AssetsManager = AssetsManager;
  93579. })(BABYLON || (BABYLON = {}));
  93580. //# sourceMappingURL=babylon.assetsManager.js.map
  93581. var BABYLON;
  93582. (function (BABYLON) {
  93583. var serializedGeometries = [];
  93584. var serializeGeometry = function (geometry, serializationGeometries) {
  93585. if (serializedGeometries[geometry.id]) {
  93586. return;
  93587. }
  93588. if (geometry.doNotSerialize) {
  93589. return;
  93590. }
  93591. if (geometry instanceof BABYLON.BoxGeometry) {
  93592. serializationGeometries.boxes.push(geometry.serialize());
  93593. }
  93594. else if (geometry instanceof BABYLON.SphereGeometry) {
  93595. serializationGeometries.spheres.push(geometry.serialize());
  93596. }
  93597. else if (geometry instanceof BABYLON.CylinderGeometry) {
  93598. serializationGeometries.cylinders.push(geometry.serialize());
  93599. }
  93600. else if (geometry instanceof BABYLON.TorusGeometry) {
  93601. serializationGeometries.toruses.push(geometry.serialize());
  93602. }
  93603. else if (geometry instanceof BABYLON.GroundGeometry) {
  93604. serializationGeometries.grounds.push(geometry.serialize());
  93605. }
  93606. else if (geometry instanceof BABYLON.Plane) {
  93607. serializationGeometries.planes.push(geometry.serialize());
  93608. }
  93609. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  93610. serializationGeometries.torusKnots.push(geometry.serialize());
  93611. }
  93612. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  93613. throw new Error("Unknown primitive type");
  93614. }
  93615. else {
  93616. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  93617. }
  93618. serializedGeometries[geometry.id] = true;
  93619. };
  93620. var serializeMesh = function (mesh, serializationScene) {
  93621. var serializationObject = {};
  93622. // Geometry
  93623. var geometry = mesh._geometry;
  93624. if (geometry) {
  93625. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  93626. // 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
  93627. serializeGeometry(geometry, serializationScene.geometries);
  93628. }
  93629. }
  93630. // Custom
  93631. if (mesh.serialize) {
  93632. mesh.serialize(serializationObject);
  93633. }
  93634. return serializationObject;
  93635. };
  93636. var finalizeSingleMesh = function (mesh, serializationObject) {
  93637. //only works if the mesh is already loaded
  93638. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93639. //serialize material
  93640. if (mesh.material) {
  93641. if (mesh.material instanceof BABYLON.StandardMaterial) {
  93642. serializationObject.materials = serializationObject.materials || [];
  93643. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93644. serializationObject.materials.push(mesh.material.serialize());
  93645. }
  93646. }
  93647. else if (mesh.material instanceof BABYLON.MultiMaterial) {
  93648. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  93649. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  93650. serializationObject.multiMaterials.push(mesh.material.serialize());
  93651. }
  93652. }
  93653. }
  93654. //serialize geometry
  93655. var geometry = mesh._geometry;
  93656. if (geometry) {
  93657. if (!serializationObject.geometries) {
  93658. serializationObject.geometries = {};
  93659. serializationObject.geometries.boxes = [];
  93660. serializationObject.geometries.spheres = [];
  93661. serializationObject.geometries.cylinders = [];
  93662. serializationObject.geometries.toruses = [];
  93663. serializationObject.geometries.grounds = [];
  93664. serializationObject.geometries.planes = [];
  93665. serializationObject.geometries.torusKnots = [];
  93666. serializationObject.geometries.vertexData = [];
  93667. }
  93668. serializeGeometry(geometry, serializationObject.geometries);
  93669. }
  93670. // Skeletons
  93671. if (mesh.skeleton) {
  93672. serializationObject.skeletons = serializationObject.skeletons || [];
  93673. serializationObject.skeletons.push(mesh.skeleton.serialize());
  93674. }
  93675. //serialize the actual mesh
  93676. serializationObject.meshes = serializationObject.meshes || [];
  93677. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93678. }
  93679. };
  93680. var SceneSerializer = /** @class */ (function () {
  93681. function SceneSerializer() {
  93682. }
  93683. SceneSerializer.ClearCache = function () {
  93684. serializedGeometries = [];
  93685. };
  93686. SceneSerializer.Serialize = function (scene) {
  93687. var serializationObject = {};
  93688. SceneSerializer.ClearCache();
  93689. // Scene
  93690. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  93691. serializationObject.autoClear = scene.autoClear;
  93692. serializationObject.clearColor = scene.clearColor.asArray();
  93693. serializationObject.ambientColor = scene.ambientColor.asArray();
  93694. serializationObject.gravity = scene.gravity.asArray();
  93695. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  93696. serializationObject.workerCollisions = scene.workerCollisions;
  93697. // Fog
  93698. if (scene.fogMode && scene.fogMode !== 0) {
  93699. serializationObject.fogMode = scene.fogMode;
  93700. serializationObject.fogColor = scene.fogColor.asArray();
  93701. serializationObject.fogStart = scene.fogStart;
  93702. serializationObject.fogEnd = scene.fogEnd;
  93703. serializationObject.fogDensity = scene.fogDensity;
  93704. }
  93705. //Physics
  93706. if (scene.isPhysicsEnabled()) {
  93707. var physicEngine = scene.getPhysicsEngine();
  93708. if (physicEngine) {
  93709. serializationObject.physicsEnabled = true;
  93710. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  93711. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  93712. }
  93713. }
  93714. // Metadata
  93715. if (scene.metadata) {
  93716. serializationObject.metadata = scene.metadata;
  93717. }
  93718. // Morph targets
  93719. serializationObject.morphTargetManagers = [];
  93720. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  93721. var abstractMesh = _a[_i];
  93722. var manager = abstractMesh.morphTargetManager;
  93723. if (manager) {
  93724. serializationObject.morphTargetManagers.push(manager.serialize());
  93725. }
  93726. }
  93727. // Lights
  93728. serializationObject.lights = [];
  93729. var index;
  93730. var light;
  93731. for (index = 0; index < scene.lights.length; index++) {
  93732. light = scene.lights[index];
  93733. if (!light.doNotSerialize) {
  93734. serializationObject.lights.push(light.serialize());
  93735. }
  93736. }
  93737. // Cameras
  93738. serializationObject.cameras = [];
  93739. for (index = 0; index < scene.cameras.length; index++) {
  93740. var camera = scene.cameras[index];
  93741. if (!camera.doNotSerialize) {
  93742. serializationObject.cameras.push(camera.serialize());
  93743. }
  93744. }
  93745. if (scene.activeCamera) {
  93746. serializationObject.activeCameraID = scene.activeCamera.id;
  93747. }
  93748. // Animations
  93749. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  93750. // Materials
  93751. serializationObject.materials = [];
  93752. serializationObject.multiMaterials = [];
  93753. var material;
  93754. for (index = 0; index < scene.materials.length; index++) {
  93755. material = scene.materials[index];
  93756. if (!material.doNotSerialize) {
  93757. serializationObject.materials.push(material.serialize());
  93758. }
  93759. }
  93760. // MultiMaterials
  93761. serializationObject.multiMaterials = [];
  93762. for (index = 0; index < scene.multiMaterials.length; index++) {
  93763. var multiMaterial = scene.multiMaterials[index];
  93764. serializationObject.multiMaterials.push(multiMaterial.serialize());
  93765. }
  93766. // Environment texture
  93767. if (scene.environmentTexture) {
  93768. serializationObject.environmentTexture = scene.environmentTexture.name;
  93769. }
  93770. // Skeletons
  93771. serializationObject.skeletons = [];
  93772. for (index = 0; index < scene.skeletons.length; index++) {
  93773. var skeleton = scene.skeletons[index];
  93774. if (!skeleton.doNotSerialize) {
  93775. serializationObject.skeletons.push(skeleton.serialize());
  93776. }
  93777. }
  93778. // Transform nodes
  93779. serializationObject.transformNodes = [];
  93780. for (index = 0; index < scene.transformNodes.length; index++) {
  93781. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  93782. }
  93783. // Geometries
  93784. serializationObject.geometries = {};
  93785. serializationObject.geometries.boxes = [];
  93786. serializationObject.geometries.spheres = [];
  93787. serializationObject.geometries.cylinders = [];
  93788. serializationObject.geometries.toruses = [];
  93789. serializationObject.geometries.grounds = [];
  93790. serializationObject.geometries.planes = [];
  93791. serializationObject.geometries.torusKnots = [];
  93792. serializationObject.geometries.vertexData = [];
  93793. serializedGeometries = [];
  93794. var geometries = scene.getGeometries();
  93795. for (index = 0; index < geometries.length; index++) {
  93796. var geometry = geometries[index];
  93797. if (geometry.isReady()) {
  93798. serializeGeometry(geometry, serializationObject.geometries);
  93799. }
  93800. }
  93801. // Meshes
  93802. serializationObject.meshes = [];
  93803. for (index = 0; index < scene.meshes.length; index++) {
  93804. var abstractMesh = scene.meshes[index];
  93805. if (abstractMesh instanceof BABYLON.Mesh) {
  93806. var mesh = abstractMesh;
  93807. if (!mesh.doNotSerialize) {
  93808. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  93809. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  93810. }
  93811. }
  93812. }
  93813. }
  93814. // Particles Systems
  93815. serializationObject.particleSystems = [];
  93816. for (index = 0; index < scene.particleSystems.length; index++) {
  93817. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  93818. }
  93819. // Lens flares
  93820. serializationObject.lensFlareSystems = [];
  93821. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  93822. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  93823. }
  93824. // Shadows
  93825. serializationObject.shadowGenerators = [];
  93826. for (index = 0; index < scene.lights.length; index++) {
  93827. light = scene.lights[index];
  93828. var shadowGenerator = light.getShadowGenerator();
  93829. if (shadowGenerator) {
  93830. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  93831. }
  93832. }
  93833. // Action Manager
  93834. if (scene.actionManager) {
  93835. serializationObject.actions = scene.actionManager.serialize("scene");
  93836. }
  93837. // Audio
  93838. serializationObject.sounds = [];
  93839. for (index = 0; index < scene.soundTracks.length; index++) {
  93840. var soundtrack = scene.soundTracks[index];
  93841. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  93842. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  93843. }
  93844. }
  93845. // Effect layers
  93846. serializationObject.effectLayers = [];
  93847. for (index = 0; index < scene.effectLayers.length; index++) {
  93848. var layer = scene.effectLayers[index];
  93849. if (layer.serialize) {
  93850. serializationObject.effectLayers.push(layer.serialize());
  93851. }
  93852. }
  93853. return serializationObject;
  93854. };
  93855. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  93856. if (withParents === void 0) { withParents = false; }
  93857. if (withChildren === void 0) { withChildren = false; }
  93858. var serializationObject = {};
  93859. SceneSerializer.ClearCache();
  93860. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  93861. if (withParents || withChildren) {
  93862. //deliberate for loop! not for each, appended should be processed as well.
  93863. for (var i = 0; i < toSerialize.length; ++i) {
  93864. if (withChildren) {
  93865. toSerialize[i].getDescendants().forEach(function (node) {
  93866. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  93867. toSerialize.push(node);
  93868. }
  93869. });
  93870. }
  93871. //make sure the array doesn't contain the object already
  93872. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  93873. toSerialize.push(toSerialize[i].parent);
  93874. }
  93875. }
  93876. }
  93877. toSerialize.forEach(function (mesh) {
  93878. finalizeSingleMesh(mesh, serializationObject);
  93879. });
  93880. return serializationObject;
  93881. };
  93882. return SceneSerializer;
  93883. }());
  93884. BABYLON.SceneSerializer = SceneSerializer;
  93885. })(BABYLON || (BABYLON = {}));
  93886. //# sourceMappingURL=babylon.sceneSerializer.js.map
  93887. var BABYLON;
  93888. (function (BABYLON) {
  93889. var ReflectionProbe = /** @class */ (function () {
  93890. function ReflectionProbe(name, size, scene, generateMipMaps) {
  93891. if (generateMipMaps === void 0) { generateMipMaps = true; }
  93892. var _this = this;
  93893. this.name = name;
  93894. this._viewMatrix = BABYLON.Matrix.Identity();
  93895. this._target = BABYLON.Vector3.Zero();
  93896. this._add = BABYLON.Vector3.Zero();
  93897. this._invertYAxis = false;
  93898. this.position = BABYLON.Vector3.Zero();
  93899. this._scene = scene;
  93900. this._scene.reflectionProbes.push(this);
  93901. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  93902. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  93903. switch (faceIndex) {
  93904. case 0:
  93905. _this._add.copyFromFloats(1, 0, 0);
  93906. break;
  93907. case 1:
  93908. _this._add.copyFromFloats(-1, 0, 0);
  93909. break;
  93910. case 2:
  93911. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  93912. break;
  93913. case 3:
  93914. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  93915. break;
  93916. case 4:
  93917. _this._add.copyFromFloats(0, 0, 1);
  93918. break;
  93919. case 5:
  93920. _this._add.copyFromFloats(0, 0, -1);
  93921. break;
  93922. }
  93923. if (_this._attachedMesh) {
  93924. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  93925. }
  93926. _this.position.addToRef(_this._add, _this._target);
  93927. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  93928. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  93929. scene._forcedViewPosition = _this.position;
  93930. });
  93931. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  93932. scene._forcedViewPosition = null;
  93933. scene.updateTransformMatrix(true);
  93934. });
  93935. if (scene.activeCamera) {
  93936. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  93937. }
  93938. }
  93939. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  93940. get: function () {
  93941. return this._renderTargetTexture.samples;
  93942. },
  93943. set: function (value) {
  93944. this._renderTargetTexture.samples = value;
  93945. },
  93946. enumerable: true,
  93947. configurable: true
  93948. });
  93949. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  93950. get: function () {
  93951. return this._renderTargetTexture.refreshRate;
  93952. },
  93953. set: function (value) {
  93954. this._renderTargetTexture.refreshRate = value;
  93955. },
  93956. enumerable: true,
  93957. configurable: true
  93958. });
  93959. ReflectionProbe.prototype.getScene = function () {
  93960. return this._scene;
  93961. };
  93962. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  93963. get: function () {
  93964. return this._renderTargetTexture;
  93965. },
  93966. enumerable: true,
  93967. configurable: true
  93968. });
  93969. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  93970. get: function () {
  93971. return this._renderTargetTexture.renderList;
  93972. },
  93973. enumerable: true,
  93974. configurable: true
  93975. });
  93976. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  93977. this._attachedMesh = mesh;
  93978. };
  93979. /**
  93980. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  93981. *
  93982. * @param renderingGroupId The rendering group id corresponding to its index
  93983. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  93984. */
  93985. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  93986. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  93987. };
  93988. ReflectionProbe.prototype.dispose = function () {
  93989. var index = this._scene.reflectionProbes.indexOf(this);
  93990. if (index !== -1) {
  93991. // Remove from the scene if found
  93992. this._scene.reflectionProbes.splice(index, 1);
  93993. }
  93994. if (this._renderTargetTexture) {
  93995. this._renderTargetTexture.dispose();
  93996. this._renderTargetTexture = null;
  93997. }
  93998. };
  93999. return ReflectionProbe;
  94000. }());
  94001. BABYLON.ReflectionProbe = ReflectionProbe;
  94002. })(BABYLON || (BABYLON = {}));
  94003. //# sourceMappingURL=babylon.reflectionProbe.js.map
  94004. var BABYLON;
  94005. (function (BABYLON) {
  94006. var Layer = /** @class */ (function () {
  94007. function Layer(name, imgUrl, scene, isBackground, color) {
  94008. this.name = name;
  94009. this.scale = new BABYLON.Vector2(1, 1);
  94010. this.offset = new BABYLON.Vector2(0, 0);
  94011. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  94012. this.layerMask = 0x0FFFFFFF;
  94013. this._vertexBuffers = {};
  94014. // Events
  94015. /**
  94016. * An event triggered when the layer is disposed.
  94017. */
  94018. this.onDisposeObservable = new BABYLON.Observable();
  94019. /**
  94020. * An event triggered before rendering the scene
  94021. */
  94022. this.onBeforeRenderObservable = new BABYLON.Observable();
  94023. /**
  94024. * An event triggered after rendering the scene
  94025. */
  94026. this.onAfterRenderObservable = new BABYLON.Observable();
  94027. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  94028. this.isBackground = isBackground === undefined ? true : isBackground;
  94029. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  94030. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  94031. this._scene.layers.push(this);
  94032. var engine = this._scene.getEngine();
  94033. // VBO
  94034. var vertices = [];
  94035. vertices.push(1, 1);
  94036. vertices.push(-1, 1);
  94037. vertices.push(-1, -1);
  94038. vertices.push(1, -1);
  94039. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  94040. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  94041. this._createIndexBuffer();
  94042. // Effects
  94043. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  94044. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  94045. }
  94046. Object.defineProperty(Layer.prototype, "onDispose", {
  94047. set: function (callback) {
  94048. if (this._onDisposeObserver) {
  94049. this.onDisposeObservable.remove(this._onDisposeObserver);
  94050. }
  94051. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  94052. },
  94053. enumerable: true,
  94054. configurable: true
  94055. });
  94056. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  94057. set: function (callback) {
  94058. if (this._onBeforeRenderObserver) {
  94059. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  94060. }
  94061. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  94062. },
  94063. enumerable: true,
  94064. configurable: true
  94065. });
  94066. Object.defineProperty(Layer.prototype, "onAfterRender", {
  94067. set: function (callback) {
  94068. if (this._onAfterRenderObserver) {
  94069. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  94070. }
  94071. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  94072. },
  94073. enumerable: true,
  94074. configurable: true
  94075. });
  94076. Layer.prototype._createIndexBuffer = function () {
  94077. var engine = this._scene.getEngine();
  94078. // Indices
  94079. var indices = [];
  94080. indices.push(0);
  94081. indices.push(1);
  94082. indices.push(2);
  94083. indices.push(0);
  94084. indices.push(2);
  94085. indices.push(3);
  94086. this._indexBuffer = engine.createIndexBuffer(indices);
  94087. };
  94088. Layer.prototype._rebuild = function () {
  94089. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94090. if (vb) {
  94091. vb._rebuild();
  94092. }
  94093. this._createIndexBuffer();
  94094. };
  94095. Layer.prototype.render = function () {
  94096. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  94097. // Check
  94098. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  94099. return;
  94100. var engine = this._scene.getEngine();
  94101. this.onBeforeRenderObservable.notifyObservers(this);
  94102. // Render
  94103. engine.enableEffect(currentEffect);
  94104. engine.setState(false);
  94105. // Texture
  94106. currentEffect.setTexture("textureSampler", this.texture);
  94107. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  94108. // Color
  94109. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  94110. // Scale / offset
  94111. currentEffect.setVector2("offset", this.offset);
  94112. currentEffect.setVector2("scale", this.scale);
  94113. // VBOs
  94114. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  94115. // Draw order
  94116. if (!this.alphaTest) {
  94117. engine.setAlphaMode(this.alphaBlendingMode);
  94118. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94119. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  94120. }
  94121. else {
  94122. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  94123. }
  94124. this.onAfterRenderObservable.notifyObservers(this);
  94125. };
  94126. Layer.prototype.dispose = function () {
  94127. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  94128. if (vertexBuffer) {
  94129. vertexBuffer.dispose();
  94130. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  94131. }
  94132. if (this._indexBuffer) {
  94133. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  94134. this._indexBuffer = null;
  94135. }
  94136. if (this.texture) {
  94137. this.texture.dispose();
  94138. this.texture = null;
  94139. }
  94140. // Remove from scene
  94141. var index = this._scene.layers.indexOf(this);
  94142. this._scene.layers.splice(index, 1);
  94143. // Callback
  94144. this.onDisposeObservable.notifyObservers(this);
  94145. this.onDisposeObservable.clear();
  94146. this.onAfterRenderObservable.clear();
  94147. this.onBeforeRenderObservable.clear();
  94148. };
  94149. return Layer;
  94150. }());
  94151. BABYLON.Layer = Layer;
  94152. })(BABYLON || (BABYLON = {}));
  94153. //# sourceMappingURL=babylon.layer.js.map
  94154. var BABYLON;
  94155. (function (BABYLON) {
  94156. var TextureTools = /** @class */ (function () {
  94157. function TextureTools() {
  94158. }
  94159. /**
  94160. * Uses the GPU to create a copy texture rescaled at a given size
  94161. * @param texture Texture to copy from
  94162. * @param width Desired width
  94163. * @param height Desired height
  94164. * @return Generated texture
  94165. */
  94166. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  94167. if (useBilinearMode === void 0) { useBilinearMode = true; }
  94168. var scene = texture.getScene();
  94169. var engine = scene.getEngine();
  94170. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  94171. rtt.wrapU = texture.wrapU;
  94172. rtt.wrapV = texture.wrapV;
  94173. rtt.uOffset = texture.uOffset;
  94174. rtt.vOffset = texture.vOffset;
  94175. rtt.uScale = texture.uScale;
  94176. rtt.vScale = texture.vScale;
  94177. rtt.uAng = texture.uAng;
  94178. rtt.vAng = texture.vAng;
  94179. rtt.wAng = texture.wAng;
  94180. rtt.coordinatesIndex = texture.coordinatesIndex;
  94181. rtt.level = texture.level;
  94182. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  94183. rtt._texture.isReady = false;
  94184. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94185. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94186. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  94187. passPostProcess.getEffect().executeWhenCompiled(function () {
  94188. passPostProcess.onApply = function (effect) {
  94189. effect.setTexture("textureSampler", texture);
  94190. };
  94191. var internalTexture = rtt.getInternalTexture();
  94192. if (internalTexture) {
  94193. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  94194. engine.unBindFramebuffer(internalTexture);
  94195. rtt.disposeFramebufferObjects();
  94196. passPostProcess.dispose();
  94197. internalTexture.isReady = true;
  94198. }
  94199. });
  94200. return rtt;
  94201. };
  94202. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  94203. if (!scene._environmentBRDFTexture) {
  94204. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  94205. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94206. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  94207. scene._environmentBRDFTexture = texture;
  94208. }
  94209. return scene._environmentBRDFTexture;
  94210. };
  94211. 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=";
  94212. return TextureTools;
  94213. }());
  94214. BABYLON.TextureTools = TextureTools;
  94215. })(BABYLON || (BABYLON = {}));
  94216. //# sourceMappingURL=babylon.textureTools.js.map
  94217. var BABYLON;
  94218. (function (BABYLON) {
  94219. var FramingBehavior = /** @class */ (function () {
  94220. function FramingBehavior() {
  94221. this._mode = FramingBehavior.FitFrustumSidesMode;
  94222. this._radiusScale = 1.0;
  94223. this._positionScale = 0.5;
  94224. this._defaultElevation = 0.3;
  94225. this._elevationReturnTime = 1500;
  94226. this._elevationReturnWaitTime = 1000;
  94227. this._zoomStopsAnimation = false;
  94228. this._framingTime = 1500;
  94229. this._isPointerDown = false;
  94230. this._lastInteractionTime = -Infinity;
  94231. // Framing control
  94232. this._animatables = new Array();
  94233. this._betaIsAnimating = false;
  94234. }
  94235. Object.defineProperty(FramingBehavior.prototype, "name", {
  94236. get: function () {
  94237. return "Framing";
  94238. },
  94239. enumerable: true,
  94240. configurable: true
  94241. });
  94242. Object.defineProperty(FramingBehavior.prototype, "mode", {
  94243. /**
  94244. * Gets current mode used by the behavior.
  94245. */
  94246. get: function () {
  94247. return this._mode;
  94248. },
  94249. /**
  94250. * Sets the current mode used by the behavior
  94251. */
  94252. set: function (mode) {
  94253. this._mode = mode;
  94254. },
  94255. enumerable: true,
  94256. configurable: true
  94257. });
  94258. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  94259. /**
  94260. * Gets the scale applied to the radius
  94261. */
  94262. get: function () {
  94263. return this._radiusScale;
  94264. },
  94265. /**
  94266. * Sets the scale applied to the radius (1 by default)
  94267. */
  94268. set: function (radius) {
  94269. this._radiusScale = radius;
  94270. },
  94271. enumerable: true,
  94272. configurable: true
  94273. });
  94274. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  94275. /**
  94276. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94277. */
  94278. get: function () {
  94279. return this._positionScale;
  94280. },
  94281. /**
  94282. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  94283. */
  94284. set: function (scale) {
  94285. this._positionScale = scale;
  94286. },
  94287. enumerable: true,
  94288. configurable: true
  94289. });
  94290. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  94291. /**
  94292. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94293. * behaviour is triggered, in radians.
  94294. */
  94295. get: function () {
  94296. return this._defaultElevation;
  94297. },
  94298. /**
  94299. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  94300. * behaviour is triggered, in radians.
  94301. */
  94302. set: function (elevation) {
  94303. this._defaultElevation = elevation;
  94304. },
  94305. enumerable: true,
  94306. configurable: true
  94307. });
  94308. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  94309. /**
  94310. * Gets the time (in milliseconds) taken to return to the default beta position.
  94311. * Negative value indicates camera should not return to default.
  94312. */
  94313. get: function () {
  94314. return this._elevationReturnTime;
  94315. },
  94316. /**
  94317. * Sets the time (in milliseconds) taken to return to the default beta position.
  94318. * Negative value indicates camera should not return to default.
  94319. */
  94320. set: function (speed) {
  94321. this._elevationReturnTime = speed;
  94322. },
  94323. enumerable: true,
  94324. configurable: true
  94325. });
  94326. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  94327. /**
  94328. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94329. */
  94330. get: function () {
  94331. return this._elevationReturnWaitTime;
  94332. },
  94333. /**
  94334. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  94335. */
  94336. set: function (time) {
  94337. this._elevationReturnWaitTime = time;
  94338. },
  94339. enumerable: true,
  94340. configurable: true
  94341. });
  94342. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  94343. /**
  94344. * Gets the flag that indicates if user zooming should stop animation.
  94345. */
  94346. get: function () {
  94347. return this._zoomStopsAnimation;
  94348. },
  94349. /**
  94350. * Sets the flag that indicates if user zooming should stop animation.
  94351. */
  94352. set: function (flag) {
  94353. this._zoomStopsAnimation = flag;
  94354. },
  94355. enumerable: true,
  94356. configurable: true
  94357. });
  94358. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  94359. /**
  94360. * Gets the transition time when framing the mesh, in milliseconds
  94361. */
  94362. get: function () {
  94363. return this._framingTime;
  94364. },
  94365. /**
  94366. * Sets the transition time when framing the mesh, in milliseconds
  94367. */
  94368. set: function (time) {
  94369. this._framingTime = time;
  94370. },
  94371. enumerable: true,
  94372. configurable: true
  94373. });
  94374. FramingBehavior.prototype.init = function () {
  94375. // Do notihng
  94376. };
  94377. FramingBehavior.prototype.attach = function (camera) {
  94378. var _this = this;
  94379. this._attachedCamera = camera;
  94380. var scene = this._attachedCamera.getScene();
  94381. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  94382. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94383. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94384. _this._isPointerDown = true;
  94385. return;
  94386. }
  94387. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94388. _this._isPointerDown = false;
  94389. }
  94390. });
  94391. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94392. if (mesh) {
  94393. _this.zoomOnMesh(mesh);
  94394. }
  94395. });
  94396. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94397. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94398. _this._applyUserInteraction();
  94399. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  94400. // back to the default position after a given timeout
  94401. _this._maintainCameraAboveGround();
  94402. });
  94403. };
  94404. FramingBehavior.prototype.detach = function () {
  94405. if (!this._attachedCamera) {
  94406. return;
  94407. }
  94408. var scene = this._attachedCamera.getScene();
  94409. if (this._onPrePointerObservableObserver) {
  94410. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  94411. }
  94412. if (this._onAfterCheckInputsObserver) {
  94413. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94414. }
  94415. if (this._onMeshTargetChangedObserver) {
  94416. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94417. }
  94418. this._attachedCamera = null;
  94419. };
  94420. /**
  94421. * Targets the given mesh and updates zoom level accordingly.
  94422. * @param mesh The mesh to target.
  94423. * @param radius Optional. If a cached radius position already exists, overrides default.
  94424. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94425. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94426. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94427. */
  94428. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94429. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94430. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94431. mesh.computeWorldMatrix(true);
  94432. var boundingBox = mesh.getBoundingInfo().boundingBox;
  94433. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  94434. };
  94435. /**
  94436. * Targets the given mesh with its children and updates zoom level accordingly.
  94437. * @param mesh The mesh to target.
  94438. * @param radius Optional. If a cached radius position already exists, overrides default.
  94439. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94440. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94441. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94442. */
  94443. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  94444. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94445. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94446. mesh.computeWorldMatrix(true);
  94447. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  94448. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  94449. };
  94450. /**
  94451. * Targets the given meshes with their children and updates zoom level accordingly.
  94452. * @param meshes The mesh to target.
  94453. * @param radius Optional. If a cached radius position already exists, overrides default.
  94454. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94455. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94456. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94457. */
  94458. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  94459. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94460. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94461. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  94462. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  94463. for (var i = 0; i < meshes.length; i++) {
  94464. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  94465. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  94466. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  94467. }
  94468. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  94469. };
  94470. /**
  94471. * Targets the given mesh and updates zoom level accordingly.
  94472. * @param mesh The mesh to target.
  94473. * @param radius Optional. If a cached radius position already exists, overrides default.
  94474. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  94475. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  94476. * @param onAnimationEnd Callback triggered at the end of the framing animation
  94477. */
  94478. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  94479. var _this = this;
  94480. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  94481. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  94482. var zoomTarget;
  94483. if (!this._attachedCamera) {
  94484. return;
  94485. }
  94486. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  94487. var bottom = minimumWorld.y;
  94488. var top = maximumWorld.y;
  94489. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  94490. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  94491. if (focusOnOriginXZ) {
  94492. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  94493. }
  94494. else {
  94495. var centerWorld = minimumWorld.add(radiusWorld);
  94496. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  94497. }
  94498. if (!this._vectorTransition) {
  94499. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  94500. }
  94501. this._betaIsAnimating = true;
  94502. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  94503. if (animatable) {
  94504. this._animatables.push(animatable);
  94505. }
  94506. // sets the radius and lower radius bounds
  94507. // Small delta ensures camera is not always at lower zoom limit.
  94508. var radius = 0;
  94509. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  94510. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94511. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  94512. radius = position;
  94513. }
  94514. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94515. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  94516. if (this._attachedCamera.lowerRadiusLimit === null) {
  94517. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  94518. }
  94519. }
  94520. // Set sensibilities
  94521. var extend = maximumWorld.subtract(minimumWorld).length();
  94522. this._attachedCamera.panningSensibility = 5000 / extend;
  94523. this._attachedCamera.wheelPrecision = 100 / radius;
  94524. // transition to new radius
  94525. if (!this._radiusTransition) {
  94526. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94527. }
  94528. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  94529. _this.stopAllAnimations();
  94530. if (onAnimationEnd) {
  94531. onAnimationEnd();
  94532. }
  94533. if (_this._attachedCamera) {
  94534. _this._attachedCamera.storeState();
  94535. }
  94536. });
  94537. if (animatable) {
  94538. this._animatables.push(animatable);
  94539. }
  94540. };
  94541. /**
  94542. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  94543. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  94544. * frustum width.
  94545. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  94546. * to fully enclose the mesh in the viewing frustum.
  94547. */
  94548. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  94549. var size = maximumWorld.subtract(minimumWorld);
  94550. var boxVectorGlobalDiagonal = size.length();
  94551. var frustumSlope = this._getFrustumSlope();
  94552. // Formula for setting distance
  94553. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  94554. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  94555. // Horizon distance
  94556. var radius = radiusWithoutFraming * this._radiusScale;
  94557. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  94558. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  94559. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  94560. var camera = this._attachedCamera;
  94561. if (!camera) {
  94562. return 0;
  94563. }
  94564. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  94565. // Don't exceed the requested limit
  94566. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  94567. }
  94568. // Don't exceed the upper radius limit
  94569. if (camera.upperRadiusLimit) {
  94570. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  94571. }
  94572. return distance;
  94573. };
  94574. /**
  94575. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  94576. * is automatically returned to its default position (expected to be above ground plane).
  94577. */
  94578. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  94579. var _this = this;
  94580. if (this._elevationReturnTime < 0) {
  94581. return;
  94582. }
  94583. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  94584. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  94585. var limitBeta = Math.PI * 0.5;
  94586. // Bring the camera back up if below the ground plane
  94587. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  94588. this._betaIsAnimating = true;
  94589. //Transition to new position
  94590. this.stopAllAnimations();
  94591. if (!this._betaTransition) {
  94592. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  94593. }
  94594. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  94595. _this._clearAnimationLocks();
  94596. _this.stopAllAnimations();
  94597. });
  94598. if (animatabe) {
  94599. this._animatables.push(animatabe);
  94600. }
  94601. }
  94602. };
  94603. /**
  94604. * Returns the frustum slope based on the canvas ratio and camera FOV
  94605. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  94606. */
  94607. FramingBehavior.prototype._getFrustumSlope = function () {
  94608. // Calculate the viewport ratio
  94609. // Aspect Ratio is Height/Width.
  94610. var camera = this._attachedCamera;
  94611. if (!camera) {
  94612. return BABYLON.Vector2.Zero();
  94613. }
  94614. var engine = camera.getScene().getEngine();
  94615. var aspectRatio = engine.getAspectRatio(camera);
  94616. // Camera FOV is the vertical field of view (top-bottom) in radians.
  94617. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  94618. var frustumSlopeY = Math.tan(camera.fov / 2);
  94619. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  94620. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  94621. // along the forward vector.
  94622. var frustumSlopeX = frustumSlopeY * aspectRatio;
  94623. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  94624. };
  94625. /**
  94626. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  94627. */
  94628. FramingBehavior.prototype._clearAnimationLocks = function () {
  94629. this._betaIsAnimating = false;
  94630. };
  94631. /**
  94632. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  94633. */
  94634. FramingBehavior.prototype._applyUserInteraction = function () {
  94635. if (this.isUserIsMoving) {
  94636. this._lastInteractionTime = BABYLON.Tools.Now;
  94637. this.stopAllAnimations();
  94638. this._clearAnimationLocks();
  94639. }
  94640. };
  94641. /**
  94642. * Stops and removes all animations that have been applied to the camera
  94643. */
  94644. FramingBehavior.prototype.stopAllAnimations = function () {
  94645. if (this._attachedCamera) {
  94646. this._attachedCamera.animations = [];
  94647. }
  94648. while (this._animatables.length) {
  94649. if (this._animatables[0]) {
  94650. this._animatables[0].onAnimationEnd = null;
  94651. this._animatables[0].stop();
  94652. }
  94653. this._animatables.shift();
  94654. }
  94655. };
  94656. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  94657. /**
  94658. * Gets a value indicating if the user is moving the camera
  94659. */
  94660. get: function () {
  94661. if (!this._attachedCamera) {
  94662. return false;
  94663. }
  94664. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  94665. this._attachedCamera.inertialBetaOffset !== 0 ||
  94666. this._attachedCamera.inertialRadiusOffset !== 0 ||
  94667. this._attachedCamera.inertialPanningX !== 0 ||
  94668. this._attachedCamera.inertialPanningY !== 0 ||
  94669. this._isPointerDown;
  94670. },
  94671. enumerable: true,
  94672. configurable: true
  94673. });
  94674. /**
  94675. * The easing function used by animations
  94676. */
  94677. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  94678. /**
  94679. * The easing mode used by animations
  94680. */
  94681. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  94682. // Statics
  94683. /**
  94684. * The camera can move all the way towards the mesh.
  94685. */
  94686. FramingBehavior.IgnoreBoundsSizeMode = 0;
  94687. /**
  94688. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  94689. */
  94690. FramingBehavior.FitFrustumSidesMode = 1;
  94691. return FramingBehavior;
  94692. }());
  94693. BABYLON.FramingBehavior = FramingBehavior;
  94694. })(BABYLON || (BABYLON = {}));
  94695. //# sourceMappingURL=babylon.framingBehavior.js.map
  94696. var BABYLON;
  94697. (function (BABYLON) {
  94698. /**
  94699. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  94700. */
  94701. var BouncingBehavior = /** @class */ (function () {
  94702. function BouncingBehavior() {
  94703. /**
  94704. * The duration of the animation, in milliseconds
  94705. */
  94706. this.transitionDuration = 450;
  94707. /**
  94708. * Length of the distance animated by the transition when lower radius is reached
  94709. */
  94710. this.lowerRadiusTransitionRange = 2;
  94711. /**
  94712. * Length of the distance animated by the transition when upper radius is reached
  94713. */
  94714. this.upperRadiusTransitionRange = -2;
  94715. this._autoTransitionRange = false;
  94716. // Animations
  94717. this._radiusIsAnimating = false;
  94718. this._radiusBounceTransition = null;
  94719. this._animatables = new Array();
  94720. }
  94721. Object.defineProperty(BouncingBehavior.prototype, "name", {
  94722. get: function () {
  94723. return "Bouncing";
  94724. },
  94725. enumerable: true,
  94726. configurable: true
  94727. });
  94728. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  94729. /**
  94730. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94731. */
  94732. get: function () {
  94733. return this._autoTransitionRange;
  94734. },
  94735. /**
  94736. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  94737. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  94738. */
  94739. set: function (value) {
  94740. var _this = this;
  94741. if (this._autoTransitionRange === value) {
  94742. return;
  94743. }
  94744. this._autoTransitionRange = value;
  94745. var camera = this._attachedCamera;
  94746. if (!camera) {
  94747. return;
  94748. }
  94749. if (value) {
  94750. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  94751. if (!mesh) {
  94752. return;
  94753. }
  94754. mesh.computeWorldMatrix(true);
  94755. var diagonal = mesh.getBoundingInfo().diagonalLength;
  94756. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  94757. _this.upperRadiusTransitionRange = diagonal * 0.05;
  94758. });
  94759. }
  94760. else if (this._onMeshTargetChangedObserver) {
  94761. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94762. }
  94763. },
  94764. enumerable: true,
  94765. configurable: true
  94766. });
  94767. BouncingBehavior.prototype.init = function () {
  94768. // Do notihng
  94769. };
  94770. BouncingBehavior.prototype.attach = function (camera) {
  94771. var _this = this;
  94772. this._attachedCamera = camera;
  94773. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94774. if (!_this._attachedCamera) {
  94775. return;
  94776. }
  94777. // Add the bounce animation to the lower radius limit
  94778. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  94779. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  94780. }
  94781. // Add the bounce animation to the upper radius limit
  94782. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  94783. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  94784. }
  94785. });
  94786. };
  94787. BouncingBehavior.prototype.detach = function () {
  94788. if (!this._attachedCamera) {
  94789. return;
  94790. }
  94791. if (this._onAfterCheckInputsObserver) {
  94792. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  94793. }
  94794. if (this._onMeshTargetChangedObserver) {
  94795. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  94796. }
  94797. this._attachedCamera = null;
  94798. };
  94799. /**
  94800. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  94801. * @param radiusLimit The limit to check against.
  94802. * @return Bool to indicate if at limit.
  94803. */
  94804. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  94805. if (!this._attachedCamera) {
  94806. return false;
  94807. }
  94808. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  94809. return true;
  94810. }
  94811. return false;
  94812. };
  94813. /**
  94814. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  94815. * @param radiusDelta The delta by which to animate to. Can be negative.
  94816. */
  94817. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  94818. var _this = this;
  94819. if (!this._attachedCamera) {
  94820. return;
  94821. }
  94822. if (!this._radiusBounceTransition) {
  94823. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  94824. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  94825. }
  94826. // Prevent zoom until bounce has completed
  94827. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  94828. this._attachedCamera.wheelPrecision = Infinity;
  94829. this._attachedCamera.inertialRadiusOffset = 0;
  94830. // Animate to the radius limit
  94831. this.stopAllAnimations();
  94832. this._radiusIsAnimating = true;
  94833. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  94834. if (animatable) {
  94835. this._animatables.push(animatable);
  94836. }
  94837. };
  94838. /**
  94839. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  94840. */
  94841. BouncingBehavior.prototype._clearAnimationLocks = function () {
  94842. this._radiusIsAnimating = false;
  94843. if (this._attachedCamera) {
  94844. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  94845. }
  94846. };
  94847. /**
  94848. * Stops and removes all animations that have been applied to the camera
  94849. */
  94850. BouncingBehavior.prototype.stopAllAnimations = function () {
  94851. if (this._attachedCamera) {
  94852. this._attachedCamera.animations = [];
  94853. }
  94854. while (this._animatables.length) {
  94855. this._animatables[0].onAnimationEnd = null;
  94856. this._animatables[0].stop();
  94857. this._animatables.shift();
  94858. }
  94859. };
  94860. /**
  94861. * The easing function used by animations
  94862. */
  94863. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  94864. /**
  94865. * The easing mode used by animations
  94866. */
  94867. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  94868. return BouncingBehavior;
  94869. }());
  94870. BABYLON.BouncingBehavior = BouncingBehavior;
  94871. })(BABYLON || (BABYLON = {}));
  94872. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  94873. var BABYLON;
  94874. (function (BABYLON) {
  94875. var AutoRotationBehavior = /** @class */ (function () {
  94876. function AutoRotationBehavior() {
  94877. this._zoomStopsAnimation = false;
  94878. this._idleRotationSpeed = 0.05;
  94879. this._idleRotationWaitTime = 2000;
  94880. this._idleRotationSpinupTime = 2000;
  94881. this._isPointerDown = false;
  94882. this._lastFrameTime = null;
  94883. this._lastInteractionTime = -Infinity;
  94884. this._cameraRotationSpeed = 0;
  94885. this._lastFrameRadius = 0;
  94886. }
  94887. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  94888. get: function () {
  94889. return "AutoRotation";
  94890. },
  94891. enumerable: true,
  94892. configurable: true
  94893. });
  94894. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  94895. /**
  94896. * Gets the flag that indicates if user zooming should stop animation.
  94897. */
  94898. get: function () {
  94899. return this._zoomStopsAnimation;
  94900. },
  94901. /**
  94902. * Sets the flag that indicates if user zooming should stop animation.
  94903. */
  94904. set: function (flag) {
  94905. this._zoomStopsAnimation = flag;
  94906. },
  94907. enumerable: true,
  94908. configurable: true
  94909. });
  94910. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  94911. /**
  94912. * Gets the default speed at which the camera rotates around the model.
  94913. */
  94914. get: function () {
  94915. return this._idleRotationSpeed;
  94916. },
  94917. /**
  94918. * Sets the default speed at which the camera rotates around the model.
  94919. */
  94920. set: function (speed) {
  94921. this._idleRotationSpeed = speed;
  94922. },
  94923. enumerable: true,
  94924. configurable: true
  94925. });
  94926. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  94927. /**
  94928. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  94929. */
  94930. get: function () {
  94931. return this._idleRotationWaitTime;
  94932. },
  94933. /**
  94934. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  94935. */
  94936. set: function (time) {
  94937. this._idleRotationWaitTime = time;
  94938. },
  94939. enumerable: true,
  94940. configurable: true
  94941. });
  94942. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  94943. /**
  94944. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94945. */
  94946. get: function () {
  94947. return this._idleRotationSpinupTime;
  94948. },
  94949. /**
  94950. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  94951. */
  94952. set: function (time) {
  94953. this._idleRotationSpinupTime = time;
  94954. },
  94955. enumerable: true,
  94956. configurable: true
  94957. });
  94958. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  94959. /**
  94960. * Gets a value indicating if the camera is currently rotating because of this behavior
  94961. */
  94962. get: function () {
  94963. return Math.abs(this._cameraRotationSpeed) > 0;
  94964. },
  94965. enumerable: true,
  94966. configurable: true
  94967. });
  94968. AutoRotationBehavior.prototype.init = function () {
  94969. // Do notihng
  94970. };
  94971. AutoRotationBehavior.prototype.attach = function (camera) {
  94972. var _this = this;
  94973. this._attachedCamera = camera;
  94974. var scene = this._attachedCamera.getScene();
  94975. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  94976. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  94977. _this._isPointerDown = true;
  94978. return;
  94979. }
  94980. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  94981. _this._isPointerDown = false;
  94982. }
  94983. });
  94984. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  94985. var now = BABYLON.Tools.Now;
  94986. var dt = 0;
  94987. if (_this._lastFrameTime != null) {
  94988. dt = now - _this._lastFrameTime;
  94989. }
  94990. _this._lastFrameTime = now;
  94991. // Stop the animation if there is user interaction and the animation should stop for this interaction
  94992. _this._applyUserInteraction();
  94993. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  94994. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  94995. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  94996. // Step camera rotation by rotation speed
  94997. if (_this._attachedCamera) {
  94998. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  94999. }
  95000. });
  95001. };
  95002. AutoRotationBehavior.prototype.detach = function () {
  95003. if (!this._attachedCamera) {
  95004. return;
  95005. }
  95006. var scene = this._attachedCamera.getScene();
  95007. if (this._onPrePointerObservableObserver) {
  95008. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  95009. }
  95010. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  95011. this._attachedCamera = null;
  95012. };
  95013. /**
  95014. * Returns true if user is scrolling.
  95015. * @return true if user is scrolling.
  95016. */
  95017. AutoRotationBehavior.prototype._userIsZooming = function () {
  95018. if (!this._attachedCamera) {
  95019. return false;
  95020. }
  95021. return this._attachedCamera.inertialRadiusOffset !== 0;
  95022. };
  95023. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  95024. if (!this._attachedCamera) {
  95025. return false;
  95026. }
  95027. var zoomHasHitLimit = false;
  95028. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  95029. zoomHasHitLimit = true;
  95030. }
  95031. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  95032. this._lastFrameRadius = this._attachedCamera.radius;
  95033. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  95034. };
  95035. /**
  95036. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  95037. */
  95038. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  95039. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  95040. this._lastInteractionTime = BABYLON.Tools.Now;
  95041. }
  95042. };
  95043. // Tools
  95044. AutoRotationBehavior.prototype._userIsMoving = function () {
  95045. if (!this._attachedCamera) {
  95046. return false;
  95047. }
  95048. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  95049. this._attachedCamera.inertialBetaOffset !== 0 ||
  95050. this._attachedCamera.inertialRadiusOffset !== 0 ||
  95051. this._attachedCamera.inertialPanningX !== 0 ||
  95052. this._attachedCamera.inertialPanningY !== 0 ||
  95053. this._isPointerDown;
  95054. };
  95055. return AutoRotationBehavior;
  95056. }());
  95057. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  95058. })(BABYLON || (BABYLON = {}));
  95059. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  95060. var BABYLON;
  95061. (function (BABYLON) {
  95062. var NullEngineOptions = /** @class */ (function () {
  95063. function NullEngineOptions() {
  95064. this.renderWidth = 512;
  95065. this.renderHeight = 256;
  95066. this.textureSize = 512;
  95067. this.deterministicLockstep = false;
  95068. this.lockstepMaxSteps = 4;
  95069. }
  95070. return NullEngineOptions;
  95071. }());
  95072. BABYLON.NullEngineOptions = NullEngineOptions;
  95073. /**
  95074. * The null engine class provides support for headless version of babylon.js.
  95075. * This can be used in server side scenario or for testing purposes
  95076. */
  95077. var NullEngine = /** @class */ (function (_super) {
  95078. __extends(NullEngine, _super);
  95079. function NullEngine(options) {
  95080. if (options === void 0) { options = new NullEngineOptions(); }
  95081. var _this = _super.call(this, null) || this;
  95082. if (options.deterministicLockstep === undefined) {
  95083. options.deterministicLockstep = false;
  95084. }
  95085. if (options.lockstepMaxSteps === undefined) {
  95086. options.lockstepMaxSteps = 4;
  95087. }
  95088. _this._options = options;
  95089. // Init caps
  95090. // We consider we are on a webgl1 capable device
  95091. _this._caps = new BABYLON.EngineCapabilities();
  95092. _this._caps.maxTexturesImageUnits = 16;
  95093. _this._caps.maxVertexTextureImageUnits = 16;
  95094. _this._caps.maxTextureSize = 512;
  95095. _this._caps.maxCubemapTextureSize = 512;
  95096. _this._caps.maxRenderTextureSize = 512;
  95097. _this._caps.maxVertexAttribs = 16;
  95098. _this._caps.maxVaryingVectors = 16;
  95099. _this._caps.maxFragmentUniformVectors = 16;
  95100. _this._caps.maxVertexUniformVectors = 16;
  95101. // Extensions
  95102. _this._caps.standardDerivatives = false;
  95103. _this._caps.astc = null;
  95104. _this._caps.s3tc = null;
  95105. _this._caps.pvrtc = null;
  95106. _this._caps.etc1 = null;
  95107. _this._caps.etc2 = null;
  95108. _this._caps.textureAnisotropicFilterExtension = null;
  95109. _this._caps.maxAnisotropy = 0;
  95110. _this._caps.uintIndices = false;
  95111. _this._caps.fragmentDepthSupported = false;
  95112. _this._caps.highPrecisionShaderSupported = true;
  95113. _this._caps.colorBufferFloat = false;
  95114. _this._caps.textureFloat = false;
  95115. _this._caps.textureFloatLinearFiltering = false;
  95116. _this._caps.textureFloatRender = false;
  95117. _this._caps.textureHalfFloat = false;
  95118. _this._caps.textureHalfFloatLinearFiltering = false;
  95119. _this._caps.textureHalfFloatRender = false;
  95120. _this._caps.textureLOD = false;
  95121. _this._caps.drawBuffersExtension = false;
  95122. _this._caps.depthTextureExtension = false;
  95123. _this._caps.vertexArrayObject = false;
  95124. _this._caps.instancedArrays = false;
  95125. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  95126. // Wrappers
  95127. if (typeof URL === "undefined") {
  95128. URL = {
  95129. createObjectURL: function () { },
  95130. revokeObjectURL: function () { }
  95131. };
  95132. }
  95133. if (typeof Blob === "undefined") {
  95134. Blob = function () { };
  95135. }
  95136. return _this;
  95137. }
  95138. NullEngine.prototype.isDeterministicLockStep = function () {
  95139. return this._options.deterministicLockstep;
  95140. };
  95141. NullEngine.prototype.getLockstepMaxSteps = function () {
  95142. return this._options.lockstepMaxSteps;
  95143. };
  95144. NullEngine.prototype.getHardwareScalingLevel = function () {
  95145. return 1.0;
  95146. };
  95147. NullEngine.prototype.createVertexBuffer = function (vertices) {
  95148. return {
  95149. capacity: 0,
  95150. references: 1,
  95151. is32Bits: false
  95152. };
  95153. };
  95154. NullEngine.prototype.createIndexBuffer = function (indices) {
  95155. return {
  95156. capacity: 0,
  95157. references: 1,
  95158. is32Bits: false
  95159. };
  95160. };
  95161. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  95162. if (stencil === void 0) { stencil = false; }
  95163. };
  95164. NullEngine.prototype.getRenderWidth = function (useScreen) {
  95165. if (useScreen === void 0) { useScreen = false; }
  95166. if (!useScreen && this._currentRenderTarget) {
  95167. return this._currentRenderTarget.width;
  95168. }
  95169. return this._options.renderWidth;
  95170. };
  95171. NullEngine.prototype.getRenderHeight = function (useScreen) {
  95172. if (useScreen === void 0) { useScreen = false; }
  95173. if (!useScreen && this._currentRenderTarget) {
  95174. return this._currentRenderTarget.height;
  95175. }
  95176. return this._options.renderHeight;
  95177. };
  95178. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  95179. this._cachedViewport = viewport;
  95180. };
  95181. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  95182. return {
  95183. transformFeedback: null,
  95184. __SPECTOR_rebuildProgram: null
  95185. };
  95186. };
  95187. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  95188. return [];
  95189. };
  95190. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  95191. return [];
  95192. };
  95193. NullEngine.prototype.bindSamplers = function (effect) {
  95194. this._currentEffect = null;
  95195. };
  95196. NullEngine.prototype.enableEffect = function (effect) {
  95197. this._currentEffect = effect;
  95198. if (effect.onBind) {
  95199. effect.onBind(effect);
  95200. }
  95201. effect.onBindObservable.notifyObservers(effect);
  95202. };
  95203. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  95204. if (zOffset === void 0) { zOffset = 0; }
  95205. if (reverseSide === void 0) { reverseSide = false; }
  95206. };
  95207. NullEngine.prototype.setIntArray = function (uniform, array) {
  95208. };
  95209. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  95210. };
  95211. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  95212. };
  95213. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  95214. };
  95215. NullEngine.prototype.setFloatArray = function (uniform, array) {
  95216. };
  95217. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  95218. };
  95219. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  95220. };
  95221. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  95222. };
  95223. NullEngine.prototype.setArray = function (uniform, array) {
  95224. };
  95225. NullEngine.prototype.setArray2 = function (uniform, array) {
  95226. };
  95227. NullEngine.prototype.setArray3 = function (uniform, array) {
  95228. };
  95229. NullEngine.prototype.setArray4 = function (uniform, array) {
  95230. };
  95231. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  95232. };
  95233. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  95234. };
  95235. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  95236. };
  95237. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  95238. };
  95239. NullEngine.prototype.setFloat = function (uniform, value) {
  95240. };
  95241. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  95242. };
  95243. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  95244. };
  95245. NullEngine.prototype.setBool = function (uniform, bool) {
  95246. };
  95247. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  95248. };
  95249. NullEngine.prototype.setColor3 = function (uniform, color3) {
  95250. };
  95251. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  95252. };
  95253. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  95254. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  95255. if (this._alphaMode === mode) {
  95256. return;
  95257. }
  95258. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  95259. if (!noDepthWriteChange) {
  95260. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  95261. }
  95262. this._alphaMode = mode;
  95263. };
  95264. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  95265. };
  95266. NullEngine.prototype.wipeCaches = function (bruteForce) {
  95267. if (this.preventCacheWipeBetweenFrames) {
  95268. return;
  95269. }
  95270. this.resetTextureCache();
  95271. this._currentEffect = null;
  95272. if (bruteForce) {
  95273. this._currentProgram = null;
  95274. this._stencilState.reset();
  95275. this._depthCullingState.reset();
  95276. this._alphaState.reset();
  95277. }
  95278. this._cachedVertexBuffers = null;
  95279. this._cachedIndexBuffer = null;
  95280. this._cachedEffectForVertexBuffers = null;
  95281. };
  95282. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  95283. };
  95284. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  95285. };
  95286. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  95287. };
  95288. NullEngine.prototype._createTexture = function () {
  95289. return {};
  95290. };
  95291. NullEngine.prototype._releaseTexture = function (texture) {
  95292. };
  95293. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  95294. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  95295. if (onLoad === void 0) { onLoad = null; }
  95296. if (onError === void 0) { onError = null; }
  95297. if (buffer === void 0) { buffer = null; }
  95298. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  95299. var url = String(urlArg);
  95300. texture.url = url;
  95301. texture.generateMipMaps = !noMipmap;
  95302. texture.samplingMode = samplingMode;
  95303. texture.invertY = invertY;
  95304. texture.baseWidth = this._options.textureSize;
  95305. texture.baseHeight = this._options.textureSize;
  95306. texture.width = this._options.textureSize;
  95307. texture.height = this._options.textureSize;
  95308. if (format) {
  95309. texture.format = format;
  95310. }
  95311. texture.isReady = true;
  95312. if (onLoad) {
  95313. onLoad();
  95314. }
  95315. return texture;
  95316. };
  95317. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  95318. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  95319. if (options !== undefined && typeof options === "object") {
  95320. fullOptions.generateMipMaps = options.generateMipMaps;
  95321. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  95322. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  95323. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  95324. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  95325. }
  95326. else {
  95327. fullOptions.generateMipMaps = options;
  95328. fullOptions.generateDepthBuffer = true;
  95329. fullOptions.generateStencilBuffer = false;
  95330. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  95331. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  95332. }
  95333. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  95334. var width = size.width || size;
  95335. var height = size.height || size;
  95336. texture._depthStencilBuffer = {};
  95337. texture._framebuffer = {};
  95338. texture.baseWidth = width;
  95339. texture.baseHeight = height;
  95340. texture.width = width;
  95341. texture.height = height;
  95342. texture.isReady = true;
  95343. texture.samples = 1;
  95344. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  95345. texture.samplingMode = fullOptions.samplingMode;
  95346. texture.type = fullOptions.type;
  95347. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  95348. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  95349. return texture;
  95350. };
  95351. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  95352. texture.samplingMode = samplingMode;
  95353. };
  95354. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  95355. if (this._currentRenderTarget) {
  95356. this.unBindFramebuffer(this._currentRenderTarget);
  95357. }
  95358. this._currentRenderTarget = texture;
  95359. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  95360. if (this._cachedViewport && !forceFullscreenViewport) {
  95361. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  95362. }
  95363. };
  95364. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  95365. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  95366. this._currentRenderTarget = null;
  95367. if (onBeforeUnbind) {
  95368. if (texture._MSAAFramebuffer) {
  95369. this._currentFramebuffer = texture._framebuffer;
  95370. }
  95371. onBeforeUnbind();
  95372. }
  95373. this._currentFramebuffer = null;
  95374. };
  95375. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  95376. var vbo = {
  95377. capacity: 1,
  95378. references: 1,
  95379. is32Bits: false
  95380. };
  95381. return vbo;
  95382. };
  95383. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  95384. if (offset === void 0) { offset = 0; }
  95385. };
  95386. /**
  95387. * Updates a dynamic vertex buffer.
  95388. * @param vertexBuffer the vertex buffer to update
  95389. * @param data the data used to update the vertex buffer
  95390. * @param byteOffset the byte offset of the data (optional)
  95391. * @param byteLength the byte length of the data (optional)
  95392. */
  95393. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  95394. };
  95395. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  95396. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  95397. this._boundTexturesCache[this._activeChannel] = texture;
  95398. }
  95399. };
  95400. NullEngine.prototype._bindTexture = function (channel, texture) {
  95401. if (channel < 0) {
  95402. return;
  95403. }
  95404. this._bindTextureDirectly(0, texture);
  95405. };
  95406. NullEngine.prototype._releaseBuffer = function (buffer) {
  95407. buffer.references--;
  95408. if (buffer.references === 0) {
  95409. return true;
  95410. }
  95411. return false;
  95412. };
  95413. NullEngine.prototype.releaseEffects = function () {
  95414. };
  95415. return NullEngine;
  95416. }(BABYLON.Engine));
  95417. BABYLON.NullEngine = NullEngine;
  95418. })(BABYLON || (BABYLON = {}));
  95419. //# sourceMappingURL=babylon.nullEngine.js.map
  95420. var BABYLON;
  95421. (function (BABYLON) {
  95422. /**
  95423. * This class can be used to get instrumentation data from a Babylon engine
  95424. */
  95425. var EngineInstrumentation = /** @class */ (function () {
  95426. function EngineInstrumentation(engine) {
  95427. this.engine = engine;
  95428. this._captureGPUFrameTime = false;
  95429. this._gpuFrameTime = new BABYLON.PerfCounter();
  95430. this._captureShaderCompilationTime = false;
  95431. this._shaderCompilationTime = new BABYLON.PerfCounter();
  95432. // Observers
  95433. this._onBeginFrameObserver = null;
  95434. this._onEndFrameObserver = null;
  95435. this._onBeforeShaderCompilationObserver = null;
  95436. this._onAfterShaderCompilationObserver = null;
  95437. }
  95438. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  95439. // Properties
  95440. /**
  95441. * Gets the perf counter used for GPU frame time
  95442. */
  95443. get: function () {
  95444. return this._gpuFrameTime;
  95445. },
  95446. enumerable: true,
  95447. configurable: true
  95448. });
  95449. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  95450. /**
  95451. * Gets the GPU frame time capture status
  95452. */
  95453. get: function () {
  95454. return this._captureGPUFrameTime;
  95455. },
  95456. /**
  95457. * Enable or disable the GPU frame time capture
  95458. */
  95459. set: function (value) {
  95460. var _this = this;
  95461. if (value === this._captureGPUFrameTime) {
  95462. return;
  95463. }
  95464. this._captureGPUFrameTime = value;
  95465. if (value) {
  95466. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  95467. if (!_this._gpuFrameTimeToken) {
  95468. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  95469. }
  95470. });
  95471. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  95472. if (!_this._gpuFrameTimeToken) {
  95473. return;
  95474. }
  95475. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  95476. if (time > -1) {
  95477. _this._gpuFrameTimeToken = null;
  95478. _this._gpuFrameTime.fetchNewFrame();
  95479. _this._gpuFrameTime.addCount(time, true);
  95480. }
  95481. });
  95482. }
  95483. else {
  95484. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95485. this._onBeginFrameObserver = null;
  95486. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95487. this._onEndFrameObserver = null;
  95488. }
  95489. },
  95490. enumerable: true,
  95491. configurable: true
  95492. });
  95493. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  95494. /**
  95495. * Gets the perf counter used for shader compilation time
  95496. */
  95497. get: function () {
  95498. return this._shaderCompilationTime;
  95499. },
  95500. enumerable: true,
  95501. configurable: true
  95502. });
  95503. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  95504. /**
  95505. * Gets the shader compilation time capture status
  95506. */
  95507. get: function () {
  95508. return this._captureShaderCompilationTime;
  95509. },
  95510. /**
  95511. * Enable or disable the shader compilation time capture
  95512. */
  95513. set: function (value) {
  95514. var _this = this;
  95515. if (value === this._captureShaderCompilationTime) {
  95516. return;
  95517. }
  95518. this._captureShaderCompilationTime = value;
  95519. if (value) {
  95520. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  95521. _this._shaderCompilationTime.fetchNewFrame();
  95522. _this._shaderCompilationTime.beginMonitoring();
  95523. });
  95524. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  95525. _this._shaderCompilationTime.endMonitoring();
  95526. });
  95527. }
  95528. else {
  95529. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95530. this._onBeforeShaderCompilationObserver = null;
  95531. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95532. this._onAfterShaderCompilationObserver = null;
  95533. }
  95534. },
  95535. enumerable: true,
  95536. configurable: true
  95537. });
  95538. EngineInstrumentation.prototype.dispose = function () {
  95539. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  95540. this._onBeginFrameObserver = null;
  95541. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  95542. this._onEndFrameObserver = null;
  95543. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  95544. this._onBeforeShaderCompilationObserver = null;
  95545. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  95546. this._onAfterShaderCompilationObserver = null;
  95547. this.engine = null;
  95548. };
  95549. return EngineInstrumentation;
  95550. }());
  95551. BABYLON.EngineInstrumentation = EngineInstrumentation;
  95552. })(BABYLON || (BABYLON = {}));
  95553. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  95554. var BABYLON;
  95555. (function (BABYLON) {
  95556. /**
  95557. * This class can be used to get instrumentation data from a Babylon engine
  95558. */
  95559. var SceneInstrumentation = /** @class */ (function () {
  95560. function SceneInstrumentation(scene) {
  95561. var _this = this;
  95562. this.scene = scene;
  95563. this._captureActiveMeshesEvaluationTime = false;
  95564. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  95565. this._captureRenderTargetsRenderTime = false;
  95566. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  95567. this._captureFrameTime = false;
  95568. this._frameTime = new BABYLON.PerfCounter();
  95569. this._captureRenderTime = false;
  95570. this._renderTime = new BABYLON.PerfCounter();
  95571. this._captureInterFrameTime = false;
  95572. this._interFrameTime = new BABYLON.PerfCounter();
  95573. this._captureParticlesRenderTime = false;
  95574. this._particlesRenderTime = new BABYLON.PerfCounter();
  95575. this._captureSpritesRenderTime = false;
  95576. this._spritesRenderTime = new BABYLON.PerfCounter();
  95577. this._capturePhysicsTime = false;
  95578. this._physicsTime = new BABYLON.PerfCounter();
  95579. this._captureAnimationsTime = false;
  95580. this._animationsTime = new BABYLON.PerfCounter();
  95581. // Observers
  95582. this._onBeforeActiveMeshesEvaluationObserver = null;
  95583. this._onAfterActiveMeshesEvaluationObserver = null;
  95584. this._onBeforeRenderTargetsRenderObserver = null;
  95585. this._onAfterRenderTargetsRenderObserver = null;
  95586. this._onAfterRenderObserver = null;
  95587. this._onBeforeDrawPhaseObserver = null;
  95588. this._onAfterDrawPhaseObserver = null;
  95589. this._onBeforeAnimationsObserver = null;
  95590. this._onBeforeParticlesRenderingObserver = null;
  95591. this._onAfterParticlesRenderingObserver = null;
  95592. this._onBeforeSpritesRenderingObserver = null;
  95593. this._onAfterSpritesRenderingObserver = null;
  95594. this._onBeforePhysicsObserver = null;
  95595. this._onAfterPhysicsObserver = null;
  95596. this._onAfterAnimationsObserver = null;
  95597. // Before render
  95598. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  95599. if (_this._captureActiveMeshesEvaluationTime) {
  95600. _this._activeMeshesEvaluationTime.fetchNewFrame();
  95601. }
  95602. if (_this._captureRenderTargetsRenderTime) {
  95603. _this._renderTargetsRenderTime.fetchNewFrame();
  95604. }
  95605. if (_this._captureFrameTime) {
  95606. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  95607. _this._frameTime.beginMonitoring();
  95608. }
  95609. if (_this._captureInterFrameTime) {
  95610. _this._interFrameTime.endMonitoring();
  95611. }
  95612. if (_this._captureParticlesRenderTime) {
  95613. _this._particlesRenderTime.fetchNewFrame();
  95614. }
  95615. if (_this._captureSpritesRenderTime) {
  95616. _this._spritesRenderTime.fetchNewFrame();
  95617. }
  95618. if (_this._captureAnimationsTime) {
  95619. _this._animationsTime.beginMonitoring();
  95620. }
  95621. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  95622. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  95623. });
  95624. // After render
  95625. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  95626. if (_this._captureFrameTime) {
  95627. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  95628. _this._frameTime.endMonitoring();
  95629. }
  95630. if (_this._captureRenderTime) {
  95631. _this._renderTime.endMonitoring(false);
  95632. }
  95633. if (_this._captureInterFrameTime) {
  95634. _this._interFrameTime.beginMonitoring();
  95635. }
  95636. });
  95637. }
  95638. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  95639. // Properties
  95640. /**
  95641. * Gets the perf counter used for active meshes evaluation time
  95642. */
  95643. get: function () {
  95644. return this._activeMeshesEvaluationTime;
  95645. },
  95646. enumerable: true,
  95647. configurable: true
  95648. });
  95649. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  95650. /**
  95651. * Gets the active meshes evaluation time capture status
  95652. */
  95653. get: function () {
  95654. return this._captureActiveMeshesEvaluationTime;
  95655. },
  95656. /**
  95657. * Enable or disable the active meshes evaluation time capture
  95658. */
  95659. set: function (value) {
  95660. var _this = this;
  95661. if (value === this._captureActiveMeshesEvaluationTime) {
  95662. return;
  95663. }
  95664. this._captureActiveMeshesEvaluationTime = value;
  95665. if (value) {
  95666. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  95667. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  95668. _this._activeMeshesEvaluationTime.beginMonitoring();
  95669. });
  95670. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  95671. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  95672. _this._activeMeshesEvaluationTime.endMonitoring();
  95673. });
  95674. }
  95675. else {
  95676. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  95677. this._onBeforeActiveMeshesEvaluationObserver = null;
  95678. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  95679. this._onAfterActiveMeshesEvaluationObserver = null;
  95680. }
  95681. },
  95682. enumerable: true,
  95683. configurable: true
  95684. });
  95685. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  95686. /**
  95687. * Gets the perf counter used for render targets render time
  95688. */
  95689. get: function () {
  95690. return this._renderTargetsRenderTime;
  95691. },
  95692. enumerable: true,
  95693. configurable: true
  95694. });
  95695. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  95696. /**
  95697. * Gets the render targets render time capture status
  95698. */
  95699. get: function () {
  95700. return this._captureRenderTargetsRenderTime;
  95701. },
  95702. /**
  95703. * Enable or disable the render targets render time capture
  95704. */
  95705. set: function (value) {
  95706. var _this = this;
  95707. if (value === this._captureRenderTargetsRenderTime) {
  95708. return;
  95709. }
  95710. this._captureRenderTargetsRenderTime = value;
  95711. if (value) {
  95712. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  95713. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  95714. _this._renderTargetsRenderTime.beginMonitoring();
  95715. });
  95716. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  95717. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  95718. _this._renderTargetsRenderTime.endMonitoring(false);
  95719. });
  95720. }
  95721. else {
  95722. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  95723. this._onBeforeRenderTargetsRenderObserver = null;
  95724. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  95725. this._onAfterRenderTargetsRenderObserver = null;
  95726. }
  95727. },
  95728. enumerable: true,
  95729. configurable: true
  95730. });
  95731. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  95732. /**
  95733. * Gets the perf counter used for particles render time
  95734. */
  95735. get: function () {
  95736. return this._particlesRenderTime;
  95737. },
  95738. enumerable: true,
  95739. configurable: true
  95740. });
  95741. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  95742. /**
  95743. * Gets the particles render time capture status
  95744. */
  95745. get: function () {
  95746. return this._captureParticlesRenderTime;
  95747. },
  95748. /**
  95749. * Enable or disable the particles render time capture
  95750. */
  95751. set: function (value) {
  95752. var _this = this;
  95753. if (value === this._captureParticlesRenderTime) {
  95754. return;
  95755. }
  95756. this._captureParticlesRenderTime = value;
  95757. if (value) {
  95758. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  95759. BABYLON.Tools.StartPerformanceCounter("Particles");
  95760. _this._particlesRenderTime.beginMonitoring();
  95761. });
  95762. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  95763. BABYLON.Tools.EndPerformanceCounter("Particles");
  95764. _this._particlesRenderTime.endMonitoring(false);
  95765. });
  95766. }
  95767. else {
  95768. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  95769. this._onBeforeParticlesRenderingObserver = null;
  95770. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  95771. this._onAfterParticlesRenderingObserver = null;
  95772. }
  95773. },
  95774. enumerable: true,
  95775. configurable: true
  95776. });
  95777. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  95778. /**
  95779. * Gets the perf counter used for sprites render time
  95780. */
  95781. get: function () {
  95782. return this._spritesRenderTime;
  95783. },
  95784. enumerable: true,
  95785. configurable: true
  95786. });
  95787. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  95788. /**
  95789. * Gets the sprites render time capture status
  95790. */
  95791. get: function () {
  95792. return this._captureSpritesRenderTime;
  95793. },
  95794. /**
  95795. * Enable or disable the sprites render time capture
  95796. */
  95797. set: function (value) {
  95798. var _this = this;
  95799. if (value === this._captureSpritesRenderTime) {
  95800. return;
  95801. }
  95802. this._captureSpritesRenderTime = value;
  95803. if (value) {
  95804. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  95805. BABYLON.Tools.StartPerformanceCounter("Sprites");
  95806. _this._spritesRenderTime.beginMonitoring();
  95807. });
  95808. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  95809. BABYLON.Tools.EndPerformanceCounter("Sprites");
  95810. _this._spritesRenderTime.endMonitoring(false);
  95811. });
  95812. }
  95813. else {
  95814. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  95815. this._onBeforeSpritesRenderingObserver = null;
  95816. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  95817. this._onAfterSpritesRenderingObserver = null;
  95818. }
  95819. },
  95820. enumerable: true,
  95821. configurable: true
  95822. });
  95823. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  95824. /**
  95825. * Gets the perf counter used for physics time
  95826. */
  95827. get: function () {
  95828. return this._physicsTime;
  95829. },
  95830. enumerable: true,
  95831. configurable: true
  95832. });
  95833. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  95834. /**
  95835. * Gets the physics time capture status
  95836. */
  95837. get: function () {
  95838. return this._capturePhysicsTime;
  95839. },
  95840. /**
  95841. * Enable or disable the physics time capture
  95842. */
  95843. set: function (value) {
  95844. var _this = this;
  95845. if (value === this._capturePhysicsTime) {
  95846. return;
  95847. }
  95848. this._capturePhysicsTime = value;
  95849. if (value) {
  95850. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  95851. BABYLON.Tools.StartPerformanceCounter("Physics");
  95852. _this._physicsTime.beginMonitoring();
  95853. });
  95854. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  95855. BABYLON.Tools.EndPerformanceCounter("Physics");
  95856. _this._physicsTime.endMonitoring();
  95857. });
  95858. }
  95859. else {
  95860. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  95861. this._onBeforePhysicsObserver = null;
  95862. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  95863. this._onAfterPhysicsObserver = null;
  95864. }
  95865. },
  95866. enumerable: true,
  95867. configurable: true
  95868. });
  95869. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  95870. /**
  95871. * Gets the perf counter used for animations time
  95872. */
  95873. get: function () {
  95874. return this._animationsTime;
  95875. },
  95876. enumerable: true,
  95877. configurable: true
  95878. });
  95879. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  95880. /**
  95881. * Gets the animations time capture status
  95882. */
  95883. get: function () {
  95884. return this._captureAnimationsTime;
  95885. },
  95886. /**
  95887. * Enable or disable the animations time capture
  95888. */
  95889. set: function (value) {
  95890. var _this = this;
  95891. if (value === this._captureAnimationsTime) {
  95892. return;
  95893. }
  95894. this._captureAnimationsTime = value;
  95895. if (value) {
  95896. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  95897. _this._animationsTime.endMonitoring();
  95898. });
  95899. }
  95900. else {
  95901. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  95902. this._onAfterAnimationsObserver = null;
  95903. }
  95904. },
  95905. enumerable: true,
  95906. configurable: true
  95907. });
  95908. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  95909. /**
  95910. * Gets the perf counter used for frame time capture
  95911. */
  95912. get: function () {
  95913. return this._frameTime;
  95914. },
  95915. enumerable: true,
  95916. configurable: true
  95917. });
  95918. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  95919. /**
  95920. * Gets the frame time capture status
  95921. */
  95922. get: function () {
  95923. return this._captureFrameTime;
  95924. },
  95925. /**
  95926. * Enable or disable the frame time capture
  95927. */
  95928. set: function (value) {
  95929. this._captureFrameTime = value;
  95930. },
  95931. enumerable: true,
  95932. configurable: true
  95933. });
  95934. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  95935. /**
  95936. * Gets the perf counter used for inter-frames time capture
  95937. */
  95938. get: function () {
  95939. return this._interFrameTime;
  95940. },
  95941. enumerable: true,
  95942. configurable: true
  95943. });
  95944. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  95945. /**
  95946. * Gets the inter-frames time capture status
  95947. */
  95948. get: function () {
  95949. return this._captureInterFrameTime;
  95950. },
  95951. /**
  95952. * Enable or disable the inter-frames time capture
  95953. */
  95954. set: function (value) {
  95955. this._captureInterFrameTime = value;
  95956. },
  95957. enumerable: true,
  95958. configurable: true
  95959. });
  95960. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  95961. /**
  95962. * Gets the perf counter used for render time capture
  95963. */
  95964. get: function () {
  95965. return this._renderTime;
  95966. },
  95967. enumerable: true,
  95968. configurable: true
  95969. });
  95970. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  95971. /**
  95972. * Gets the render time capture status
  95973. */
  95974. get: function () {
  95975. return this._captureRenderTime;
  95976. },
  95977. /**
  95978. * Enable or disable the render time capture
  95979. */
  95980. set: function (value) {
  95981. var _this = this;
  95982. if (value === this._captureRenderTime) {
  95983. return;
  95984. }
  95985. this._captureRenderTime = value;
  95986. if (value) {
  95987. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  95988. _this._renderTime.beginMonitoring();
  95989. BABYLON.Tools.StartPerformanceCounter("Main render");
  95990. });
  95991. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  95992. _this._renderTime.endMonitoring(false);
  95993. BABYLON.Tools.EndPerformanceCounter("Main render");
  95994. });
  95995. }
  95996. else {
  95997. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  95998. this._onBeforeDrawPhaseObserver = null;
  95999. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96000. this._onAfterDrawPhaseObserver = null;
  96001. }
  96002. },
  96003. enumerable: true,
  96004. configurable: true
  96005. });
  96006. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  96007. /**
  96008. * Gets the perf counter used for draw calls
  96009. */
  96010. get: function () {
  96011. return this.scene.getEngine()._drawCalls;
  96012. },
  96013. enumerable: true,
  96014. configurable: true
  96015. });
  96016. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  96017. /**
  96018. * Gets the perf counter used for texture collisions
  96019. */
  96020. get: function () {
  96021. return this.scene.getEngine()._textureCollisions;
  96022. },
  96023. enumerable: true,
  96024. configurable: true
  96025. });
  96026. SceneInstrumentation.prototype.dispose = function () {
  96027. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  96028. this._onAfterRenderObserver = null;
  96029. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  96030. this._onBeforeActiveMeshesEvaluationObserver = null;
  96031. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  96032. this._onAfterActiveMeshesEvaluationObserver = null;
  96033. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  96034. this._onBeforeRenderTargetsRenderObserver = null;
  96035. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  96036. this._onAfterRenderTargetsRenderObserver = null;
  96037. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  96038. this._onBeforeAnimationsObserver = null;
  96039. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  96040. this._onBeforeParticlesRenderingObserver = null;
  96041. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  96042. this._onAfterParticlesRenderingObserver = null;
  96043. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  96044. this._onBeforeSpritesRenderingObserver = null;
  96045. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  96046. this._onAfterSpritesRenderingObserver = null;
  96047. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  96048. this._onBeforeDrawPhaseObserver = null;
  96049. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  96050. this._onAfterDrawPhaseObserver = null;
  96051. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  96052. this._onBeforePhysicsObserver = null;
  96053. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  96054. this._onAfterPhysicsObserver = null;
  96055. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  96056. this._onAfterAnimationsObserver = null;
  96057. this.scene = null;
  96058. };
  96059. return SceneInstrumentation;
  96060. }());
  96061. BABYLON.SceneInstrumentation = SceneInstrumentation;
  96062. })(BABYLON || (BABYLON = {}));
  96063. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  96064. var BABYLON;
  96065. (function (BABYLON) {
  96066. /**
  96067. * @hidden
  96068. **/
  96069. var _TimeToken = /** @class */ (function () {
  96070. function _TimeToken() {
  96071. this._timeElapsedQueryEnded = false;
  96072. }
  96073. return _TimeToken;
  96074. }());
  96075. BABYLON._TimeToken = _TimeToken;
  96076. })(BABYLON || (BABYLON = {}));
  96077. //# sourceMappingURL=babylon.timeToken.js.map
  96078. var BABYLON;
  96079. (function (BABYLON) {
  96080. /**
  96081. * Background material defines definition.
  96082. * @hidden Mainly internal Use
  96083. */
  96084. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  96085. __extends(BackgroundMaterialDefines, _super);
  96086. /**
  96087. * Constructor of the defines.
  96088. */
  96089. function BackgroundMaterialDefines() {
  96090. var _this = _super.call(this) || this;
  96091. /**
  96092. * True if the diffuse texture is in use.
  96093. */
  96094. _this.DIFFUSE = false;
  96095. /**
  96096. * The direct UV channel to use.
  96097. */
  96098. _this.DIFFUSEDIRECTUV = 0;
  96099. /**
  96100. * True if the diffuse texture is in gamma space.
  96101. */
  96102. _this.GAMMADIFFUSE = false;
  96103. /**
  96104. * True if the diffuse texture has opacity in the alpha channel.
  96105. */
  96106. _this.DIFFUSEHASALPHA = false;
  96107. /**
  96108. * True if you want the material to fade to transparent at grazing angle.
  96109. */
  96110. _this.OPACITYFRESNEL = false;
  96111. /**
  96112. * True if an extra blur needs to be added in the reflection.
  96113. */
  96114. _this.REFLECTIONBLUR = false;
  96115. /**
  96116. * True if you want the material to fade to reflection at grazing angle.
  96117. */
  96118. _this.REFLECTIONFRESNEL = false;
  96119. /**
  96120. * True if you want the material to falloff as far as you move away from the scene center.
  96121. */
  96122. _this.REFLECTIONFALLOFF = false;
  96123. /**
  96124. * False if the current Webgl implementation does not support the texture lod extension.
  96125. */
  96126. _this.TEXTURELODSUPPORT = false;
  96127. /**
  96128. * True to ensure the data are premultiplied.
  96129. */
  96130. _this.PREMULTIPLYALPHA = false;
  96131. /**
  96132. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  96133. */
  96134. _this.USERGBCOLOR = false;
  96135. /**
  96136. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  96137. * stays aligned with the desired configuration.
  96138. */
  96139. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  96140. /**
  96141. * True to add noise in order to reduce the banding effect.
  96142. */
  96143. _this.NOISE = false;
  96144. /**
  96145. * is the reflection texture in BGR color scheme?
  96146. * Mainly used to solve a bug in ios10 video tag
  96147. */
  96148. _this.REFLECTIONBGR = false;
  96149. _this.IMAGEPROCESSING = false;
  96150. _this.VIGNETTE = false;
  96151. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  96152. _this.VIGNETTEBLENDMODEOPAQUE = false;
  96153. _this.TONEMAPPING = false;
  96154. _this.CONTRAST = false;
  96155. _this.COLORCURVES = false;
  96156. _this.COLORGRADING = false;
  96157. _this.COLORGRADING3D = false;
  96158. _this.SAMPLER3DGREENDEPTH = false;
  96159. _this.SAMPLER3DBGRMAP = false;
  96160. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  96161. _this.EXPOSURE = false;
  96162. // Reflection.
  96163. _this.REFLECTION = false;
  96164. _this.REFLECTIONMAP_3D = false;
  96165. _this.REFLECTIONMAP_SPHERICAL = false;
  96166. _this.REFLECTIONMAP_PLANAR = false;
  96167. _this.REFLECTIONMAP_CUBIC = false;
  96168. _this.REFLECTIONMAP_PROJECTION = false;
  96169. _this.REFLECTIONMAP_SKYBOX = false;
  96170. _this.REFLECTIONMAP_EXPLICIT = false;
  96171. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96172. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96173. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96174. _this.INVERTCUBICMAP = false;
  96175. _this.REFLECTIONMAP_OPPOSITEZ = false;
  96176. _this.LODINREFLECTIONALPHA = false;
  96177. _this.GAMMAREFLECTION = false;
  96178. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  96179. // Default BJS.
  96180. _this.MAINUV1 = false;
  96181. _this.MAINUV2 = false;
  96182. _this.UV1 = false;
  96183. _this.UV2 = false;
  96184. _this.CLIPPLANE = false;
  96185. _this.POINTSIZE = false;
  96186. _this.FOG = false;
  96187. _this.NORMAL = false;
  96188. _this.NUM_BONE_INFLUENCERS = 0;
  96189. _this.BonesPerMesh = 0;
  96190. _this.INSTANCES = false;
  96191. _this.SHADOWFLOAT = false;
  96192. _this.rebuild();
  96193. return _this;
  96194. }
  96195. return BackgroundMaterialDefines;
  96196. }(BABYLON.MaterialDefines));
  96197. /**
  96198. * Background material used to create an efficient environement around your scene.
  96199. */
  96200. var BackgroundMaterial = /** @class */ (function (_super) {
  96201. __extends(BackgroundMaterial, _super);
  96202. /**
  96203. * Instantiates a Background Material in the given scene
  96204. * @param name The friendly name of the material
  96205. * @param scene The scene to add the material to
  96206. */
  96207. function BackgroundMaterial(name, scene) {
  96208. var _this = _super.call(this, name, scene) || this;
  96209. /**
  96210. * Key light Color (multiply against the environement texture)
  96211. */
  96212. _this.primaryColor = BABYLON.Color3.White();
  96213. _this._primaryColorShadowLevel = 0;
  96214. _this._primaryColorHighlightLevel = 0;
  96215. /**
  96216. * Reflection Texture used in the material.
  96217. * Should be author in a specific way for the best result (refer to the documentation).
  96218. */
  96219. _this.reflectionTexture = null;
  96220. /**
  96221. * Reflection Texture level of blur.
  96222. *
  96223. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  96224. * texture twice.
  96225. */
  96226. _this.reflectionBlur = 0;
  96227. /**
  96228. * Diffuse Texture used in the material.
  96229. * Should be author in a specific way for the best result (refer to the documentation).
  96230. */
  96231. _this.diffuseTexture = null;
  96232. _this._shadowLights = null;
  96233. /**
  96234. * Specify the list of lights casting shadow on the material.
  96235. * All scene shadow lights will be included if null.
  96236. */
  96237. _this.shadowLights = null;
  96238. /**
  96239. * Helps adjusting the shadow to a softer level if required.
  96240. * 0 means black shadows and 1 means no shadows.
  96241. */
  96242. _this.shadowLevel = 0;
  96243. /**
  96244. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  96245. * It is usually zero but might be interesting to modify according to your setup.
  96246. */
  96247. _this.sceneCenter = BABYLON.Vector3.Zero();
  96248. /**
  96249. * This helps specifying that the material is falling off to the sky box at grazing angle.
  96250. * This helps ensuring a nice transition when the camera goes under the ground.
  96251. */
  96252. _this.opacityFresnel = true;
  96253. /**
  96254. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  96255. * This helps adding a mirror texture on the ground.
  96256. */
  96257. _this.reflectionFresnel = false;
  96258. /**
  96259. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  96260. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  96261. */
  96262. _this.reflectionFalloffDistance = 0.0;
  96263. /**
  96264. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  96265. */
  96266. _this.reflectionAmount = 1.0;
  96267. /**
  96268. * This specifies the weight of the reflection at grazing angle.
  96269. */
  96270. _this.reflectionReflectance0 = 0.05;
  96271. /**
  96272. * This specifies the weight of the reflection at a perpendicular point of view.
  96273. */
  96274. _this.reflectionReflectance90 = 0.5;
  96275. /**
  96276. * Helps to directly use the maps channels instead of their level.
  96277. */
  96278. _this.useRGBColor = true;
  96279. /**
  96280. * This helps reducing the banding effect that could occur on the background.
  96281. */
  96282. _this.enableNoise = false;
  96283. _this._fovMultiplier = 1.0;
  96284. /**
  96285. * Enable the FOV adjustment feature controlled by fovMultiplier.
  96286. */
  96287. _this.useEquirectangularFOV = false;
  96288. _this._maxSimultaneousLights = 4;
  96289. /**
  96290. * Number of Simultaneous lights allowed on the material.
  96291. */
  96292. _this.maxSimultaneousLights = 4;
  96293. /**
  96294. * Keep track of the image processing observer to allow dispose and replace.
  96295. */
  96296. _this._imageProcessingObserver = null;
  96297. /**
  96298. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  96299. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  96300. */
  96301. _this.switchToBGR = false;
  96302. // Temp values kept as cache in the material.
  96303. _this._renderTargets = new BABYLON.SmartArray(16);
  96304. _this._reflectionControls = BABYLON.Vector4.Zero();
  96305. _this._white = BABYLON.Color3.White();
  96306. _this._primaryShadowColor = BABYLON.Color3.Black();
  96307. _this._primaryHighlightColor = BABYLON.Color3.Black();
  96308. // Setup the default processing configuration to the scene.
  96309. _this._attachImageProcessingConfiguration(null);
  96310. _this.getRenderTargetTextures = function () {
  96311. _this._renderTargets.reset();
  96312. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  96313. _this._renderTargets.push(_this._diffuseTexture);
  96314. }
  96315. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  96316. _this._renderTargets.push(_this._reflectionTexture);
  96317. }
  96318. return _this._renderTargets;
  96319. };
  96320. return _this;
  96321. }
  96322. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  96323. /**
  96324. * Experimental Internal Use Only.
  96325. *
  96326. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  96327. * This acts as a helper to set the primary color to a more "human friendly" value.
  96328. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  96329. * output color as close as possible from the chosen value.
  96330. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  96331. * part of lighting setup.)
  96332. */
  96333. get: function () {
  96334. return this.__perceptualColor;
  96335. },
  96336. set: function (value) {
  96337. this.__perceptualColor = value;
  96338. this._computePrimaryColorFromPerceptualColor();
  96339. this._markAllSubMeshesAsLightsDirty();
  96340. },
  96341. enumerable: true,
  96342. configurable: true
  96343. });
  96344. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  96345. /**
  96346. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  96347. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  96348. */
  96349. get: function () {
  96350. return this._primaryColorShadowLevel;
  96351. },
  96352. set: function (value) {
  96353. this._primaryColorShadowLevel = value;
  96354. this._computePrimaryColors();
  96355. this._markAllSubMeshesAsLightsDirty();
  96356. },
  96357. enumerable: true,
  96358. configurable: true
  96359. });
  96360. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  96361. /**
  96362. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  96363. * The primary color is used at the level chosen to define what the white area would look.
  96364. */
  96365. get: function () {
  96366. return this._primaryColorHighlightLevel;
  96367. },
  96368. set: function (value) {
  96369. this._primaryColorHighlightLevel = value;
  96370. this._computePrimaryColors();
  96371. this._markAllSubMeshesAsLightsDirty();
  96372. },
  96373. enumerable: true,
  96374. configurable: true
  96375. });
  96376. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  96377. /**
  96378. * Sets the reflection reflectance fresnel values according to the default standard
  96379. * empirically know to work well :-)
  96380. */
  96381. set: function (value) {
  96382. var reflectionWeight = value;
  96383. if (reflectionWeight < 0.5) {
  96384. reflectionWeight = reflectionWeight * 2.0;
  96385. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  96386. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  96387. }
  96388. else {
  96389. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  96390. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  96391. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  96392. }
  96393. },
  96394. enumerable: true,
  96395. configurable: true
  96396. });
  96397. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  96398. /**
  96399. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  96400. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  96401. * Recommended to be keep at 1.0 except for special cases.
  96402. */
  96403. get: function () {
  96404. return this._fovMultiplier;
  96405. },
  96406. set: function (value) {
  96407. if (isNaN(value)) {
  96408. value = 1.0;
  96409. }
  96410. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  96411. },
  96412. enumerable: true,
  96413. configurable: true
  96414. });
  96415. /**
  96416. * Attaches a new image processing configuration to the PBR Material.
  96417. * @param configuration (if null the scene configuration will be use)
  96418. */
  96419. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  96420. var _this = this;
  96421. if (configuration === this._imageProcessingConfiguration) {
  96422. return;
  96423. }
  96424. // Detaches observer.
  96425. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  96426. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  96427. }
  96428. // Pick the scene configuration if needed.
  96429. if (!configuration) {
  96430. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  96431. }
  96432. else {
  96433. this._imageProcessingConfiguration = configuration;
  96434. }
  96435. // Attaches observer.
  96436. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  96437. _this._computePrimaryColorFromPerceptualColor();
  96438. _this._markAllSubMeshesAsImageProcessingDirty();
  96439. });
  96440. };
  96441. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  96442. /**
  96443. * Gets the image processing configuration used either in this material.
  96444. */
  96445. get: function () {
  96446. return this._imageProcessingConfiguration;
  96447. },
  96448. /**
  96449. * Sets the Default image processing configuration used either in the this material.
  96450. *
  96451. * If sets to null, the scene one is in use.
  96452. */
  96453. set: function (value) {
  96454. this._attachImageProcessingConfiguration(value);
  96455. // Ensure the effect will be rebuilt.
  96456. this._markAllSubMeshesAsTexturesDirty();
  96457. },
  96458. enumerable: true,
  96459. configurable: true
  96460. });
  96461. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  96462. /**
  96463. * Gets wether the color curves effect is enabled.
  96464. */
  96465. get: function () {
  96466. return this.imageProcessingConfiguration.colorCurvesEnabled;
  96467. },
  96468. /**
  96469. * Sets wether the color curves effect is enabled.
  96470. */
  96471. set: function (value) {
  96472. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  96473. },
  96474. enumerable: true,
  96475. configurable: true
  96476. });
  96477. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  96478. /**
  96479. * Gets wether the color grading effect is enabled.
  96480. */
  96481. get: function () {
  96482. return this.imageProcessingConfiguration.colorGradingEnabled;
  96483. },
  96484. /**
  96485. * Gets wether the color grading effect is enabled.
  96486. */
  96487. set: function (value) {
  96488. this.imageProcessingConfiguration.colorGradingEnabled = value;
  96489. },
  96490. enumerable: true,
  96491. configurable: true
  96492. });
  96493. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  96494. /**
  96495. * Gets wether tonemapping is enabled or not.
  96496. */
  96497. get: function () {
  96498. return this._imageProcessingConfiguration.toneMappingEnabled;
  96499. },
  96500. /**
  96501. * Sets wether tonemapping is enabled or not
  96502. */
  96503. set: function (value) {
  96504. this._imageProcessingConfiguration.toneMappingEnabled = value;
  96505. },
  96506. enumerable: true,
  96507. configurable: true
  96508. });
  96509. ;
  96510. ;
  96511. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  96512. /**
  96513. * The camera exposure used on this material.
  96514. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96515. * This corresponds to a photographic exposure.
  96516. */
  96517. get: function () {
  96518. return this._imageProcessingConfiguration.exposure;
  96519. },
  96520. /**
  96521. * The camera exposure used on this material.
  96522. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  96523. * This corresponds to a photographic exposure.
  96524. */
  96525. set: function (value) {
  96526. this._imageProcessingConfiguration.exposure = value;
  96527. },
  96528. enumerable: true,
  96529. configurable: true
  96530. });
  96531. ;
  96532. ;
  96533. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  96534. /**
  96535. * Gets The camera contrast used on this material.
  96536. */
  96537. get: function () {
  96538. return this._imageProcessingConfiguration.contrast;
  96539. },
  96540. /**
  96541. * Sets The camera contrast used on this material.
  96542. */
  96543. set: function (value) {
  96544. this._imageProcessingConfiguration.contrast = value;
  96545. },
  96546. enumerable: true,
  96547. configurable: true
  96548. });
  96549. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  96550. /**
  96551. * Gets the Color Grading 2D Lookup Texture.
  96552. */
  96553. get: function () {
  96554. return this._imageProcessingConfiguration.colorGradingTexture;
  96555. },
  96556. /**
  96557. * Sets the Color Grading 2D Lookup Texture.
  96558. */
  96559. set: function (value) {
  96560. this.imageProcessingConfiguration.colorGradingTexture = value;
  96561. },
  96562. enumerable: true,
  96563. configurable: true
  96564. });
  96565. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  96566. /**
  96567. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96568. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96569. * 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;
  96570. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96571. */
  96572. get: function () {
  96573. return this.imageProcessingConfiguration.colorCurves;
  96574. },
  96575. /**
  96576. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  96577. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  96578. * 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;
  96579. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  96580. */
  96581. set: function (value) {
  96582. this.imageProcessingConfiguration.colorCurves = value;
  96583. },
  96584. enumerable: true,
  96585. configurable: true
  96586. });
  96587. /**
  96588. * The entire material has been created in order to prevent overdraw.
  96589. * @returns false
  96590. */
  96591. BackgroundMaterial.prototype.needAlphaTesting = function () {
  96592. return true;
  96593. };
  96594. /**
  96595. * The entire material has been created in order to prevent overdraw.
  96596. * @returns true if blending is enable
  96597. */
  96598. BackgroundMaterial.prototype.needAlphaBlending = function () {
  96599. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  96600. };
  96601. /**
  96602. * Checks wether the material is ready to be rendered for a given mesh.
  96603. * @param mesh The mesh to render
  96604. * @param subMesh The submesh to check against
  96605. * @param useInstances Specify wether or not the material is used with instances
  96606. * @returns true if all the dependencies are ready (Textures, Effects...)
  96607. */
  96608. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  96609. var _this = this;
  96610. if (useInstances === void 0) { useInstances = false; }
  96611. if (subMesh.effect && this.isFrozen) {
  96612. if (this._wasPreviouslyReady) {
  96613. return true;
  96614. }
  96615. }
  96616. if (!subMesh._materialDefines) {
  96617. subMesh._materialDefines = new BackgroundMaterialDefines();
  96618. }
  96619. var scene = this.getScene();
  96620. var defines = subMesh._materialDefines;
  96621. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  96622. if (defines._renderId === scene.getRenderId()) {
  96623. return true;
  96624. }
  96625. }
  96626. var engine = scene.getEngine();
  96627. // Lights
  96628. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  96629. defines._needNormals = true;
  96630. // Textures
  96631. if (defines._areTexturesDirty) {
  96632. defines._needUVs = false;
  96633. if (scene.texturesEnabled) {
  96634. if (scene.getEngine().getCaps().textureLOD) {
  96635. defines.TEXTURELODSUPPORT = true;
  96636. }
  96637. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96638. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  96639. return false;
  96640. }
  96641. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  96642. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  96643. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  96644. defines.OPACITYFRESNEL = this._opacityFresnel;
  96645. }
  96646. else {
  96647. defines.DIFFUSE = false;
  96648. defines.DIFFUSEHASALPHA = false;
  96649. defines.GAMMADIFFUSE = false;
  96650. defines.OPACITYFRESNEL = false;
  96651. }
  96652. var reflectionTexture = this._reflectionTexture;
  96653. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96654. if (!reflectionTexture.isReadyOrNotBlocking()) {
  96655. return false;
  96656. }
  96657. defines.REFLECTION = true;
  96658. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  96659. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  96660. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  96661. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  96662. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  96663. defines.REFLECTIONBGR = this.switchToBGR;
  96664. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  96665. defines.INVERTCUBICMAP = true;
  96666. }
  96667. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  96668. switch (reflectionTexture.coordinatesMode) {
  96669. case BABYLON.Texture.EXPLICIT_MODE:
  96670. defines.REFLECTIONMAP_EXPLICIT = true;
  96671. break;
  96672. case BABYLON.Texture.PLANAR_MODE:
  96673. defines.REFLECTIONMAP_PLANAR = true;
  96674. break;
  96675. case BABYLON.Texture.PROJECTION_MODE:
  96676. defines.REFLECTIONMAP_PROJECTION = true;
  96677. break;
  96678. case BABYLON.Texture.SKYBOX_MODE:
  96679. defines.REFLECTIONMAP_SKYBOX = true;
  96680. break;
  96681. case BABYLON.Texture.SPHERICAL_MODE:
  96682. defines.REFLECTIONMAP_SPHERICAL = true;
  96683. break;
  96684. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  96685. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  96686. break;
  96687. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  96688. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  96689. break;
  96690. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  96691. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  96692. break;
  96693. case BABYLON.Texture.CUBIC_MODE:
  96694. case BABYLON.Texture.INVCUBIC_MODE:
  96695. default:
  96696. defines.REFLECTIONMAP_CUBIC = true;
  96697. break;
  96698. }
  96699. if (this.reflectionFresnel) {
  96700. defines.REFLECTIONFRESNEL = true;
  96701. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  96702. this._reflectionControls.x = this.reflectionAmount;
  96703. this._reflectionControls.y = this.reflectionReflectance0;
  96704. this._reflectionControls.z = this.reflectionReflectance90;
  96705. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  96706. }
  96707. else {
  96708. defines.REFLECTIONFRESNEL = false;
  96709. defines.REFLECTIONFALLOFF = false;
  96710. }
  96711. }
  96712. else {
  96713. defines.REFLECTION = false;
  96714. defines.REFLECTIONFRESNEL = false;
  96715. defines.REFLECTIONFALLOFF = false;
  96716. defines.REFLECTIONBLUR = false;
  96717. defines.REFLECTIONMAP_3D = false;
  96718. defines.REFLECTIONMAP_SPHERICAL = false;
  96719. defines.REFLECTIONMAP_PLANAR = false;
  96720. defines.REFLECTIONMAP_CUBIC = false;
  96721. defines.REFLECTIONMAP_PROJECTION = false;
  96722. defines.REFLECTIONMAP_SKYBOX = false;
  96723. defines.REFLECTIONMAP_EXPLICIT = false;
  96724. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  96725. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  96726. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  96727. defines.INVERTCUBICMAP = false;
  96728. defines.REFLECTIONMAP_OPPOSITEZ = false;
  96729. defines.LODINREFLECTIONALPHA = false;
  96730. defines.GAMMAREFLECTION = false;
  96731. }
  96732. }
  96733. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  96734. defines.USERGBCOLOR = this._useRGBColor;
  96735. defines.NOISE = this._enableNoise;
  96736. }
  96737. if (defines._areLightsDirty) {
  96738. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  96739. }
  96740. if (defines._areImageProcessingDirty) {
  96741. if (!this._imageProcessingConfiguration.isReady()) {
  96742. return false;
  96743. }
  96744. this._imageProcessingConfiguration.prepareDefines(defines);
  96745. }
  96746. // Misc.
  96747. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  96748. // Values that need to be evaluated on every frame
  96749. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  96750. // Attribs
  96751. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  96752. if (mesh) {
  96753. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  96754. mesh.createNormals(true);
  96755. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  96756. }
  96757. }
  96758. }
  96759. // Get correct effect
  96760. if (defines.isDirty) {
  96761. defines.markAsProcessed();
  96762. scene.resetCachedMaterial();
  96763. // Fallbacks
  96764. var fallbacks = new BABYLON.EffectFallbacks();
  96765. if (defines.FOG) {
  96766. fallbacks.addFallback(0, "FOG");
  96767. }
  96768. if (defines.POINTSIZE) {
  96769. fallbacks.addFallback(1, "POINTSIZE");
  96770. }
  96771. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  96772. if (defines.NUM_BONE_INFLUENCERS > 0) {
  96773. fallbacks.addCPUSkinningFallback(0, mesh);
  96774. }
  96775. //Attributes
  96776. var attribs = [BABYLON.VertexBuffer.PositionKind];
  96777. if (defines.NORMAL) {
  96778. attribs.push(BABYLON.VertexBuffer.NormalKind);
  96779. }
  96780. if (defines.UV1) {
  96781. attribs.push(BABYLON.VertexBuffer.UVKind);
  96782. }
  96783. if (defines.UV2) {
  96784. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  96785. }
  96786. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  96787. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  96788. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  96789. "vFogInfos", "vFogColor", "pointSize",
  96790. "vClipPlane", "mBones",
  96791. "vPrimaryColor", "vPrimaryColorShadow",
  96792. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  96793. "shadowLevel", "alpha",
  96794. "vBackgroundCenter", "vReflectionControl",
  96795. "vDiffuseInfos", "diffuseMatrix",
  96796. ];
  96797. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  96798. var uniformBuffers = ["Material", "Scene"];
  96799. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  96800. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  96801. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  96802. uniformsNames: uniforms,
  96803. uniformBuffersNames: uniformBuffers,
  96804. samplers: samplers,
  96805. defines: defines,
  96806. maxSimultaneousLights: this._maxSimultaneousLights
  96807. });
  96808. var onCompiled = function (effect) {
  96809. if (_this.onCompiled) {
  96810. _this.onCompiled(effect);
  96811. }
  96812. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  96813. };
  96814. var join = defines.toString();
  96815. subMesh.setEffect(scene.getEngine().createEffect("background", {
  96816. attributes: attribs,
  96817. uniformsNames: uniforms,
  96818. uniformBuffersNames: uniformBuffers,
  96819. samplers: samplers,
  96820. defines: join,
  96821. fallbacks: fallbacks,
  96822. onCompiled: onCompiled,
  96823. onError: this.onError,
  96824. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  96825. }, engine), defines);
  96826. this.buildUniformLayout();
  96827. }
  96828. if (!subMesh.effect || !subMesh.effect.isReady()) {
  96829. return false;
  96830. }
  96831. defines._renderId = scene.getRenderId();
  96832. this._wasPreviouslyReady = true;
  96833. return true;
  96834. };
  96835. /**
  96836. * Compute the primary color according to the chosen perceptual color.
  96837. */
  96838. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  96839. if (!this.__perceptualColor) {
  96840. return;
  96841. }
  96842. this._primaryColor.copyFrom(this.__perceptualColor);
  96843. // Revert gamma space.
  96844. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  96845. // Revert image processing configuration.
  96846. if (this._imageProcessingConfiguration) {
  96847. // Revert Exposure.
  96848. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  96849. }
  96850. this._computePrimaryColors();
  96851. };
  96852. /**
  96853. * Compute the highlights and shadow colors according to their chosen levels.
  96854. */
  96855. BackgroundMaterial.prototype._computePrimaryColors = function () {
  96856. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  96857. return;
  96858. }
  96859. // Find the highlight color based on the configuration.
  96860. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  96861. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  96862. // Find the shadow color based on the configuration.
  96863. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  96864. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  96865. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  96866. };
  96867. /**
  96868. * Build the uniform buffer used in the material.
  96869. */
  96870. BackgroundMaterial.prototype.buildUniformLayout = function () {
  96871. // Order is important !
  96872. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  96873. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  96874. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  96875. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  96876. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  96877. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  96878. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  96879. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  96880. this._uniformBuffer.addUniform("pointSize", 1);
  96881. this._uniformBuffer.addUniform("shadowLevel", 1);
  96882. this._uniformBuffer.addUniform("alpha", 1);
  96883. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  96884. this._uniformBuffer.addUniform("vReflectionControl", 4);
  96885. this._uniformBuffer.create();
  96886. };
  96887. /**
  96888. * Unbind the material.
  96889. */
  96890. BackgroundMaterial.prototype.unbind = function () {
  96891. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  96892. this._uniformBuffer.setTexture("diffuseSampler", null);
  96893. }
  96894. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  96895. this._uniformBuffer.setTexture("reflectionSampler", null);
  96896. }
  96897. _super.prototype.unbind.call(this);
  96898. };
  96899. /**
  96900. * Bind only the world matrix to the material.
  96901. * @param world The world matrix to bind.
  96902. */
  96903. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  96904. this._activeEffect.setMatrix("world", world);
  96905. };
  96906. /**
  96907. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  96908. * @param world The world matrix to bind.
  96909. * @param subMesh The submesh to bind for.
  96910. */
  96911. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  96912. var scene = this.getScene();
  96913. var defines = subMesh._materialDefines;
  96914. if (!defines) {
  96915. return;
  96916. }
  96917. var effect = subMesh.effect;
  96918. if (!effect) {
  96919. return;
  96920. }
  96921. this._activeEffect = effect;
  96922. // Matrices
  96923. this.bindOnlyWorldMatrix(world);
  96924. // Bones
  96925. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  96926. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  96927. if (mustRebind) {
  96928. this._uniformBuffer.bindToEffect(effect, "Material");
  96929. this.bindViewProjection(effect);
  96930. var reflectionTexture = this._reflectionTexture;
  96931. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  96932. // Texture uniforms
  96933. if (scene.texturesEnabled) {
  96934. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96935. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  96936. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  96937. }
  96938. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96939. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  96940. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  96941. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  96942. }
  96943. }
  96944. if (this.shadowLevel > 0) {
  96945. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  96946. }
  96947. this._uniformBuffer.updateFloat("alpha", this.alpha);
  96948. // Point size
  96949. if (this.pointsCloud) {
  96950. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  96951. }
  96952. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  96953. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  96954. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  96955. }
  96956. else {
  96957. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  96958. }
  96959. }
  96960. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  96961. // Textures
  96962. if (scene.texturesEnabled) {
  96963. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  96964. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  96965. }
  96966. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  96967. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  96968. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96969. }
  96970. else if (!defines.REFLECTIONBLUR) {
  96971. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  96972. }
  96973. else {
  96974. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  96975. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  96976. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  96977. }
  96978. if (defines.REFLECTIONFRESNEL) {
  96979. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  96980. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  96981. }
  96982. }
  96983. }
  96984. // Clip plane
  96985. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  96986. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  96987. }
  96988. if (mustRebind || !this.isFrozen) {
  96989. if (scene.lightsEnabled) {
  96990. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  96991. }
  96992. // View
  96993. this.bindView(effect);
  96994. // Fog
  96995. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  96996. // image processing
  96997. this._imageProcessingConfiguration.bind(this._activeEffect);
  96998. }
  96999. this._uniformBuffer.update();
  97000. this._afterBind(mesh);
  97001. };
  97002. /**
  97003. * Dispose the material.
  97004. * @param forceDisposeEffect Force disposal of the associated effect.
  97005. * @param forceDisposeTextures Force disposal of the associated textures.
  97006. */
  97007. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  97008. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  97009. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  97010. if (forceDisposeTextures) {
  97011. if (this.diffuseTexture) {
  97012. this.diffuseTexture.dispose();
  97013. }
  97014. if (this.reflectionTexture) {
  97015. this.reflectionTexture.dispose();
  97016. }
  97017. }
  97018. this._renderTargets.dispose();
  97019. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  97020. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  97021. }
  97022. _super.prototype.dispose.call(this, forceDisposeEffect);
  97023. };
  97024. /**
  97025. * Clones the material.
  97026. * @param name The cloned name.
  97027. * @returns The cloned material.
  97028. */
  97029. BackgroundMaterial.prototype.clone = function (name) {
  97030. var _this = this;
  97031. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  97032. };
  97033. /**
  97034. * Serializes the current material to its JSON representation.
  97035. * @returns The JSON representation.
  97036. */
  97037. BackgroundMaterial.prototype.serialize = function () {
  97038. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97039. serializationObject.customType = "BABYLON.BackgroundMaterial";
  97040. return serializationObject;
  97041. };
  97042. /**
  97043. * Gets the class name of the material
  97044. * @returns "BackgroundMaterial"
  97045. */
  97046. BackgroundMaterial.prototype.getClassName = function () {
  97047. return "BackgroundMaterial";
  97048. };
  97049. /**
  97050. * Parse a JSON input to create back a background material.
  97051. * @param source The JSON data to parse
  97052. * @param scene The scene to create the parsed material in
  97053. * @param rootUrl The root url of the assets the material depends upon
  97054. * @returns the instantiated BackgroundMaterial.
  97055. */
  97056. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  97057. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  97058. };
  97059. /**
  97060. * Standard reflectance value at parallel view angle.
  97061. */
  97062. BackgroundMaterial.StandardReflectance0 = 0.05;
  97063. /**
  97064. * Standard reflectance value at grazing angle.
  97065. */
  97066. BackgroundMaterial.StandardReflectance90 = 0.5;
  97067. __decorate([
  97068. BABYLON.serializeAsColor3()
  97069. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  97070. __decorate([
  97071. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97072. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  97073. __decorate([
  97074. BABYLON.serializeAsColor3()
  97075. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  97076. __decorate([
  97077. BABYLON.serialize()
  97078. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  97079. __decorate([
  97080. BABYLON.serialize()
  97081. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  97082. __decorate([
  97083. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  97084. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  97085. __decorate([
  97086. BABYLON.serializeAsTexture()
  97087. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  97088. __decorate([
  97089. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97090. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  97091. __decorate([
  97092. BABYLON.serialize()
  97093. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  97094. __decorate([
  97095. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97096. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  97097. __decorate([
  97098. BABYLON.serializeAsTexture()
  97099. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  97100. __decorate([
  97101. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97102. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  97103. __decorate([
  97104. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97105. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  97106. __decorate([
  97107. BABYLON.serialize()
  97108. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  97109. __decorate([
  97110. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97111. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  97112. __decorate([
  97113. BABYLON.serializeAsVector3()
  97114. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  97115. __decorate([
  97116. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97117. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  97118. __decorate([
  97119. BABYLON.serialize()
  97120. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  97121. __decorate([
  97122. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97123. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  97124. __decorate([
  97125. BABYLON.serialize()
  97126. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  97127. __decorate([
  97128. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97129. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  97130. __decorate([
  97131. BABYLON.serialize()
  97132. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  97133. __decorate([
  97134. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97135. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  97136. __decorate([
  97137. BABYLON.serialize()
  97138. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  97139. __decorate([
  97140. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97141. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  97142. __decorate([
  97143. BABYLON.serialize()
  97144. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  97145. __decorate([
  97146. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97147. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  97148. __decorate([
  97149. BABYLON.serialize()
  97150. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  97151. __decorate([
  97152. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97153. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  97154. __decorate([
  97155. BABYLON.serialize()
  97156. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  97157. __decorate([
  97158. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97159. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  97160. __decorate([
  97161. BABYLON.serialize()
  97162. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  97163. __decorate([
  97164. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97165. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  97166. __decorate([
  97167. BABYLON.serialize()
  97168. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  97169. __decorate([
  97170. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  97171. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  97172. __decorate([
  97173. BABYLON.serializeAsImageProcessingConfiguration()
  97174. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  97175. return BackgroundMaterial;
  97176. }(BABYLON.PushMaterial));
  97177. BABYLON.BackgroundMaterial = BackgroundMaterial;
  97178. })(BABYLON || (BABYLON = {}));
  97179. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  97180. var __assign = (this && this.__assign) || Object.assign || function(t) {
  97181. for (var s, i = 1, n = arguments.length; i < n; i++) {
  97182. s = arguments[i];
  97183. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  97184. t[p] = s[p];
  97185. }
  97186. return t;
  97187. };
  97188. var BABYLON;
  97189. (function (BABYLON) {
  97190. /**
  97191. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  97192. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  97193. * It also helps with the default setup of your imageProcessing configuration.
  97194. */
  97195. var EnvironmentHelper = /** @class */ (function () {
  97196. /**
  97197. * constructor
  97198. * @param options
  97199. * @param scene The scene to add the material to
  97200. */
  97201. function EnvironmentHelper(options, scene) {
  97202. var _this = this;
  97203. this._errorHandler = function (message, exception) {
  97204. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  97205. };
  97206. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  97207. this._scene = scene;
  97208. this.onErrorObservable = new BABYLON.Observable();
  97209. this._setupBackground();
  97210. this._setupImageProcessing();
  97211. }
  97212. /**
  97213. * Creates the default options for the helper.
  97214. */
  97215. EnvironmentHelper._getDefaultOptions = function () {
  97216. return {
  97217. createGround: true,
  97218. groundSize: 15,
  97219. groundTexture: this._groundTextureCDNUrl,
  97220. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97221. groundOpacity: 0.9,
  97222. enableGroundShadow: true,
  97223. groundShadowLevel: 0.5,
  97224. enableGroundMirror: false,
  97225. groundMirrorSizeRatio: 0.3,
  97226. groundMirrorBlurKernel: 64,
  97227. groundMirrorAmount: 1,
  97228. groundMirrorFresnelWeight: 1,
  97229. groundMirrorFallOffDistance: 0,
  97230. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  97231. groundYBias: 0.00001,
  97232. createSkybox: true,
  97233. skyboxSize: 20,
  97234. skyboxTexture: this._skyboxTextureCDNUrl,
  97235. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  97236. backgroundYRotation: 0,
  97237. sizeAuto: true,
  97238. rootPosition: BABYLON.Vector3.Zero(),
  97239. setupImageProcessing: true,
  97240. environmentTexture: this._environmentTextureCDNUrl,
  97241. cameraExposure: 0.8,
  97242. cameraContrast: 1.2,
  97243. toneMappingEnabled: true,
  97244. };
  97245. };
  97246. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  97247. /**
  97248. * Gets the root mesh created by the helper.
  97249. */
  97250. get: function () {
  97251. return this._rootMesh;
  97252. },
  97253. enumerable: true,
  97254. configurable: true
  97255. });
  97256. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  97257. /**
  97258. * Gets the skybox created by the helper.
  97259. */
  97260. get: function () {
  97261. return this._skybox;
  97262. },
  97263. enumerable: true,
  97264. configurable: true
  97265. });
  97266. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  97267. /**
  97268. * Gets the skybox texture created by the helper.
  97269. */
  97270. get: function () {
  97271. return this._skyboxTexture;
  97272. },
  97273. enumerable: true,
  97274. configurable: true
  97275. });
  97276. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  97277. /**
  97278. * Gets the skybox material created by the helper.
  97279. */
  97280. get: function () {
  97281. return this._skyboxMaterial;
  97282. },
  97283. enumerable: true,
  97284. configurable: true
  97285. });
  97286. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  97287. /**
  97288. * Gets the ground mesh created by the helper.
  97289. */
  97290. get: function () {
  97291. return this._ground;
  97292. },
  97293. enumerable: true,
  97294. configurable: true
  97295. });
  97296. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  97297. /**
  97298. * Gets the ground texture created by the helper.
  97299. */
  97300. get: function () {
  97301. return this._groundTexture;
  97302. },
  97303. enumerable: true,
  97304. configurable: true
  97305. });
  97306. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  97307. /**
  97308. * Gets the ground mirror created by the helper.
  97309. */
  97310. get: function () {
  97311. return this._groundMirror;
  97312. },
  97313. enumerable: true,
  97314. configurable: true
  97315. });
  97316. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  97317. /**
  97318. * Gets the ground mirror render list to helps pushing the meshes
  97319. * you wish in the ground reflection.
  97320. */
  97321. get: function () {
  97322. if (this._groundMirror) {
  97323. return this._groundMirror.renderList;
  97324. }
  97325. return null;
  97326. },
  97327. enumerable: true,
  97328. configurable: true
  97329. });
  97330. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  97331. /**
  97332. * Gets the ground material created by the helper.
  97333. */
  97334. get: function () {
  97335. return this._groundMaterial;
  97336. },
  97337. enumerable: true,
  97338. configurable: true
  97339. });
  97340. /**
  97341. * Updates the background according to the new options
  97342. * @param options
  97343. */
  97344. EnvironmentHelper.prototype.updateOptions = function (options) {
  97345. var newOptions = __assign({}, this._options, options);
  97346. if (this._ground && !newOptions.createGround) {
  97347. this._ground.dispose();
  97348. this._ground = null;
  97349. }
  97350. if (this._groundMaterial && !newOptions.createGround) {
  97351. this._groundMaterial.dispose();
  97352. this._groundMaterial = null;
  97353. }
  97354. if (this._groundTexture) {
  97355. if (this._options.groundTexture != newOptions.groundTexture) {
  97356. this._groundTexture.dispose();
  97357. this._groundTexture = null;
  97358. }
  97359. }
  97360. if (this._skybox && !newOptions.createSkybox) {
  97361. this._skybox.dispose();
  97362. this._skybox = null;
  97363. }
  97364. if (this._skyboxMaterial && !newOptions.createSkybox) {
  97365. this._skyboxMaterial.dispose();
  97366. this._skyboxMaterial = null;
  97367. }
  97368. if (this._skyboxTexture) {
  97369. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  97370. this._skyboxTexture.dispose();
  97371. this._skyboxTexture = null;
  97372. }
  97373. }
  97374. if (this._groundMirror && !newOptions.enableGroundMirror) {
  97375. this._groundMirror.dispose();
  97376. this._groundMirror = null;
  97377. }
  97378. if (this._scene.environmentTexture) {
  97379. if (this._options.environmentTexture != newOptions.environmentTexture) {
  97380. this._scene.environmentTexture.dispose();
  97381. }
  97382. }
  97383. this._options = newOptions;
  97384. this._setupBackground();
  97385. this._setupImageProcessing();
  97386. };
  97387. /**
  97388. * Sets the primary color of all the available elements.
  97389. * @param color the main color to affect to the ground and the background
  97390. */
  97391. EnvironmentHelper.prototype.setMainColor = function (color) {
  97392. if (this.groundMaterial) {
  97393. this.groundMaterial.primaryColor = color;
  97394. }
  97395. if (this.skyboxMaterial) {
  97396. this.skyboxMaterial.primaryColor = color;
  97397. }
  97398. if (this.groundMirror) {
  97399. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  97400. }
  97401. };
  97402. /**
  97403. * Setup the image processing according to the specified options.
  97404. */
  97405. EnvironmentHelper.prototype._setupImageProcessing = function () {
  97406. if (this._options.setupImageProcessing) {
  97407. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  97408. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  97409. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  97410. this._setupEnvironmentTexture();
  97411. }
  97412. };
  97413. /**
  97414. * Setup the environment texture according to the specified options.
  97415. */
  97416. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  97417. if (this._scene.environmentTexture) {
  97418. return;
  97419. }
  97420. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  97421. this._scene.environmentTexture = this._options.environmentTexture;
  97422. return;
  97423. }
  97424. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  97425. this._scene.environmentTexture = environmentTexture;
  97426. };
  97427. /**
  97428. * Setup the background according to the specified options.
  97429. */
  97430. EnvironmentHelper.prototype._setupBackground = function () {
  97431. if (!this._rootMesh) {
  97432. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  97433. }
  97434. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  97435. var sceneSize = this._getSceneSize();
  97436. if (this._options.createGround) {
  97437. this._setupGround(sceneSize);
  97438. this._setupGroundMaterial();
  97439. this._setupGroundDiffuseTexture();
  97440. if (this._options.enableGroundMirror) {
  97441. this._setupGroundMirrorTexture(sceneSize);
  97442. }
  97443. this._setupMirrorInGroundMaterial();
  97444. }
  97445. if (this._options.createSkybox) {
  97446. this._setupSkybox(sceneSize);
  97447. this._setupSkyboxMaterial();
  97448. this._setupSkyboxReflectionTexture();
  97449. }
  97450. this._rootMesh.position.x = sceneSize.rootPosition.x;
  97451. this._rootMesh.position.z = sceneSize.rootPosition.z;
  97452. this._rootMesh.position.y = sceneSize.rootPosition.y;
  97453. };
  97454. /**
  97455. * Get the scene sizes according to the setup.
  97456. */
  97457. EnvironmentHelper.prototype._getSceneSize = function () {
  97458. var _this = this;
  97459. var groundSize = this._options.groundSize;
  97460. var skyboxSize = this._options.skyboxSize;
  97461. var rootPosition = this._options.rootPosition;
  97462. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  97463. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97464. }
  97465. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  97466. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  97467. });
  97468. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  97469. if (this._options.sizeAuto) {
  97470. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  97471. this._scene.activeCamera.upperRadiusLimit) {
  97472. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  97473. skyboxSize = groundSize;
  97474. }
  97475. var sceneDiagonalLenght = sceneDiagonal.length();
  97476. if (sceneDiagonalLenght > groundSize) {
  97477. groundSize = sceneDiagonalLenght * 2;
  97478. skyboxSize = groundSize;
  97479. }
  97480. // 10 % bigger.
  97481. groundSize *= 1.1;
  97482. skyboxSize *= 1.5;
  97483. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  97484. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  97485. }
  97486. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  97487. };
  97488. /**
  97489. * Setup the ground according to the specified options.
  97490. */
  97491. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  97492. var _this = this;
  97493. if (!this._ground) {
  97494. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  97495. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  97496. this._ground.parent = this._rootMesh;
  97497. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  97498. }
  97499. this._ground.receiveShadows = this._options.enableGroundShadow;
  97500. };
  97501. /**
  97502. * Setup the ground material according to the specified options.
  97503. */
  97504. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  97505. if (!this._groundMaterial) {
  97506. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  97507. }
  97508. this._groundMaterial.alpha = this._options.groundOpacity;
  97509. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  97510. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  97511. this._groundMaterial.primaryColor = this._options.groundColor;
  97512. this._groundMaterial.useRGBColor = false;
  97513. this._groundMaterial.enableNoise = true;
  97514. if (this._ground) {
  97515. this._ground.material = this._groundMaterial;
  97516. }
  97517. };
  97518. /**
  97519. * Setup the ground diffuse texture according to the specified options.
  97520. */
  97521. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  97522. if (!this._groundMaterial) {
  97523. return;
  97524. }
  97525. if (this._groundTexture) {
  97526. return;
  97527. }
  97528. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  97529. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  97530. return;
  97531. }
  97532. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97533. diffuseTexture.gammaSpace = false;
  97534. diffuseTexture.hasAlpha = true;
  97535. this._groundMaterial.diffuseTexture = diffuseTexture;
  97536. };
  97537. /**
  97538. * Setup the ground mirror texture according to the specified options.
  97539. */
  97540. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  97541. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  97542. if (!this._groundMirror) {
  97543. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  97544. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  97545. this._groundMirror.anisotropicFilteringLevel = 1;
  97546. this._groundMirror.wrapU = wrapping;
  97547. this._groundMirror.wrapV = wrapping;
  97548. this._groundMirror.gammaSpace = false;
  97549. if (this._groundMirror.renderList) {
  97550. for (var i = 0; i < this._scene.meshes.length; i++) {
  97551. var mesh = this._scene.meshes[i];
  97552. if (mesh !== this._ground &&
  97553. mesh !== this._skybox &&
  97554. mesh !== this._rootMesh) {
  97555. this._groundMirror.renderList.push(mesh);
  97556. }
  97557. }
  97558. }
  97559. }
  97560. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  97561. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  97562. };
  97563. /**
  97564. * Setup the ground to receive the mirror texture.
  97565. */
  97566. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  97567. if (this._groundMaterial) {
  97568. this._groundMaterial.reflectionTexture = this._groundMirror;
  97569. this._groundMaterial.reflectionFresnel = true;
  97570. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  97571. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  97572. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  97573. }
  97574. };
  97575. /**
  97576. * Setup the skybox according to the specified options.
  97577. */
  97578. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  97579. var _this = this;
  97580. if (!this._skybox) {
  97581. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  97582. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  97583. }
  97584. this._skybox.parent = this._rootMesh;
  97585. };
  97586. /**
  97587. * Setup the skybox material according to the specified options.
  97588. */
  97589. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  97590. if (!this._skybox) {
  97591. return;
  97592. }
  97593. if (!this._skyboxMaterial) {
  97594. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  97595. }
  97596. this._skyboxMaterial.useRGBColor = false;
  97597. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  97598. this._skyboxMaterial.enableNoise = true;
  97599. this._skybox.material = this._skyboxMaterial;
  97600. };
  97601. /**
  97602. * Setup the skybox reflection texture according to the specified options.
  97603. */
  97604. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  97605. if (!this._skyboxMaterial) {
  97606. return;
  97607. }
  97608. if (this._skyboxTexture) {
  97609. return;
  97610. }
  97611. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  97612. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  97613. return;
  97614. }
  97615. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  97616. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  97617. this._skyboxTexture.gammaSpace = false;
  97618. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  97619. };
  97620. /**
  97621. * Dispose all the elements created by the Helper.
  97622. */
  97623. EnvironmentHelper.prototype.dispose = function () {
  97624. if (this._groundMaterial) {
  97625. this._groundMaterial.dispose(true, true);
  97626. }
  97627. if (this._skyboxMaterial) {
  97628. this._skyboxMaterial.dispose(true, true);
  97629. }
  97630. this._rootMesh.dispose(false);
  97631. };
  97632. /**
  97633. * Default ground texture URL.
  97634. */
  97635. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  97636. /**
  97637. * Default skybox texture URL.
  97638. */
  97639. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  97640. /**
  97641. * Default environment texture URL.
  97642. */
  97643. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.dds";
  97644. return EnvironmentHelper;
  97645. }());
  97646. BABYLON.EnvironmentHelper = EnvironmentHelper;
  97647. })(BABYLON || (BABYLON = {}));
  97648. //# sourceMappingURL=babylon.environmentHelper.js.map
  97649. var BABYLON;
  97650. (function (BABYLON) {
  97651. /**
  97652. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  97653. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  97654. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  97655. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  97656. */
  97657. var VideoDome = /** @class */ (function (_super) {
  97658. __extends(VideoDome, _super);
  97659. /**
  97660. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  97661. * @param name Element's name, child elements will append suffixes for their own names.
  97662. * @param urlsOrVideo
  97663. * @param options An object containing optional or exposed sub element properties:
  97664. * @param options **resolution=12** Integer, lower resolutions have more artifacts at extreme fovs
  97665. * @param options **clickToPlay=false** Add a click to play listener to the video, does not prevent autoplay.
  97666. * @param options **autoPlay=true** Automatically attempt to being playing the video.
  97667. * @param options **loop=true** Automatically loop video on end.
  97668. * @param options **size=1000** Physical radius to create the dome at, defaults to approximately half the far clip plane.
  97669. */
  97670. function VideoDome(name, urlsOrVideo, options, scene) {
  97671. var _this = _super.call(this, name, scene) || this;
  97672. // set defaults and manage values
  97673. name = name || "videoDome";
  97674. options.resolution = (Math.abs(options.resolution) | 0) || 12;
  97675. options.clickToPlay = Boolean(options.clickToPlay);
  97676. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  97677. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  97678. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  97679. // create
  97680. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true };
  97681. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  97682. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  97683. _this._mesh = BABYLON.MeshBuilder.CreateIcoSphere(name + "_mesh", {
  97684. flat: false,
  97685. radius: options.size,
  97686. subdivisions: options.resolution,
  97687. sideOrientation: BABYLON.Mesh.BACKSIDE // needs to be inside out
  97688. }, scene);
  97689. // configure material
  97690. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  97691. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE; // always clamp the up/down
  97692. material.reflectionTexture = _this._videoTexture;
  97693. material.useEquirectangularFOV = true;
  97694. material.fovMultiplier = 1.0;
  97695. // configure mesh
  97696. _this._mesh.material = material;
  97697. _this._mesh.parent = _this;
  97698. // optional configuration
  97699. if (options.clickToPlay) {
  97700. scene.onPointerUp = function () {
  97701. _this._videoTexture.video.play();
  97702. };
  97703. }
  97704. return _this;
  97705. }
  97706. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  97707. /**
  97708. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  97709. * Also see the options.resolution property.
  97710. */
  97711. get: function () {
  97712. return this._material.fovMultiplier;
  97713. },
  97714. set: function (value) {
  97715. this._material.fovMultiplier = value;
  97716. },
  97717. enumerable: true,
  97718. configurable: true
  97719. });
  97720. /**
  97721. * Releases resources associated with this node.
  97722. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  97723. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  97724. */
  97725. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  97726. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  97727. this._videoTexture.dispose();
  97728. this._mesh.dispose();
  97729. this._material.dispose();
  97730. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  97731. };
  97732. return VideoDome;
  97733. }(BABYLON.Node));
  97734. BABYLON.VideoDome = VideoDome;
  97735. })(BABYLON || (BABYLON = {}));
  97736. //# sourceMappingURL=babylon.videoDome.js.map
  97737. 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;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,vUV);\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"};
  97738. 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};"};
  97739. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  97740. globalObject["BABYLON"] = BABYLON;
  97741. //backwards compatibility
  97742. if(typeof earcut !== 'undefined') {
  97743. globalObject["Earcut"] = {
  97744. earcut: earcut
  97745. };
  97746. }
  97747. return BABYLON;
  97748. });
  97749. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(22)))
  97750. /***/ }),
  97751. /* 1 */
  97752. /***/ (function(module, exports, __webpack_require__) {
  97753. (function (global, factory) {
  97754. true ? module.exports = factory() :
  97755. typeof define === 'function' && define.amd ? define(factory) :
  97756. (global.deepmerge = factory());
  97757. }(this, (function () { 'use strict';
  97758. var isMergeableObject = function isMergeableObject(value) {
  97759. return isNonNullObject(value)
  97760. && !isSpecial(value)
  97761. };
  97762. function isNonNullObject(value) {
  97763. return !!value && typeof value === 'object'
  97764. }
  97765. function isSpecial(value) {
  97766. var stringValue = Object.prototype.toString.call(value);
  97767. return stringValue === '[object RegExp]'
  97768. || stringValue === '[object Date]'
  97769. || isReactElement(value)
  97770. }
  97771. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  97772. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  97773. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  97774. function isReactElement(value) {
  97775. return value.$$typeof === REACT_ELEMENT_TYPE
  97776. }
  97777. function emptyTarget(val) {
  97778. return Array.isArray(val) ? [] : {}
  97779. }
  97780. function cloneUnlessOtherwiseSpecified(value, optionsArgument) {
  97781. var clone = !optionsArgument || optionsArgument.clone !== false;
  97782. return (clone && isMergeableObject(value))
  97783. ? deepmerge(emptyTarget(value), value, optionsArgument)
  97784. : value
  97785. }
  97786. function defaultArrayMerge(target, source, optionsArgument) {
  97787. return target.concat(source).map(function(element) {
  97788. return cloneUnlessOtherwiseSpecified(element, optionsArgument)
  97789. })
  97790. }
  97791. function mergeObject(target, source, optionsArgument) {
  97792. var destination = {};
  97793. if (isMergeableObject(target)) {
  97794. Object.keys(target).forEach(function(key) {
  97795. destination[key] = cloneUnlessOtherwiseSpecified(target[key], optionsArgument);
  97796. });
  97797. }
  97798. Object.keys(source).forEach(function(key) {
  97799. if (!isMergeableObject(source[key]) || !target[key]) {
  97800. destination[key] = cloneUnlessOtherwiseSpecified(source[key], optionsArgument);
  97801. } else {
  97802. destination[key] = deepmerge(target[key], source[key], optionsArgument);
  97803. }
  97804. });
  97805. return destination
  97806. }
  97807. function deepmerge(target, source, optionsArgument) {
  97808. var sourceIsArray = Array.isArray(source);
  97809. var targetIsArray = Array.isArray(target);
  97810. var options = optionsArgument || { arrayMerge: defaultArrayMerge };
  97811. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  97812. if (!sourceAndTargetTypesMatch) {
  97813. return cloneUnlessOtherwiseSpecified(source, optionsArgument)
  97814. } else if (sourceIsArray) {
  97815. var arrayMerge = options.arrayMerge || defaultArrayMerge;
  97816. return arrayMerge(target, source, optionsArgument)
  97817. } else {
  97818. return mergeObject(target, source, optionsArgument)
  97819. }
  97820. }
  97821. deepmerge.all = function deepmergeAll(array, optionsArgument) {
  97822. if (!Array.isArray(array)) {
  97823. throw new Error('first argument should be an array')
  97824. }
  97825. return array.reduce(function(prev, next) {
  97826. return deepmerge(prev, next, optionsArgument)
  97827. }, {})
  97828. };
  97829. var deepmerge_1 = deepmerge;
  97830. return deepmerge_1;
  97831. })));
  97832. /***/ }),
  97833. /* 2 */
  97834. /***/ (function(module, exports, __webpack_require__) {
  97835. "use strict";
  97836. Object.defineProperty(exports, "__esModule", { value: true });
  97837. /**
  97838. * Is the provided string a URL?
  97839. *
  97840. * @param urlToCheck the url to inspect
  97841. */
  97842. function isUrl(urlToCheck) {
  97843. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  97844. return true;
  97845. }
  97846. return false;
  97847. }
  97848. exports.isUrl = isUrl;
  97849. /**
  97850. * Convert a string from kebab-case to camelCase
  97851. * @param s string to convert
  97852. */
  97853. function kebabToCamel(s) {
  97854. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  97855. }
  97856. exports.kebabToCamel = kebabToCamel;
  97857. //https://gist.github.com/youssman/745578062609e8acac9f
  97858. /**
  97859. * Convert a string from camelCase to kebab-case
  97860. * @param str string to convert
  97861. */
  97862. function camelToKebab(str) {
  97863. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  97864. }
  97865. exports.camelToKebab = camelToKebab;
  97866. /**
  97867. * This will extend an object with configuration values.
  97868. * What it practically does it take the keys from the configuration and set them on the object.
  97869. * I the configuration is a tree, it will traverse into the tree.
  97870. * @param object the object to extend
  97871. * @param config the configuration object that will extend the object
  97872. */
  97873. function extendClassWithConfig(object, config) {
  97874. if (!config)
  97875. return;
  97876. Object.keys(config).forEach(function (key) {
  97877. if (key in object && typeof object[key] !== 'function') {
  97878. // if (typeof object[key] === 'function') return;
  97879. // if it is an object, iterate internally until reaching basic types
  97880. if (typeof object[key] === 'object') {
  97881. extendClassWithConfig(object[key], config[key]);
  97882. }
  97883. else {
  97884. if (config[key] !== undefined) {
  97885. object[key] = config[key];
  97886. }
  97887. }
  97888. }
  97889. });
  97890. }
  97891. exports.extendClassWithConfig = extendClassWithConfig;
  97892. /***/ }),
  97893. /* 3 */
  97894. /***/ (function(module, exports, __webpack_require__) {
  97895. "use strict";
  97896. Object.defineProperty(exports, "__esModule", { value: true });
  97897. var babylonjs_1 = __webpack_require__(0);
  97898. var helper_1 = __webpack_require__(2);
  97899. /**
  97900. * This is a simple HTML mapper.
  97901. * This mapper parses a single HTML element and returns the configuration from its attributes.
  97902. * it parses numbers and boolean values to the corresponding variable types.
  97903. * The following HTML element:
  97904. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  97905. *
  97906. * {
  97907. * test: 1, //a number!
  97908. * randomFlag: boolean, //camelCase and boolean
  97909. * a: {
  97910. * string: {
  97911. * object: "test" //dot-separated object levels
  97912. * }
  97913. * }
  97914. * }
  97915. */
  97916. var HTMLMapper = /** @class */ (function () {
  97917. function HTMLMapper() {
  97918. }
  97919. /**
  97920. * Map a specific element and get configuration from it
  97921. * @param element the HTML element to analyze.
  97922. */
  97923. HTMLMapper.prototype.map = function (element) {
  97924. var config = {};
  97925. var _loop_1 = function (attrIdx) {
  97926. var attr = element.attributes.item(attrIdx);
  97927. if (!attr) {
  97928. return "continue";
  97929. }
  97930. // map "object.property" to the right configuration place.
  97931. var split = attr.nodeName.split('.');
  97932. split.reduce(function (currentConfig, key, idx) {
  97933. //convert html-style to json-style
  97934. var camelKey = helper_1.kebabToCamel(key);
  97935. if (idx === split.length - 1) {
  97936. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  97937. if (val === "true") {
  97938. val = true;
  97939. }
  97940. else if (val === "false") {
  97941. val = false;
  97942. }
  97943. else {
  97944. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  97945. if (isnum) {
  97946. var number = parseFloat(val);
  97947. if (!isNaN(number)) {
  97948. val = number;
  97949. }
  97950. }
  97951. }
  97952. currentConfig[camelKey] = val;
  97953. }
  97954. else {
  97955. currentConfig[camelKey] = currentConfig[camelKey] || {};
  97956. }
  97957. return currentConfig[camelKey];
  97958. }, config);
  97959. };
  97960. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  97961. _loop_1(attrIdx);
  97962. }
  97963. return config;
  97964. };
  97965. return HTMLMapper;
  97966. }());
  97967. /**
  97968. * A simple string-to-JSON mapper.
  97969. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  97970. */
  97971. var JSONMapper = /** @class */ (function () {
  97972. function JSONMapper() {
  97973. }
  97974. JSONMapper.prototype.map = function (rawSource) {
  97975. return JSON.parse(rawSource);
  97976. };
  97977. return JSONMapper;
  97978. }());
  97979. /**
  97980. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  97981. * DOM elements and attributes.
  97982. */
  97983. var DOMMapper = /** @class */ (function () {
  97984. function DOMMapper() {
  97985. }
  97986. /**
  97987. * The mapping function that will convert HTML data to a viewer configuration object
  97988. * @param baseElement the baseElement from which to start traversing
  97989. * @returns a ViewerCOnfiguration object from the provided HTML Element
  97990. */
  97991. DOMMapper.prototype.map = function (baseElement) {
  97992. var htmlMapper = new HTMLMapper();
  97993. var config = htmlMapper.map(baseElement);
  97994. var traverseChildren = function (element, partConfig) {
  97995. var children = element.children;
  97996. if (children.length) {
  97997. for (var i = 0; i < children.length; ++i) {
  97998. var item = children.item(i);
  97999. // use the HTML Mapper to read configuration from a single element
  98000. var configMapped = htmlMapper.map(item);
  98001. var key = helper_1.kebabToCamel(item.nodeName.toLowerCase());
  98002. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  98003. partConfig[key] = [];
  98004. }
  98005. else {
  98006. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  98007. partConfig.push(configMapped);
  98008. }
  98009. else if (partConfig[key]) {
  98010. //exists already! probably an array
  98011. element.setAttribute('array', 'true');
  98012. var oldItem = partConfig[key];
  98013. partConfig = [oldItem, configMapped];
  98014. }
  98015. else {
  98016. partConfig[key] = configMapped;
  98017. }
  98018. }
  98019. traverseChildren(item, partConfig[key] || configMapped);
  98020. }
  98021. }
  98022. return partConfig;
  98023. };
  98024. traverseChildren(baseElement, config);
  98025. return config;
  98026. };
  98027. return DOMMapper;
  98028. }());
  98029. /**
  98030. * The MapperManager manages the different implemented mappers.
  98031. * It allows the user to register new mappers as well and use them to parse their own configuration data
  98032. */
  98033. var MapperManager = /** @class */ (function () {
  98034. function MapperManager() {
  98035. this._mappers = {
  98036. "html": new HTMLMapper(),
  98037. "json": new JSONMapper(),
  98038. "dom": new DOMMapper()
  98039. };
  98040. }
  98041. /**
  98042. * Get a specific configuration mapper.
  98043. *
  98044. * @param type the name of the mapper to load
  98045. */
  98046. MapperManager.prototype.getMapper = function (type) {
  98047. if (!this._mappers[type]) {
  98048. babylonjs_1.Tools.Error("No mapper defined for " + type);
  98049. }
  98050. return this._mappers[type] || this._mappers[MapperManager.DefaultMapper];
  98051. };
  98052. /**
  98053. * Use this functio to register your own configuration mapper.
  98054. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  98055. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  98056. * @param mapper The implemented mapper
  98057. */
  98058. MapperManager.prototype.registerMapper = function (type, mapper) {
  98059. this._mappers[type] = mapper;
  98060. };
  98061. /**
  98062. * Dispose the mapper manager and all of its mappers.
  98063. */
  98064. MapperManager.prototype.dispose = function () {
  98065. this._mappers = {};
  98066. };
  98067. /**
  98068. * The default mapper is the JSON mapper.
  98069. */
  98070. MapperManager.DefaultMapper = 'json';
  98071. return MapperManager;
  98072. }());
  98073. exports.MapperManager = MapperManager;
  98074. /**
  98075. * mapperManager is a singleton of the type MapperManager.
  98076. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  98077. * or indirectly with using BabylonViewer.disposeAll()
  98078. */
  98079. exports.mapperManager = new MapperManager();
  98080. /***/ }),
  98081. /* 4 */
  98082. /***/ (function(module, exports, __webpack_require__) {
  98083. "use strict";
  98084. Object.defineProperty(exports, "__esModule", { value: true });
  98085. var babylonjs_1 = __webpack_require__(0);
  98086. var modelAnimation_1 = __webpack_require__(28);
  98087. var deepmerge = __webpack_require__(1);
  98088. var helper_1 = __webpack_require__(2);
  98089. var ModelState;
  98090. (function (ModelState) {
  98091. ModelState[ModelState["INIT"] = 0] = "INIT";
  98092. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  98093. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  98094. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  98095. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  98096. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  98097. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  98098. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  98099. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  98100. /**
  98101. * The viewer model is a container for all assets representing a sngle loaded model.
  98102. */
  98103. var ViewerModel = /** @class */ (function () {
  98104. function ViewerModel(_viewer, modelConfiguration) {
  98105. var _this = this;
  98106. this._viewer = _viewer;
  98107. /**
  98108. * the list of meshes that are a part of this model
  98109. */
  98110. this._meshes = [];
  98111. /**
  98112. * ParticleSystems connected to this model
  98113. */
  98114. this.particleSystems = [];
  98115. /**
  98116. * Skeletons defined in this model
  98117. */
  98118. this.skeletons = [];
  98119. this._loaderDone = false;
  98120. this._animatables = [];
  98121. this._frameRate = 60;
  98122. this.onLoadedObservable = new babylonjs_1.Observable();
  98123. this.onLoadErrorObservable = new babylonjs_1.Observable();
  98124. this.onLoadProgressObservable = new babylonjs_1.Observable();
  98125. this.onCompleteObservable = new babylonjs_1.Observable();
  98126. this.onAfterConfigure = new babylonjs_1.Observable();
  98127. this.state = ModelState.INIT;
  98128. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", this._viewer.sceneManager.scene);
  98129. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", this._viewer.sceneManager.scene);
  98130. this._pivotMesh.parent = this.rootMesh;
  98131. // rotate 180, gltf fun
  98132. this._pivotMesh.rotation.y += Math.PI;
  98133. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  98134. this._animations = [];
  98135. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  98136. this._modelConfiguration = deepmerge(this._viewer.configuration.model || {}, modelConfiguration);
  98137. this._viewer.sceneManager.models.push(this);
  98138. this._viewer.onModelAddedObservable.notifyObservers(this);
  98139. this.onLoadedObservable.add(function () {
  98140. _this.updateConfiguration(_this._modelConfiguration);
  98141. _this._viewer.onModelLoadedObservable.notifyObservers(_this);
  98142. _this._initAnimations();
  98143. });
  98144. this.onCompleteObservable.add(function () {
  98145. _this.state = ModelState.COMPLETE;
  98146. });
  98147. }
  98148. Object.defineProperty(ViewerModel.prototype, "enabled", {
  98149. /**
  98150. * Is this model enabled?
  98151. */
  98152. get: function () {
  98153. return this.rootMesh.isEnabled();
  98154. },
  98155. /**
  98156. * Set whether this model is enabled or not.
  98157. */
  98158. set: function (enable) {
  98159. this.rootMesh.setEnabled(enable);
  98160. },
  98161. enumerable: true,
  98162. configurable: true
  98163. });
  98164. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  98165. set: function (done) {
  98166. this._loaderDone = done;
  98167. this._checkCompleteState();
  98168. },
  98169. enumerable: true,
  98170. configurable: true
  98171. });
  98172. ViewerModel.prototype._checkCompleteState = function () {
  98173. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  98174. this._modelComplete();
  98175. }
  98176. };
  98177. /**
  98178. * Get the viewer showing this model
  98179. */
  98180. ViewerModel.prototype.getViewer = function () {
  98181. return this._viewer;
  98182. };
  98183. /**
  98184. * Add a mesh to this model.
  98185. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  98186. *
  98187. * @param mesh the new mesh to add
  98188. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  98189. */
  98190. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  98191. if (!mesh.parent) {
  98192. mesh.parent = this._pivotMesh;
  98193. }
  98194. mesh.receiveShadows = !!this.configuration.receiveShadows;
  98195. this._meshes.push(mesh);
  98196. if (triggerLoaded) {
  98197. return this.onLoadedObservable.notifyObserversWithPromise(this);
  98198. }
  98199. };
  98200. Object.defineProperty(ViewerModel.prototype, "meshes", {
  98201. /**
  98202. * get the list of meshes (excluding the root mesh)
  98203. */
  98204. get: function () {
  98205. return this._meshes;
  98206. },
  98207. enumerable: true,
  98208. configurable: true
  98209. });
  98210. Object.defineProperty(ViewerModel.prototype, "configuration", {
  98211. /**
  98212. * Get the model's configuration
  98213. */
  98214. get: function () {
  98215. return this._modelConfiguration;
  98216. },
  98217. /**
  98218. * (Re-)set the model's entire configuration
  98219. * @param newConfiguration the new configuration to replace the new one
  98220. */
  98221. set: function (newConfiguration) {
  98222. this._modelConfiguration = newConfiguration;
  98223. this._configureModel();
  98224. },
  98225. enumerable: true,
  98226. configurable: true
  98227. });
  98228. /**
  98229. * Update the current configuration with new values.
  98230. * Configuration will not be overwritten, but merged with the new configuration.
  98231. * Priority is to the new configuration
  98232. * @param newConfiguration the configuration to be merged into the current configuration;
  98233. */
  98234. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  98235. this._modelConfiguration = deepmerge(this._modelConfiguration, newConfiguration);
  98236. this._configureModel();
  98237. };
  98238. ViewerModel.prototype._initAnimations = function () {
  98239. var _this = this;
  98240. // check if this is not a gltf loader and init the animations
  98241. if (this.skeletons.length) {
  98242. this.skeletons.forEach(function (skeleton, idx) {
  98243. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._viewer.sceneManager.scene);
  98244. skeleton.getAnimatables().forEach(function (a) {
  98245. if (a.animations[0]) {
  98246. ag.addTargetedAnimation(a.animations[0], a);
  98247. }
  98248. });
  98249. _this.addAnimationGroup(ag);
  98250. });
  98251. }
  98252. var completeCallback = function () {
  98253. };
  98254. if (this._modelConfiguration.animation) {
  98255. if (this._modelConfiguration.animation.playOnce) {
  98256. this._animations.forEach(function (a) {
  98257. a.playMode = 0 /* ONCE */;
  98258. });
  98259. }
  98260. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  98261. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  98262. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  98263. completeCallback = function () {
  98264. _this.playAnimation(animationName_1);
  98265. };
  98266. }
  98267. }
  98268. this._enterScene(completeCallback);
  98269. };
  98270. /**
  98271. * Animates the model from the current position to the default position
  98272. * @param completeCallback A function to call when the animation has completed
  98273. */
  98274. ViewerModel.prototype._enterScene = function (completeCallback) {
  98275. var _this = this;
  98276. var callback = function () {
  98277. _this.state = ModelState.ENTRYDONE;
  98278. _this._viewer.sceneManager.animationBlendingEnabled = true;
  98279. _this._checkCompleteState();
  98280. if (completeCallback)
  98281. completeCallback();
  98282. };
  98283. if (!this._entryAnimation) {
  98284. callback();
  98285. return;
  98286. }
  98287. // disable blending for the sake of the entry animation;
  98288. this._viewer.sceneManager.animationBlendingEnabled = false;
  98289. this._applyAnimation(this._entryAnimation, true, callback);
  98290. };
  98291. /**
  98292. * Animates the model from the current position to the exit-screen position
  98293. * @param completeCallback A function to call when the animation has completed
  98294. */
  98295. ViewerModel.prototype._exitScene = function (completeCallback) {
  98296. if (!this._exitAnimation) {
  98297. completeCallback();
  98298. return;
  98299. }
  98300. this._applyAnimation(this._exitAnimation, false, completeCallback);
  98301. };
  98302. ViewerModel.prototype._modelComplete = function () {
  98303. var _this = this;
  98304. //reapply material defines to be sure:
  98305. var meshes = this._pivotMesh.getChildMeshes(false);
  98306. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98307. _this._applyModelMaterialConfiguration(mesh.material);
  98308. });
  98309. this.state = ModelState.COMPLETE;
  98310. this.onCompleteObservable.notifyObservers(this);
  98311. };
  98312. /**
  98313. * Add a new animation group to this model.
  98314. * @param animationGroup the new animation group to be added
  98315. */
  98316. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  98317. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  98318. };
  98319. /**
  98320. * Get the ModelAnimation array
  98321. */
  98322. ViewerModel.prototype.getAnimations = function () {
  98323. return this._animations;
  98324. };
  98325. /**
  98326. * Get the animations' names. Using the names you can play a specific animation.
  98327. */
  98328. ViewerModel.prototype.getAnimationNames = function () {
  98329. return this._animations.map(function (a) { return a.name; });
  98330. };
  98331. /**
  98332. * Get an animation by the provided name. Used mainly when playing n animation.
  98333. * @param name the name of the animation to find
  98334. */
  98335. ViewerModel.prototype._getAnimationByName = function (name) {
  98336. // can't use .find, noe available on IE
  98337. var filtered = this._animations.filter(function (a) { return a.name === name; });
  98338. // what the next line means - if two animations have the same name, they will not be returned!
  98339. if (filtered.length === 1) {
  98340. return filtered[0];
  98341. }
  98342. else {
  98343. return null;
  98344. }
  98345. };
  98346. /**
  98347. * Choose an initialized animation using its name and start playing it
  98348. * @param name the name of the animation to play
  98349. * @returns The model aniamtion to be played.
  98350. */
  98351. ViewerModel.prototype.playAnimation = function (name) {
  98352. var animation = this.setCurrentAnimationByName(name);
  98353. if (animation) {
  98354. animation.start();
  98355. }
  98356. return animation;
  98357. };
  98358. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  98359. var animation = this._getAnimationByName(name);
  98360. if (animation) {
  98361. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  98362. this.currentAnimation.stop();
  98363. }
  98364. this.currentAnimation = animation;
  98365. return animation;
  98366. }
  98367. else {
  98368. throw new Error("animation not found - " + name);
  98369. }
  98370. };
  98371. ViewerModel.prototype._configureModel = function () {
  98372. var _this = this;
  98373. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  98374. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  98375. var updateMeshesWithNoParent = function (variable, value, param) {
  98376. meshesWithNoParent.forEach(function (mesh) {
  98377. if (param) {
  98378. mesh[variable][param] = value;
  98379. }
  98380. else {
  98381. mesh[variable] = value;
  98382. }
  98383. });
  98384. };
  98385. var updateXYZ = function (variable, configValues) {
  98386. if (configValues.x !== undefined) {
  98387. updateMeshesWithNoParent(variable, configValues.x, 'x');
  98388. }
  98389. if (configValues.y !== undefined) {
  98390. updateMeshesWithNoParent(variable, configValues.y, 'y');
  98391. }
  98392. if (configValues.z !== undefined) {
  98393. updateMeshesWithNoParent(variable, configValues.z, 'z');
  98394. }
  98395. if (configValues.w !== undefined) {
  98396. updateMeshesWithNoParent(variable, configValues.w, 'w');
  98397. }
  98398. };
  98399. if (this._modelConfiguration.normalize) {
  98400. var center = false;
  98401. var unitSize = false;
  98402. var parentIndex = void 0;
  98403. if (this._modelConfiguration.normalize === true) {
  98404. center = true;
  98405. unitSize = true;
  98406. }
  98407. else {
  98408. center = !!this._modelConfiguration.normalize.center;
  98409. unitSize = !!this._modelConfiguration.normalize.unitSize;
  98410. parentIndex = this._modelConfiguration.normalize.parentIndex;
  98411. }
  98412. var meshesToNormalize = [];
  98413. if (parentIndex !== undefined) {
  98414. meshesToNormalize.push(this._meshes[parentIndex]);
  98415. }
  98416. else {
  98417. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  98418. }
  98419. if (unitSize) {
  98420. meshesToNormalize.forEach(function (mesh) {
  98421. mesh.normalizeToUnitCube(true);
  98422. mesh.computeWorldMatrix(true);
  98423. });
  98424. }
  98425. if (center) {
  98426. meshesToNormalize.forEach(function (mesh) {
  98427. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  98428. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  98429. var halfSizeVec = sizeVec.scale(0.5);
  98430. var center = boundingInfo.min.add(halfSizeVec);
  98431. mesh.position = center.scale(-1);
  98432. mesh.position.y += halfSizeVec.y;
  98433. // Recompute Info.
  98434. mesh.computeWorldMatrix(true);
  98435. });
  98436. }
  98437. }
  98438. else {
  98439. // if centered, should be done here
  98440. }
  98441. // position?
  98442. if (this._modelConfiguration.position) {
  98443. updateXYZ('position', this._modelConfiguration.position);
  98444. }
  98445. if (this._modelConfiguration.rotation) {
  98446. //quaternion?
  98447. if (this._modelConfiguration.rotation.w) {
  98448. meshesWithNoParent.forEach(function (mesh) {
  98449. if (!mesh.rotationQuaternion) {
  98450. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  98451. }
  98452. });
  98453. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  98454. }
  98455. else {
  98456. updateXYZ('rotation', this._modelConfiguration.rotation);
  98457. }
  98458. }
  98459. if (this._modelConfiguration.rotationOffsetAxis) {
  98460. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  98461. meshesWithNoParent.forEach(function (m) {
  98462. if (_this._modelConfiguration.rotationOffsetAngle) {
  98463. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  98464. }
  98465. });
  98466. }
  98467. if (this._modelConfiguration.scaling) {
  98468. updateXYZ('scaling', this._modelConfiguration.scaling);
  98469. }
  98470. if (this._modelConfiguration.castShadow) {
  98471. this._meshes.forEach(function (mesh) {
  98472. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  98473. });
  98474. }
  98475. var meshes = this._pivotMesh.getChildMeshes(false);
  98476. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  98477. _this._applyModelMaterialConfiguration(mesh.material);
  98478. });
  98479. if (this._modelConfiguration.entryAnimation) {
  98480. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  98481. }
  98482. if (this._modelConfiguration.exitAnimation) {
  98483. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  98484. }
  98485. this.onAfterConfigure.notifyObservers(this);
  98486. };
  98487. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  98488. var anim = {
  98489. time: 0.5
  98490. };
  98491. if (animConfig.scaling) {
  98492. anim.scaling = babylonjs_1.Vector3.Zero();
  98493. }
  98494. if (animConfig.easingFunction !== undefined) {
  98495. anim.easingFunction = animConfig.easingFunction;
  98496. }
  98497. if (animConfig.easingMode !== undefined) {
  98498. anim.easingMode = animConfig.easingMode;
  98499. }
  98500. helper_1.extendClassWithConfig(anim, animConfig);
  98501. return anim;
  98502. };
  98503. /**
  98504. * Apply a material configuration to a material
  98505. * @param material Material to apply configuration to
  98506. */
  98507. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  98508. if (!this._modelConfiguration.material)
  98509. return;
  98510. helper_1.extendClassWithConfig(material, this._modelConfiguration.material);
  98511. if (material instanceof babylonjs_1.PBRMaterial) {
  98512. if (this._modelConfiguration.material.directIntensity !== undefined) {
  98513. material.directIntensity = this._modelConfiguration.material.directIntensity;
  98514. }
  98515. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  98516. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  98517. }
  98518. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  98519. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  98520. }
  98521. if (this._modelConfiguration.material.directEnabled !== undefined) {
  98522. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  98523. }
  98524. if (this._viewer.sceneManager.reflectionColor) {
  98525. material.reflectionColor = this._viewer.sceneManager.reflectionColor;
  98526. }
  98527. }
  98528. else if (material instanceof babylonjs_1.MultiMaterial) {
  98529. for (var i = 0; i < material.subMaterials.length; i++) {
  98530. var subMaterial = material.subMaterials[i];
  98531. if (subMaterial) {
  98532. this._applyModelMaterialConfiguration(subMaterial);
  98533. }
  98534. }
  98535. }
  98536. };
  98537. /**
  98538. * Start entry/exit animation given an animation configuration
  98539. * @param animationConfiguration Entry/Exit animation configuration
  98540. * @param isEntry Pass true if the animation is an entry animation
  98541. * @param completeCallback Callback to execute when the animation completes
  98542. */
  98543. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  98544. var animations = [];
  98545. //scale
  98546. if (animationConfiguration.scaling) {
  98547. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  98548. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  98549. if (!scaleStart.equals(scaleEnd)) {
  98550. this.rootMesh.scaling = scaleStart;
  98551. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  98552. animations.push(this._scaleTransition);
  98553. }
  98554. }
  98555. //Start the animation(s)
  98556. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  98557. completeCallback(); });
  98558. };
  98559. /**
  98560. * Begin @animations with the specified @easingFunction
  98561. * @param animations The BABYLON Animations to begin
  98562. * @param duration of transition, in seconds
  98563. * @param easingFunction An easing function to apply
  98564. * @param easingMode A easing mode to apply to the easingFunction
  98565. * @param onAnimationEnd Call back trigger at the end of the animation.
  98566. */
  98567. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  98568. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  98569. if (easingFunction) {
  98570. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  98571. var animation = animations_1[_i];
  98572. easingFunction.setEasingMode(easingMode);
  98573. animation.setEasingFunction(easingFunction);
  98574. }
  98575. }
  98576. //Stop any current animations before starting the new one - merging not yet supported.
  98577. this.stopAllAnimations();
  98578. this.rootMesh.animations = animations;
  98579. if (this._viewer.sceneManager.scene.beginAnimation) {
  98580. var animatable = this._viewer.sceneManager.scene.beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  98581. if (onAnimationEnd) {
  98582. onAnimationEnd();
  98583. }
  98584. });
  98585. this._animatables.push(animatable);
  98586. }
  98587. };
  98588. /**
  98589. * Sets key values on an Animation from first to last frame.
  98590. * @param animation The Babylon animation object to set keys on
  98591. * @param startValue The value of the first key
  98592. * @param endValue The value of the last key
  98593. * @param duration The duration of the animation, used to determine the end frame
  98594. */
  98595. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  98596. animation.setKeys([
  98597. {
  98598. frame: 0,
  98599. value: startValue
  98600. },
  98601. {
  98602. frame: this._frameRate * duration,
  98603. value: endValue
  98604. }
  98605. ]);
  98606. };
  98607. /**
  98608. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  98609. * @param easingFunctionID The enum of the easing funtion to create
  98610. * @return The newly created Babylon easing function object
  98611. */
  98612. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  98613. var easingFunction;
  98614. switch (easingFunctionID) {
  98615. case 1 /* CircleEase */:
  98616. easingFunction = new babylonjs_1.CircleEase();
  98617. break;
  98618. case 2 /* BackEase */:
  98619. easingFunction = new babylonjs_1.BackEase(0.3);
  98620. break;
  98621. case 3 /* BounceEase */:
  98622. easingFunction = new babylonjs_1.BounceEase();
  98623. break;
  98624. case 4 /* CubicEase */:
  98625. easingFunction = new babylonjs_1.CubicEase();
  98626. break;
  98627. case 5 /* ElasticEase */:
  98628. easingFunction = new babylonjs_1.ElasticEase();
  98629. break;
  98630. case 6 /* ExponentialEase */:
  98631. easingFunction = new babylonjs_1.ExponentialEase();
  98632. break;
  98633. case 7 /* PowerEase */:
  98634. easingFunction = new babylonjs_1.PowerEase();
  98635. break;
  98636. case 8 /* QuadraticEase */:
  98637. easingFunction = new babylonjs_1.QuadraticEase();
  98638. break;
  98639. case 9 /* QuarticEase */:
  98640. easingFunction = new babylonjs_1.QuarticEase();
  98641. break;
  98642. case 10 /* QuinticEase */:
  98643. easingFunction = new babylonjs_1.QuinticEase();
  98644. break;
  98645. case 11 /* SineEase */:
  98646. easingFunction = new babylonjs_1.SineEase();
  98647. break;
  98648. default:
  98649. babylonjs_1.Tools.Log("No ease function found");
  98650. break;
  98651. }
  98652. return easingFunction;
  98653. };
  98654. /**
  98655. * Stops and removes all animations that have been applied to the model
  98656. */
  98657. ViewerModel.prototype.stopAllAnimations = function () {
  98658. if (this.rootMesh) {
  98659. this.rootMesh.animations = [];
  98660. }
  98661. if (this.currentAnimation) {
  98662. this.currentAnimation.stop();
  98663. }
  98664. while (this._animatables.length) {
  98665. this._animatables[0].onAnimationEnd = null;
  98666. this._animatables[0].stop();
  98667. this._animatables.shift();
  98668. }
  98669. };
  98670. /**
  98671. * Will remove this model from the viewer (but NOT dispose it).
  98672. */
  98673. ViewerModel.prototype.remove = function () {
  98674. this.stopAllAnimations();
  98675. this._viewer.sceneManager.models.splice(this._viewer.sceneManager.models.indexOf(this), 1);
  98676. // hide it
  98677. this.rootMesh.isVisible = false;
  98678. this._viewer.onModelRemovedObservable.notifyObservers(this);
  98679. };
  98680. /**
  98681. * Dispose this model, including all of its associated assets.
  98682. */
  98683. ViewerModel.prototype.dispose = function () {
  98684. this.remove();
  98685. this.onAfterConfigure.clear();
  98686. this.onLoadedObservable.clear();
  98687. this.onLoadErrorObservable.clear();
  98688. this.onLoadProgressObservable.clear();
  98689. if (this.loader && this.loader.name === "gltf") {
  98690. this.loader.dispose();
  98691. }
  98692. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  98693. this.particleSystems.length = 0;
  98694. this.skeletons.forEach(function (s) { return s.dispose(); });
  98695. this.skeletons.length = 0;
  98696. this._animations.forEach(function (ag) { return ag.dispose(); });
  98697. this._animations.length = 0;
  98698. this.rootMesh.dispose(false, true);
  98699. };
  98700. return ViewerModel;
  98701. }());
  98702. exports.ViewerModel = ViewerModel;
  98703. /***/ }),
  98704. /* 5 */
  98705. /***/ (function(module, exports, __webpack_require__) {
  98706. "use strict";
  98707. Object.defineProperty(exports, "__esModule", { value: true });
  98708. var babylonjs_1 = __webpack_require__(0);
  98709. /**
  98710. * Receives Telemetry events and raises events to the API
  98711. */
  98712. var TelemetryManager = /** @class */ (function () {
  98713. function TelemetryManager() {
  98714. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  98715. this._event = this._eventEnabled;
  98716. }
  98717. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  98718. /**
  98719. * Receives a telemetry event
  98720. * @param event The name of the Telemetry event
  98721. * @param details An additional value, or an object containing a list of property/value pairs
  98722. */
  98723. get: function () {
  98724. return this._event;
  98725. },
  98726. enumerable: true,
  98727. configurable: true
  98728. });
  98729. /**
  98730. * Log a Telemetry event for errors raised on the WebGL context.
  98731. * @param engine The Babylon engine with the WebGL context.
  98732. */
  98733. TelemetryManager.prototype.flushWebGLErrors = function (viewer) {
  98734. var engine = viewer.engine;
  98735. if (!engine) {
  98736. return;
  98737. }
  98738. var logErrors = true;
  98739. while (logErrors) {
  98740. var gl = engine._gl;
  98741. if (gl && gl.getError) {
  98742. var error = gl.getError();
  98743. if (error === gl.NO_ERROR) {
  98744. logErrors = false;
  98745. }
  98746. else {
  98747. this.broadcast("WebGL Error", viewer, { error: error });
  98748. }
  98749. }
  98750. else {
  98751. logErrors = false;
  98752. }
  98753. }
  98754. };
  98755. Object.defineProperty(TelemetryManager.prototype, "enable", {
  98756. /**
  98757. * Enable or disable telemetry events
  98758. * @param enabled Boolan, true if events are enabled
  98759. */
  98760. set: function (enabled) {
  98761. if (enabled) {
  98762. this._event = this._eventEnabled;
  98763. }
  98764. else {
  98765. this._event = this._eventDisabled;
  98766. }
  98767. },
  98768. enumerable: true,
  98769. configurable: true
  98770. });
  98771. /**
  98772. * Called on event when disabled, typically do nothing here
  98773. */
  98774. TelemetryManager.prototype._eventDisabled = function () {
  98775. // nothing to do
  98776. };
  98777. /**
  98778. * Called on event when enabled
  98779. * @param event - The name of the Telemetry event
  98780. * @param details An additional value, or an object containing a list of property/value pairs
  98781. */
  98782. TelemetryManager.prototype._eventEnabled = function (event, viewer, details) {
  98783. var telemetryData = {
  98784. viewer: viewer,
  98785. event: event,
  98786. session: this.session,
  98787. date: new Date(),
  98788. now: window.performance ? window.performance.now() : Date.now(),
  98789. detail: null
  98790. };
  98791. if (typeof details === "object") {
  98792. for (var attr in details) {
  98793. if (details.hasOwnProperty(attr)) {
  98794. telemetryData[attr] = details[attr];
  98795. }
  98796. }
  98797. }
  98798. else if (details) {
  98799. telemetryData.detail = details;
  98800. }
  98801. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  98802. };
  98803. Object.defineProperty(TelemetryManager.prototype, "session", {
  98804. /**
  98805. * Returns the current session ID or creates one if it doesn't exixt
  98806. * @return The current session ID
  98807. */
  98808. get: function () {
  98809. if (!this._currentSessionId) {
  98810. //String + Timestamp + Random Integer
  98811. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  98812. }
  98813. return this._currentSessionId;
  98814. },
  98815. enumerable: true,
  98816. configurable: true
  98817. });
  98818. TelemetryManager.prototype.dispose = function () {
  98819. this.onEventBroadcastedObservable.clear();
  98820. delete this.onEventBroadcastedObservable;
  98821. };
  98822. return TelemetryManager;
  98823. }());
  98824. exports.TelemetryManager = TelemetryManager;
  98825. exports.telemetryManager = new TelemetryManager();
  98826. /***/ }),
  98827. /* 6 */
  98828. /***/ (function(module, exports, __webpack_require__) {
  98829. "use strict";
  98830. Object.defineProperty(exports, "__esModule", { value: true });
  98831. /// <reference path="../../dist/babylon.glTF2Interface.d.ts"/>
  98832. var mappers_1 = __webpack_require__(3);
  98833. exports.mapperManager = mappers_1.mapperManager;
  98834. var globals_1 = __webpack_require__(7);
  98835. exports.viewerGlobals = globals_1.viewerGlobals;
  98836. var viewerManager_1 = __webpack_require__(8);
  98837. exports.viewerManager = viewerManager_1.viewerManager;
  98838. var defaultViewer_1 = __webpack_require__(9);
  98839. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  98840. var viewer_1 = __webpack_require__(10);
  98841. exports.AbstractViewer = viewer_1.AbstractViewer;
  98842. var telemetryManager_1 = __webpack_require__(5);
  98843. exports.telemetryManager = telemetryManager_1.telemetryManager;
  98844. var modelLoader_1 = __webpack_require__(19);
  98845. exports.ModelLoader = modelLoader_1.ModelLoader;
  98846. var viewerModel_1 = __webpack_require__(4);
  98847. exports.ViewerModel = viewerModel_1.ViewerModel;
  98848. exports.ModelState = viewerModel_1.ModelState;
  98849. /**
  98850. * BabylonJS Viewer
  98851. *
  98852. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  98853. */
  98854. var BABYLON = __webpack_require__(0);
  98855. exports.BABYLON = BABYLON;
  98856. // load needed modules.
  98857. __webpack_require__(20);
  98858. __webpack_require__(53);
  98859. var initializer_1 = __webpack_require__(54);
  98860. exports.InitTags = initializer_1.InitTags;
  98861. // promise polyfill, if needed!
  98862. BABYLON.PromisePolyfill.Apply();
  98863. initializer_1.initListeners();
  98864. //deprectaed, here for backwards compatibility
  98865. var disableInit = globals_1.viewerGlobals.disableInit;
  98866. exports.disableInit = disableInit;
  98867. /**
  98868. * Dispose all viewers currently registered
  98869. */
  98870. function disposeAll() {
  98871. viewerManager_1.viewerManager.dispose();
  98872. mappers_1.mapperManager.dispose();
  98873. telemetryManager_1.telemetryManager.dispose();
  98874. }
  98875. exports.disposeAll = disposeAll;
  98876. var Version = BABYLON.Engine.Version;
  98877. exports.Version = Version;
  98878. console.log("Babylon.js viewer (v" + Version + ")");
  98879. /***/ }),
  98880. /* 7 */
  98881. /***/ (function(module, exports, __webpack_require__) {
  98882. "use strict";
  98883. Object.defineProperty(exports, "__esModule", { value: true });
  98884. var ViewerGlobals = /** @class */ (function () {
  98885. function ViewerGlobals() {
  98886. this.disableInit = false;
  98887. this.disableWebGL2Support = false;
  98888. }
  98889. return ViewerGlobals;
  98890. }());
  98891. exports.ViewerGlobals = ViewerGlobals;
  98892. exports.viewerGlobals = new ViewerGlobals();
  98893. /***/ }),
  98894. /* 8 */
  98895. /***/ (function(module, exports, __webpack_require__) {
  98896. "use strict";
  98897. Object.defineProperty(exports, "__esModule", { value: true });
  98898. var babylonjs_1 = __webpack_require__(0);
  98899. /**
  98900. * The viewer manager is the container for all viewers currently registered on this page.
  98901. * It is possible to have more than one viewer on a single page.
  98902. */
  98903. var ViewerManager = /** @class */ (function () {
  98904. function ViewerManager() {
  98905. this._viewers = {};
  98906. this.onViewerAddedObservable = new babylonjs_1.Observable();
  98907. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  98908. }
  98909. /**
  98910. * Adding a new viewer to the viewer manager and start tracking it.
  98911. * @param viewer the viewer to add
  98912. */
  98913. ViewerManager.prototype.addViewer = function (viewer) {
  98914. this._viewers[viewer.getBaseId()] = viewer;
  98915. this._onViewerAdded(viewer);
  98916. };
  98917. /**
  98918. * remove a viewer from the viewer manager
  98919. * @param viewer the viewer to remove
  98920. */
  98921. ViewerManager.prototype.removeViewer = function (viewer) {
  98922. var id = viewer.getBaseId();
  98923. delete this._viewers[id];
  98924. this.onViewerRemovedObservable.notifyObservers(id);
  98925. };
  98926. /**
  98927. * 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)
  98928. * @param id the id of the HTMl element (or the viewer's, if none provided)
  98929. */
  98930. ViewerManager.prototype.getViewerById = function (id) {
  98931. return this._viewers[id];
  98932. };
  98933. /**
  98934. * Get a viewer using a container element
  98935. * @param element the HTML element to search viewers associated with
  98936. */
  98937. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  98938. for (var id in this._viewers) {
  98939. if (this._viewers[id].containerElement === element) {
  98940. return this.getViewerById(id);
  98941. }
  98942. }
  98943. };
  98944. /**
  98945. * Get a promise that will fullfil when this viewer was initialized.
  98946. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  98947. * you will get the viewer after everything was already configured.
  98948. * @param id the viewer id to find
  98949. */
  98950. ViewerManager.prototype.getViewerPromiseById = function (id) {
  98951. var _this = this;
  98952. return new Promise(function (resolve, reject) {
  98953. var localViewer = _this.getViewerById(id);
  98954. if (localViewer) {
  98955. return resolve(localViewer);
  98956. }
  98957. var viewerFunction = function (viewer) {
  98958. if (viewer.getBaseId() === id) {
  98959. resolve(viewer);
  98960. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  98961. }
  98962. };
  98963. _this.onViewerAddedObservable.add(viewerFunction);
  98964. });
  98965. };
  98966. ViewerManager.prototype._onViewerAdded = function (viewer) {
  98967. this.onViewerAdded && this.onViewerAdded(viewer);
  98968. this.onViewerAddedObservable.notifyObservers(viewer);
  98969. };
  98970. /**
  98971. * dispose the manager and all of its associated viewers
  98972. */
  98973. ViewerManager.prototype.dispose = function () {
  98974. for (var id in this._viewers) {
  98975. this._viewers[id].dispose();
  98976. }
  98977. };
  98978. return ViewerManager;
  98979. }());
  98980. exports.ViewerManager = ViewerManager;
  98981. exports.viewerManager = new ViewerManager();
  98982. /***/ }),
  98983. /* 9 */
  98984. /***/ (function(module, exports, __webpack_require__) {
  98985. "use strict";
  98986. var __extends = (this && this.__extends) || (function () {
  98987. var extendStatics = Object.setPrototypeOf ||
  98988. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  98989. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  98990. return function (d, b) {
  98991. extendStatics(d, b);
  98992. function __() { this.constructor = d; }
  98993. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  98994. };
  98995. })();
  98996. Object.defineProperty(exports, "__esModule", { value: true });
  98997. var viewer_1 = __webpack_require__(10);
  98998. var babylonjs_1 = __webpack_require__(0);
  98999. /**
  99000. * The Default viewer is the default implementation of the AbstractViewer.
  99001. * It uses the templating system to render a new canvas and controls.
  99002. */
  99003. var DefaultViewer = /** @class */ (function (_super) {
  99004. __extends(DefaultViewer, _super);
  99005. /**
  99006. * Create a new default viewer
  99007. * @param containerElement the element in which the templates will be rendered
  99008. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  99009. */
  99010. function DefaultViewer(containerElement, initialConfiguration) {
  99011. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  99012. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  99013. _this.containerElement = containerElement;
  99014. _this._handlePointerDown = function (event) {
  99015. var pointerDown = event.event;
  99016. if (pointerDown.button !== 0)
  99017. return;
  99018. var element = event.event.srcElement;
  99019. if (!element) {
  99020. return;
  99021. }
  99022. var parentClasses = element.parentElement.classList;
  99023. switch (element.id) {
  99024. case "speed-button":
  99025. case "types-button":
  99026. if (parentClasses.contains("open")) {
  99027. parentClasses.remove("open");
  99028. }
  99029. else {
  99030. parentClasses.add("open");
  99031. }
  99032. break;
  99033. case "play-pause-button":
  99034. _this._togglePlayPause();
  99035. break;
  99036. case "label-option-button":
  99037. var label = element.dataset["value"];
  99038. if (label) {
  99039. _this._updateAnimationType(label);
  99040. }
  99041. break;
  99042. case "speed-option-button":
  99043. if (!_this._currentAnimation) {
  99044. return;
  99045. }
  99046. var speed = element.dataset["value"];
  99047. if (speed)
  99048. _this._updateAnimationSpeed(speed);
  99049. break;
  99050. case "progress-wrapper":
  99051. _this._resumePlay = !_this._isAnimationPaused;
  99052. if (_this._resumePlay) {
  99053. _this._togglePlayPause(true);
  99054. }
  99055. break;
  99056. case "fullscreen-button":
  99057. _this.toggleFullscreen();
  99058. default:
  99059. return;
  99060. }
  99061. };
  99062. /**
  99063. * Plays or Pauses animation
  99064. */
  99065. _this._togglePlayPause = function (noUiUpdate) {
  99066. if (!_this._currentAnimation) {
  99067. return;
  99068. }
  99069. if (_this._isAnimationPaused) {
  99070. _this._currentAnimation.restart();
  99071. }
  99072. else {
  99073. _this._currentAnimation.pause();
  99074. }
  99075. _this._isAnimationPaused = !_this._isAnimationPaused;
  99076. if (noUiUpdate)
  99077. return;
  99078. var navbar = _this.templateManager.getTemplate('navBar');
  99079. if (!navbar)
  99080. return;
  99081. navbar.updateParams({
  99082. paused: _this._isAnimationPaused,
  99083. });
  99084. };
  99085. /**
  99086. * Control progress bar position based on animation current frame
  99087. */
  99088. _this._updateProgressBar = function () {
  99089. var navbar = _this.templateManager.getTemplate('navBar');
  99090. if (!navbar)
  99091. return;
  99092. var progressSlider = navbar.parent.querySelector("input#progress-wrapper");
  99093. if (progressSlider && _this._currentAnimation) {
  99094. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  99095. var currentValue = progressSlider.valueAsNumber;
  99096. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  99097. progressSlider.value = '' + progress;
  99098. }
  99099. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  99100. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  99101. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  99102. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  99103. }
  99104. }
  99105. else {
  99106. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  99107. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  99108. _this._oldIdleRotationValue = 0;
  99109. }
  99110. }
  99111. }
  99112. };
  99113. /**
  99114. * Update Current Animation Speed
  99115. */
  99116. _this._updateAnimationSpeed = function (speed, paramsObject) {
  99117. var navbar = _this.templateManager.getTemplate('navBar');
  99118. if (!navbar)
  99119. return;
  99120. if (speed && _this._currentAnimation) {
  99121. _this._currentAnimation.speedRatio = parseFloat(speed);
  99122. if (!_this._isAnimationPaused) {
  99123. _this._currentAnimation.restart();
  99124. }
  99125. if (paramsObject) {
  99126. paramsObject.selectedSpeed = speed + "x";
  99127. }
  99128. else {
  99129. navbar.updateParams({
  99130. selectedSpeed: speed + "x",
  99131. });
  99132. }
  99133. }
  99134. };
  99135. /**
  99136. * Update Current Animation Type
  99137. */
  99138. _this._updateAnimationType = function (label, paramsObject) {
  99139. var navbar = _this.templateManager.getTemplate('navBar');
  99140. if (!navbar)
  99141. return;
  99142. if (label) {
  99143. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(label);
  99144. }
  99145. if (paramsObject) {
  99146. paramsObject.selectedAnimation = (_this._animationList.indexOf(label) + 1);
  99147. paramsObject.selectedAnimationName = label;
  99148. }
  99149. else {
  99150. navbar.updateParams({
  99151. selectedAnimation: (_this._animationList.indexOf(label) + 1),
  99152. selectedAnimationName: label
  99153. });
  99154. }
  99155. _this._updateAnimationSpeed("1.0", paramsObject);
  99156. };
  99157. /**
  99158. * Toggle fullscreen of the entire viewer
  99159. */
  99160. _this.toggleFullscreen = function () {
  99161. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  99162. var viewerElement = viewerTemplate && viewerTemplate.parent;
  99163. if (viewerElement) {
  99164. var fullscreenElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  99165. if (!fullscreenElement) {
  99166. var requestFullScreen = viewerElement.requestFullscreen || viewerElement.webkitRequestFullscreen || viewerElement.msRequestFullscreen || viewerElement.mozRequestFullScreen;
  99167. requestFullScreen.call(viewerElement);
  99168. }
  99169. else {
  99170. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  99171. exitFullscreen.call(document);
  99172. }
  99173. }
  99174. };
  99175. _this._onModelLoaded = function (model) {
  99176. _this._configureTemplate(model);
  99177. // with a short timeout, making sure everything is there already.
  99178. var hideLoadingDelay = 20;
  99179. if (_this._configuration.lab && _this._configuration.lab.hideLoadingDelay !== undefined) {
  99180. hideLoadingDelay = _this._configuration.lab.hideLoadingDelay;
  99181. }
  99182. setTimeout(function () {
  99183. _this.sceneManager.scene.executeWhenReady(function () {
  99184. _this.hideLoadingScreen();
  99185. });
  99186. }, hideLoadingDelay);
  99187. return;
  99188. };
  99189. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  99190. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  99191. _this._configureLights(data.newConfiguration, data.model);
  99192. });
  99193. return _this;
  99194. }
  99195. /**
  99196. * This will be executed when the templates initialize.
  99197. */
  99198. DefaultViewer.prototype._onTemplatesLoaded = function () {
  99199. var _this = this;
  99200. this.showLoadingScreen();
  99201. // navbar
  99202. this._initNavbar();
  99203. // close overlay button
  99204. var closeButton = document.getElementById('close-button');
  99205. if (closeButton) {
  99206. closeButton.addEventListener('pointerdown', function () {
  99207. _this.hideOverlayScreen();
  99208. });
  99209. }
  99210. return _super.prototype._onTemplatesLoaded.call(this);
  99211. };
  99212. DefaultViewer.prototype._initNavbar = function () {
  99213. var _this = this;
  99214. var navbar = this.templateManager.getTemplate('navBar');
  99215. if (navbar) {
  99216. this.onFrameRenderedObservable.add(this._updateProgressBar);
  99217. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  99218. // an example how to trigger the help button. publiclly available
  99219. this.templateManager.eventManager.registerCallback("navBar", function () {
  99220. // do your thing
  99221. }, "pointerdown", "#help-button");
  99222. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  99223. var element = event.event.srcElement;
  99224. if (!_this._currentAnimation)
  99225. return;
  99226. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  99227. if (isNaN(gotoFrame))
  99228. return;
  99229. _this._currentAnimation.goToFrame(gotoFrame);
  99230. }, "input");
  99231. this.templateManager.eventManager.registerCallback("navBar", function (e) {
  99232. if (_this._resumePlay) {
  99233. _this._togglePlayPause(true);
  99234. }
  99235. _this._resumePlay = false;
  99236. }, "pointerup", "#progress-wrapper");
  99237. }
  99238. };
  99239. /**
  99240. * Preparing the container element to present the viewer
  99241. */
  99242. DefaultViewer.prototype._prepareContainerElement = function () {
  99243. this.containerElement.style.position = 'relative';
  99244. this.containerElement.style.height = '100%';
  99245. this.containerElement.style.display = 'flex';
  99246. };
  99247. /**
  99248. * This function will configure the templates and update them after a model was loaded
  99249. * It is mainly responsible to changing the title and subtitle etc'.
  99250. * @param model the model to be used to configure the templates by
  99251. */
  99252. DefaultViewer.prototype._configureTemplate = function (model) {
  99253. var navbar = this.templateManager.getTemplate('navBar');
  99254. if (!navbar)
  99255. return;
  99256. var newParams = {};
  99257. var animationNames = model.getAnimationNames();
  99258. if (animationNames.length >= 1) {
  99259. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  99260. this._animationList = animationNames;
  99261. newParams.animations = this._animationList;
  99262. newParams.paused = this._isAnimationPaused;
  99263. var animationIndex = 0;
  99264. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  99265. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  99266. if (animationIndex === -1) {
  99267. animationIndex = 0;
  99268. }
  99269. }
  99270. this._updateAnimationType(animationNames[animationIndex], newParams);
  99271. }
  99272. if (model.configuration.thumbnail) {
  99273. newParams.logoImage = model.configuration.thumbnail;
  99274. }
  99275. navbar.updateParams(newParams);
  99276. };
  99277. /**
  99278. * This will load a new model to the default viewer
  99279. * overriding the AbstractViewer's loadModel.
  99280. * The scene will automatically be cleared of the old models, if exist.
  99281. * @param model the configuration object (or URL) to load.
  99282. */
  99283. DefaultViewer.prototype.loadModel = function (model) {
  99284. var _this = this;
  99285. if (!model) {
  99286. model = this.configuration.model;
  99287. }
  99288. this.showLoadingScreen();
  99289. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  99290. console.log(error);
  99291. _this.hideLoadingScreen();
  99292. _this.showOverlayScreen('error');
  99293. return Promise.reject(error);
  99294. });
  99295. };
  99296. /**
  99297. * Show the overlay and the defined sub-screen.
  99298. * Mainly used for help and errors
  99299. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  99300. */
  99301. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  99302. var _this = this;
  99303. var template = this.templateManager.getTemplate('overlay');
  99304. if (!template)
  99305. return Promise.resolve('Overlay template not found');
  99306. return template.show((function (template) {
  99307. var canvasRect = _this.containerElement.getBoundingClientRect();
  99308. template.parent.style.display = 'flex';
  99309. template.parent.style.width = canvasRect.width + "px";
  99310. template.parent.style.height = canvasRect.height + "px";
  99311. template.parent.style.opacity = "1";
  99312. var subTemplate = _this.templateManager.getTemplate(subScreen);
  99313. if (!subTemplate) {
  99314. return Promise.reject(subScreen + ' template not found');
  99315. }
  99316. return subTemplate.show((function (template) {
  99317. template.parent.style.display = 'flex';
  99318. return Promise.resolve(template);
  99319. }));
  99320. }));
  99321. };
  99322. /**
  99323. * Hide the overlay screen.
  99324. */
  99325. DefaultViewer.prototype.hideOverlayScreen = function () {
  99326. var template = this.templateManager.getTemplate('overlay');
  99327. if (!template)
  99328. return Promise.resolve('Overlay template not found');
  99329. return template.hide((function (template) {
  99330. template.parent.style.opacity = "0";
  99331. var onTransitionEnd = function () {
  99332. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99333. template.parent.style.display = 'none';
  99334. };
  99335. template.parent.addEventListener("transitionend", onTransitionEnd);
  99336. var overlays = template.parent.querySelectorAll('.overlay');
  99337. if (overlays) {
  99338. for (var i = 0; i < overlays.length; ++i) {
  99339. var htmlElement = overlays.item(i);
  99340. htmlElement.style.display = 'none';
  99341. }
  99342. }
  99343. return Promise.resolve(template);
  99344. }));
  99345. };
  99346. /**
  99347. * show the viewer (in case it was hidden)
  99348. *
  99349. * @param visibilityFunction an optional function to execute in order to show the container
  99350. */
  99351. DefaultViewer.prototype.show = function (visibilityFunction) {
  99352. var template = this.templateManager.getTemplate('main');
  99353. //not possible, but yet:
  99354. if (!template)
  99355. return Promise.reject('Main template not found');
  99356. return template.show(visibilityFunction);
  99357. };
  99358. /**
  99359. * hide the viewer (in case it is visible)
  99360. *
  99361. * @param visibilityFunction an optional function to execute in order to hide the container
  99362. */
  99363. DefaultViewer.prototype.hide = function (visibilityFunction) {
  99364. var template = this.templateManager.getTemplate('main');
  99365. //not possible, but yet:
  99366. if (!template)
  99367. return Promise.reject('Main template not found');
  99368. return template.hide(visibilityFunction);
  99369. };
  99370. /**
  99371. * Show the loading screen.
  99372. * The loading screen can be configured using the configuration object
  99373. */
  99374. DefaultViewer.prototype.showLoadingScreen = function () {
  99375. var _this = this;
  99376. var template = this.templateManager.getTemplate('loadingScreen');
  99377. if (!template)
  99378. return Promise.resolve('Loading Screen template not found');
  99379. return template.show((function (template) {
  99380. var canvasRect = _this.containerElement.getBoundingClientRect();
  99381. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  99382. template.parent.style.display = 'flex';
  99383. template.parent.style.width = canvasRect.width + "px";
  99384. template.parent.style.height = canvasRect.height + "px";
  99385. template.parent.style.opacity = "1";
  99386. // from the configuration!!!
  99387. var color = "black";
  99388. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  99389. color = (_this.configuration.templates.loadingScreen.params &&
  99390. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  99391. }
  99392. template.parent.style.backgroundColor = color;
  99393. return Promise.resolve(template);
  99394. }));
  99395. };
  99396. /**
  99397. * Hide the loading screen
  99398. */
  99399. DefaultViewer.prototype.hideLoadingScreen = function () {
  99400. var template = this.templateManager.getTemplate('loadingScreen');
  99401. if (!template)
  99402. return Promise.resolve('Loading Screen template not found');
  99403. return template.hide((function (template) {
  99404. template.parent.style.opacity = "0";
  99405. var onTransitionEnd = function () {
  99406. template.parent.removeEventListener("transitionend", onTransitionEnd);
  99407. template.parent.style.display = 'none';
  99408. };
  99409. template.parent.addEventListener("transitionend", onTransitionEnd);
  99410. return Promise.resolve(template);
  99411. }));
  99412. };
  99413. /**
  99414. * An extension of the light configuration of the abstract viewer.
  99415. * @param lightsConfiguration the light configuration to use
  99416. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  99417. */
  99418. DefaultViewer.prototype._configureLights = function (lightsConfiguration, model) {
  99419. var _this = this;
  99420. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  99421. // labs feature - flashlight
  99422. if (this._configuration.lab && this._configuration.lab.flashlight) {
  99423. var pointerPosition = babylonjs_1.Vector3.Zero();
  99424. var lightTarget_1;
  99425. var angle = 0.5;
  99426. var exponent = Math.PI / 2;
  99427. if (typeof this._configuration.lab.flashlight === "object") {
  99428. exponent = this._configuration.lab.flashlight.exponent || exponent;
  99429. angle = this._configuration.lab.flashlight.angle || angle;
  99430. }
  99431. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  99432. if (typeof this._configuration.lab.flashlight === "object") {
  99433. flashlight.intensity = this._configuration.lab.flashlight.intensity || flashlight.intensity;
  99434. if (this._configuration.lab.flashlight.diffuse) {
  99435. flashlight.diffuse.r = this._configuration.lab.flashlight.diffuse.r;
  99436. flashlight.diffuse.g = this._configuration.lab.flashlight.diffuse.g;
  99437. flashlight.diffuse.b = this._configuration.lab.flashlight.diffuse.b;
  99438. }
  99439. if (this._configuration.lab.flashlight.specular) {
  99440. flashlight.specular.r = this._configuration.lab.flashlight.specular.r;
  99441. flashlight.specular.g = this._configuration.lab.flashlight.specular.g;
  99442. flashlight.specular.b = this._configuration.lab.flashlight.specular.b;
  99443. }
  99444. }
  99445. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  99446. this.sceneManager.scene.onPointerObservable.add(function (eventData, eventState) {
  99447. if (eventData.type === 4 && eventData.pickInfo) {
  99448. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  99449. }
  99450. else {
  99451. lightTarget_1 = undefined;
  99452. }
  99453. });
  99454. var updateFlashlightFunction = function () {
  99455. if (_this.sceneManager.camera && flashlight) {
  99456. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  99457. if (lightTarget_1) {
  99458. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  99459. }
  99460. }
  99461. };
  99462. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  99463. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  99464. }
  99465. };
  99466. return DefaultViewer;
  99467. }(viewer_1.AbstractViewer));
  99468. exports.DefaultViewer = DefaultViewer;
  99469. /***/ }),
  99470. /* 10 */
  99471. /***/ (function(module, exports, __webpack_require__) {
  99472. "use strict";
  99473. Object.defineProperty(exports, "__esModule", { value: true });
  99474. var viewerManager_1 = __webpack_require__(8);
  99475. var sceneManager_1 = __webpack_require__(26);
  99476. var templateManager_1 = __webpack_require__(33);
  99477. var loader_1 = __webpack_require__(36);
  99478. var babylonjs_1 = __webpack_require__(0);
  99479. var deepmerge = __webpack_require__(1);
  99480. var modelLoader_1 = __webpack_require__(19);
  99481. var globals_1 = __webpack_require__(7);
  99482. var telemetryManager_1 = __webpack_require__(5);
  99483. /**
  99484. * The AbstractViewr is the center of Babylon's viewer.
  99485. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  99486. */
  99487. var AbstractViewer = /** @class */ (function () {
  99488. function AbstractViewer(containerElement, initialConfiguration) {
  99489. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  99490. var _this = this;
  99491. this.containerElement = containerElement;
  99492. /**
  99493. * A flag that controls whether or not the render loop should be executed
  99494. */
  99495. this.runRenderLoop = true;
  99496. /**
  99497. * is this viewer disposed?
  99498. */
  99499. this._isDisposed = false;
  99500. /**
  99501. * The resize function that will be registered with the window object
  99502. */
  99503. this._resize = function () {
  99504. // Only resize if Canvas is in the DOM
  99505. if (!_this.isCanvasInDOM()) {
  99506. return;
  99507. }
  99508. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  99509. return;
  99510. }
  99511. if (_this._configuration.engine && _this._configuration.engine.disableResize) {
  99512. return;
  99513. }
  99514. _this.engine.resize();
  99515. };
  99516. /**
  99517. * render loop that will be executed by the engine
  99518. */
  99519. this._render = function (force) {
  99520. if (force === void 0) { force = false; }
  99521. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  99522. if (_this.runRenderLoop || force) {
  99523. _this.engine.performanceMonitor.enable();
  99524. _this.sceneManager.scene.render();
  99525. _this.onFrameRenderedObservable.notifyObservers(_this);
  99526. }
  99527. else {
  99528. _this.engine.performanceMonitor.disable();
  99529. // TODO - is this needed?
  99530. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  99531. }
  99532. }
  99533. };
  99534. // if exists, use the container id. otherwise, generate a random string.
  99535. if (containerElement.id) {
  99536. this.baseId = containerElement.id;
  99537. }
  99538. else {
  99539. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  99540. }
  99541. this.onSceneInitObservable = new babylonjs_1.Observable();
  99542. this.onEngineInitObservable = new babylonjs_1.Observable();
  99543. this.onModelLoadedObservable = new babylonjs_1.Observable();
  99544. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  99545. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  99546. this.onModelAddedObservable = new babylonjs_1.Observable();
  99547. this.onModelRemovedObservable = new babylonjs_1.Observable();
  99548. this.onInitDoneObservable = new babylonjs_1.Observable();
  99549. this.onLoaderInitObservable = new babylonjs_1.Observable();
  99550. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  99551. this._registeredOnBeforeRenderFunctions = [];
  99552. this.modelLoader = new modelLoader_1.ModelLoader(this);
  99553. // add this viewer to the viewer manager
  99554. viewerManager_1.viewerManager.addViewer(this);
  99555. // create a new template manager. TODO - singleton?
  99556. this.templateManager = new templateManager_1.TemplateManager(containerElement);
  99557. this.sceneManager = new sceneManager_1.SceneManager(this);
  99558. this._prepareContainerElement();
  99559. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  99560. // extend the configuration
  99561. this._configurationLoader = new loader_1.ConfigurationLoader();
  99562. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  99563. _this._configuration = deepmerge(_this._configuration || {}, configuration);
  99564. if (_this._configuration.observers) {
  99565. _this._configureObservers(_this._configuration.observers);
  99566. }
  99567. if (_this._configuration.loaderPlugins) {
  99568. // TODO should plugins be removed?
  99569. Object.keys(_this._configuration.loaderPlugins).forEach((function (name) {
  99570. if (_this._configuration.loaderPlugins && _this._configuration.loaderPlugins[name]) {
  99571. _this.modelLoader.addPlugin(name);
  99572. }
  99573. }));
  99574. }
  99575. // initialize the templates
  99576. var templateConfiguration = _this._configuration.templates || {};
  99577. _this.templateManager.initTemplate(templateConfiguration);
  99578. // when done, execute onTemplatesLoaded()
  99579. _this.templateManager.onAllLoaded.add(function () {
  99580. var canvas = _this.templateManager.getCanvas();
  99581. if (canvas) {
  99582. _this._canvas = canvas;
  99583. }
  99584. _this._onTemplateLoaded();
  99585. });
  99586. });
  99587. this.onModelLoadedObservable.add(function (model) {
  99588. //this.updateConfiguration(this._configuration, model);
  99589. });
  99590. this.onSceneInitObservable.add(function () {
  99591. _this.updateConfiguration();
  99592. });
  99593. this.onInitDoneObservable.add(function () {
  99594. _this._isInit = true;
  99595. //this.sceneManager.scene.executeWhenReady(() => {
  99596. _this.engine.runRenderLoop(_this._render);
  99597. //});
  99598. });
  99599. }
  99600. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  99601. /**
  99602. * The (single) canvas of this viewer
  99603. */
  99604. get: function () {
  99605. return this._canvas;
  99606. },
  99607. enumerable: true,
  99608. configurable: true
  99609. });
  99610. /**
  99611. * get the baseId of this viewer
  99612. */
  99613. AbstractViewer.prototype.getBaseId = function () {
  99614. return this.baseId;
  99615. };
  99616. /**
  99617. * Do we have a canvas to render on, and is it a part of the scene
  99618. */
  99619. AbstractViewer.prototype.isCanvasInDOM = function () {
  99620. return !!this._canvas && !!this._canvas.parentElement;
  99621. };
  99622. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  99623. /**
  99624. * Is the engine currently set to rende even when the page is in background
  99625. */
  99626. get: function () {
  99627. return this.engine.renderEvenInBackground;
  99628. },
  99629. /**
  99630. * Set the viewer's background rendering flag.
  99631. */
  99632. set: function (value) {
  99633. this.engine.renderEvenInBackground = value;
  99634. },
  99635. enumerable: true,
  99636. configurable: true
  99637. });
  99638. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  99639. /**
  99640. * Get the configuration object. This is a reference only.
  99641. * The configuration can ONLY be updated using the updateConfiguration function.
  99642. * changing this object will have no direct effect on the scene.
  99643. */
  99644. get: function () {
  99645. return this._configuration;
  99646. },
  99647. enumerable: true,
  99648. configurable: true
  99649. });
  99650. /**
  99651. * force resizing the engine.
  99652. */
  99653. AbstractViewer.prototype.forceResize = function () {
  99654. this._resize();
  99655. };
  99656. /**
  99657. * Force a single render loop execution.
  99658. */
  99659. AbstractViewer.prototype.forceRender = function () {
  99660. this._render(true);
  99661. };
  99662. /**
  99663. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  99664. * @param callback optional callback that will be triggered when screenshot is done.
  99665. * @param width Optional screenshot width (default to 512).
  99666. * @param height Optional screenshot height (default to 512).
  99667. * @returns a promise with the screenshot data
  99668. */
  99669. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  99670. var _this = this;
  99671. if (width === void 0) { width = 0; }
  99672. if (height === void 0) { height = 0; }
  99673. width = width || this.canvas.clientWidth;
  99674. height = height || this.canvas.clientHeight;
  99675. // Create the screenshot
  99676. return new Promise(function (resolve, reject) {
  99677. try {
  99678. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  99679. if (callback) {
  99680. callback(data);
  99681. }
  99682. resolve(data);
  99683. });
  99684. }
  99685. catch (e) {
  99686. reject(e);
  99687. }
  99688. });
  99689. };
  99690. /**
  99691. * Update the current viewer configuration with new values.
  99692. * Only provided information will be updated, old configuration values will be kept.
  99693. * If this.configuration was manually changed, you can trigger this function with no parameters,
  99694. * and the entire configuration will be updated.
  99695. * @param newConfiguration
  99696. */
  99697. AbstractViewer.prototype.updateConfiguration = function (newConfiguration, mode) {
  99698. var _this = this;
  99699. if (newConfiguration === void 0) { newConfiguration = this._configuration; }
  99700. // update this.configuration with the new data
  99701. this._configuration = deepmerge(this._configuration || {}, newConfiguration);
  99702. this.sceneManager.updateConfiguration(newConfiguration, this._configuration, mode);
  99703. // observers in configuration
  99704. if (newConfiguration.observers) {
  99705. this._configureObservers(newConfiguration.observers);
  99706. }
  99707. if (newConfiguration.loaderPlugins) {
  99708. // TODO should plugins be removed?
  99709. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  99710. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  99711. _this.modelLoader.addPlugin(name);
  99712. }
  99713. }));
  99714. }
  99715. };
  99716. /**
  99717. * this is used to register native functions using the configuration object.
  99718. * This will configure the observers.
  99719. * @param observersConfiguration observers configuration
  99720. */
  99721. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  99722. if (observersConfiguration.onEngineInit) {
  99723. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  99724. }
  99725. else {
  99726. if (observersConfiguration.onEngineInit === '' && this._configuration.observers && this._configuration.observers.onEngineInit) {
  99727. this.onEngineInitObservable.removeCallback(window[this._configuration.observers.onEngineInit]);
  99728. }
  99729. }
  99730. if (observersConfiguration.onSceneInit) {
  99731. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  99732. }
  99733. else {
  99734. if (observersConfiguration.onSceneInit === '' && this._configuration.observers && this._configuration.observers.onSceneInit) {
  99735. this.onSceneInitObservable.removeCallback(window[this._configuration.observers.onSceneInit]);
  99736. }
  99737. }
  99738. if (observersConfiguration.onModelLoaded) {
  99739. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  99740. }
  99741. else {
  99742. if (observersConfiguration.onModelLoaded === '' && this._configuration.observers && this._configuration.observers.onModelLoaded) {
  99743. this.onModelLoadedObservable.removeCallback(window[this._configuration.observers.onModelLoaded]);
  99744. }
  99745. }
  99746. };
  99747. /**
  99748. * Dispoe the entire viewer including the scene and the engine
  99749. */
  99750. AbstractViewer.prototype.dispose = function () {
  99751. if (this._isDisposed) {
  99752. return;
  99753. }
  99754. window.removeEventListener('resize', this._resize);
  99755. //observers
  99756. this.onEngineInitObservable.clear();
  99757. delete this.onEngineInitObservable;
  99758. this.onInitDoneObservable.clear();
  99759. delete this.onInitDoneObservable;
  99760. this.onLoaderInitObservable.clear();
  99761. delete this.onLoaderInitObservable;
  99762. this.onModelLoadedObservable.clear();
  99763. delete this.onModelLoadedObservable;
  99764. this.onModelLoadErrorObservable.clear();
  99765. delete this.onModelLoadErrorObservable;
  99766. this.onModelLoadProgressObservable.clear();
  99767. delete this.onModelLoadProgressObservable;
  99768. this.onSceneInitObservable.clear();
  99769. delete this.onSceneInitObservable;
  99770. this.onFrameRenderedObservable.clear();
  99771. delete this.onFrameRenderedObservable;
  99772. if (this.sceneManager.scene.activeCamera) {
  99773. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  99774. }
  99775. this._fpsTimeout && clearTimeout(this._fpsTimeout);
  99776. this.sceneManager.dispose();
  99777. this.modelLoader.dispose();
  99778. this.engine.dispose();
  99779. this.templateManager.dispose();
  99780. viewerManager_1.viewerManager.removeViewer(this);
  99781. this._isDisposed = true;
  99782. };
  99783. /**
  99784. * This function will execute when the HTML templates finished initializing.
  99785. * It should initialize the engine and continue execution.
  99786. *
  99787. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  99788. */
  99789. AbstractViewer.prototype._onTemplatesLoaded = function () {
  99790. return Promise.resolve(this);
  99791. };
  99792. /**
  99793. * This will force the creation of an engine and a scene.
  99794. * It will also load a model if preconfigured.
  99795. * But first - it will load the extendible onTemplateLoaded()!
  99796. */
  99797. AbstractViewer.prototype._onTemplateLoaded = function () {
  99798. var _this = this;
  99799. return this._onTemplatesLoaded().then(function () {
  99800. var autoLoad = typeof _this._configuration.model === 'string' || (_this._configuration.model && _this._configuration.model.url);
  99801. return _this._initEngine().then(function (engine) {
  99802. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  99803. }).then(function () {
  99804. _this._initTelemetryEvents();
  99805. if (autoLoad) {
  99806. return _this.loadModel(_this._configuration.model).catch(function (e) { }).then(function () { return _this.sceneManager.scene; });
  99807. }
  99808. else {
  99809. return _this.sceneManager.scene || _this.sceneManager.initScene(_this._configuration.scene);
  99810. }
  99811. }).then(function () {
  99812. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  99813. }).catch(function (e) {
  99814. babylonjs_1.Tools.Warn(e.toString());
  99815. return _this;
  99816. });
  99817. });
  99818. };
  99819. /**
  99820. * Initialize the engine. Retruns a promise in case async calls are needed.
  99821. *
  99822. * @protected
  99823. * @returns {Promise<Engine>}
  99824. * @memberof Viewer
  99825. */
  99826. AbstractViewer.prototype._initEngine = function () {
  99827. // init custom shaders
  99828. this._injectCustomShaders();
  99829. var canvasElement = this.templateManager.getCanvas();
  99830. if (!canvasElement) {
  99831. return Promise.reject('Canvas element not found!');
  99832. }
  99833. var config = this._configuration.engine || {};
  99834. // TDO enable further configuration
  99835. // check for webgl2 support, force-disable if needed.
  99836. if (globals_1.viewerGlobals.disableWebGL2Support) {
  99837. config.engineOptions = config.engineOptions || {};
  99838. config.engineOptions.disableWebGL2Support = true;
  99839. }
  99840. this.engine = new babylonjs_1.Engine(canvasElement, !!config.antialiasing, config.engineOptions);
  99841. // Disable manifest checking
  99842. babylonjs_1.Database.IDBStorageEnabled = false;
  99843. if (!config.disableResize) {
  99844. window.addEventListener('resize', this._resize);
  99845. }
  99846. if (this._configuration.engine && this._configuration.engine.adaptiveQuality) {
  99847. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  99848. this.engine.setHardwareScalingLevel(scale);
  99849. }
  99850. return Promise.resolve(this.engine);
  99851. };
  99852. /**
  99853. * Initialize a model loading. The returns object (a ViewerModel object) will be loaded in the background.
  99854. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  99855. *
  99856. * @param modelConfig model configuration to use when loading the model.
  99857. * @param clearScene should the scene be cleared before loading this model
  99858. * @returns a ViewerModel object that is not yet fully loaded.
  99859. */
  99860. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  99861. var _this = this;
  99862. if (clearScene === void 0) { clearScene = true; }
  99863. var modelUrl = (typeof modelConfig === 'string') ? modelConfig : modelConfig.url;
  99864. if (!modelUrl) {
  99865. throw new Error("no model url provided");
  99866. }
  99867. if (clearScene) {
  99868. }
  99869. var configuration;
  99870. if (typeof modelConfig === 'string') {
  99871. configuration = {
  99872. url: modelConfig
  99873. };
  99874. }
  99875. else {
  99876. configuration = modelConfig;
  99877. }
  99878. //merge the configuration for future models:
  99879. if (this._configuration.model && typeof this._configuration.model === 'object') {
  99880. deepmerge(this._configuration.model, configuration);
  99881. }
  99882. else {
  99883. this._configuration.model = configuration;
  99884. }
  99885. this._isLoading = true;
  99886. var model = this.modelLoader.load(configuration);
  99887. this.lastUsedLoader = model.loader;
  99888. model.onLoadErrorObservable.add(function (errorObject) {
  99889. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  99890. });
  99891. model.onLoadProgressObservable.add(function (progressEvent) {
  99892. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  99893. });
  99894. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  99895. model.onLoadedObservable.add(function () {
  99896. _this._isLoading = false;
  99897. });
  99898. return model;
  99899. };
  99900. /**
  99901. * load a model using the provided configuration
  99902. *
  99903. * @param modelConfig the model configuration or URL to load.
  99904. * @param clearScene Should the scene be cleared before loading the model
  99905. * @returns a Promise the fulfills when the model finished loading successfully.
  99906. */
  99907. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  99908. var _this = this;
  99909. if (clearScene === void 0) { clearScene = true; }
  99910. if (this._isLoading) {
  99911. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  99912. return Promise.reject("another model is curently being loaded.");
  99913. }
  99914. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  99915. if (!scene)
  99916. return _this.sceneManager.initScene(_this._configuration.scene, _this._configuration.optimizer);
  99917. return scene;
  99918. }).then(function () {
  99919. var model = _this.initModel(modelConfig, clearScene);
  99920. return new Promise(function (resolve, reject) {
  99921. // at this point, configuration.model is an object, not a string
  99922. model.onLoadedObservable.add(function () {
  99923. resolve(model);
  99924. });
  99925. model.onLoadErrorObservable.add(function (error) {
  99926. reject(error);
  99927. });
  99928. });
  99929. });
  99930. };
  99931. AbstractViewer.prototype._initTelemetryEvents = function () {
  99932. var _this = this;
  99933. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this, this.engine.getCaps());
  99934. telemetryManager_1.telemetryManager.broadcast("Platform Details", this, {
  99935. userAgent: navigator.userAgent,
  99936. platform: navigator.platform
  99937. });
  99938. telemetryManager_1.telemetryManager.flushWebGLErrors(this);
  99939. var trackFPS = function () {
  99940. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this, { fps: _this.engine.getFps() });
  99941. };
  99942. trackFPS();
  99943. // Track the FPS again after 60 seconds
  99944. this._fpsTimeout = window.setTimeout(trackFPS, 60 * 1000);
  99945. };
  99946. /**
  99947. * Injects all the spectre shader in the babylon shader store
  99948. */
  99949. AbstractViewer.prototype._injectCustomShaders = function () {
  99950. var customShaders = this._configuration.customShaders;
  99951. // Inject all the spectre shader in the babylon shader store.
  99952. if (!customShaders) {
  99953. return;
  99954. }
  99955. if (customShaders.shaders) {
  99956. Object.keys(customShaders.shaders).forEach(function (key) {
  99957. // typescript considers a callback "unsafe", so... '!'
  99958. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  99959. });
  99960. }
  99961. if (customShaders.includes) {
  99962. Object.keys(customShaders.includes).forEach(function (key) {
  99963. // typescript considers a callback "unsafe", so... '!'
  99964. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  99965. });
  99966. }
  99967. };
  99968. return AbstractViewer;
  99969. }());
  99970. exports.AbstractViewer = AbstractViewer;
  99971. /***/ }),
  99972. /* 11 */
  99973. /***/ (function(module, exports, __webpack_require__) {
  99974. "use strict";
  99975. Object.defineProperty(exports, "__esModule", { value: true });
  99976. /**
  99977. * WebGL Pixel Formats
  99978. */
  99979. var PixelFormat;
  99980. (function (PixelFormat) {
  99981. PixelFormat[PixelFormat["DEPTH_COMPONENT"] = 6402] = "DEPTH_COMPONENT";
  99982. PixelFormat[PixelFormat["ALPHA"] = 6406] = "ALPHA";
  99983. PixelFormat[PixelFormat["RGB"] = 6407] = "RGB";
  99984. PixelFormat[PixelFormat["RGBA"] = 6408] = "RGBA";
  99985. PixelFormat[PixelFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  99986. PixelFormat[PixelFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  99987. })(PixelFormat = exports.PixelFormat || (exports.PixelFormat = {}));
  99988. /**
  99989. * WebGL Pixel Types
  99990. */
  99991. var PixelType;
  99992. (function (PixelType) {
  99993. PixelType[PixelType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  99994. PixelType[PixelType["UNSIGNED_SHORT_4_4_4_4"] = 32819] = "UNSIGNED_SHORT_4_4_4_4";
  99995. PixelType[PixelType["UNSIGNED_SHORT_5_5_5_1"] = 32820] = "UNSIGNED_SHORT_5_5_5_1";
  99996. PixelType[PixelType["UNSIGNED_SHORT_5_6_5"] = 33635] = "UNSIGNED_SHORT_5_6_5";
  99997. })(PixelType = exports.PixelType || (exports.PixelType = {}));
  99998. /**
  99999. * WebGL Texture Magnification Filter
  100000. */
  100001. var TextureMagFilter;
  100002. (function (TextureMagFilter) {
  100003. TextureMagFilter[TextureMagFilter["NEAREST"] = 9728] = "NEAREST";
  100004. TextureMagFilter[TextureMagFilter["LINEAR"] = 9729] = "LINEAR";
  100005. })(TextureMagFilter = exports.TextureMagFilter || (exports.TextureMagFilter = {}));
  100006. /**
  100007. * WebGL Texture Minification Filter
  100008. */
  100009. var TextureMinFilter;
  100010. (function (TextureMinFilter) {
  100011. TextureMinFilter[TextureMinFilter["NEAREST"] = 9728] = "NEAREST";
  100012. TextureMinFilter[TextureMinFilter["LINEAR"] = 9729] = "LINEAR";
  100013. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  100014. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  100015. TextureMinFilter[TextureMinFilter["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  100016. TextureMinFilter[TextureMinFilter["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  100017. })(TextureMinFilter = exports.TextureMinFilter || (exports.TextureMinFilter = {}));
  100018. /**
  100019. * WebGL Texture Wrap Modes
  100020. */
  100021. var TextureWrapMode;
  100022. (function (TextureWrapMode) {
  100023. TextureWrapMode[TextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  100024. TextureWrapMode[TextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  100025. TextureWrapMode[TextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  100026. })(TextureWrapMode = exports.TextureWrapMode || (exports.TextureWrapMode = {}));
  100027. /**
  100028. * A minimal WebGL cubemap descriptor
  100029. */
  100030. var TextureCube = /** @class */ (function () {
  100031. /**
  100032. * constructor
  100033. * @param internalFormat WebGL pixel format for the texture on the GPU
  100034. * @param type WebGL pixel type of the supplied data and texture on the GPU
  100035. * @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
  100036. */
  100037. function TextureCube(internalFormat, type, source) {
  100038. if (source === void 0) { source = []; }
  100039. this.internalFormat = internalFormat;
  100040. this.type = type;
  100041. this.source = source;
  100042. }
  100043. Object.defineProperty(TextureCube.prototype, "Width", {
  100044. /**
  100045. * Returns the width of a face of the texture or 0 if not available
  100046. */
  100047. get: function () {
  100048. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  100049. },
  100050. enumerable: true,
  100051. configurable: true
  100052. });
  100053. Object.defineProperty(TextureCube.prototype, "Height", {
  100054. /**
  100055. * Returns the height of a face of the texture or 0 if not available
  100056. */
  100057. get: function () {
  100058. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  100059. },
  100060. enumerable: true,
  100061. configurable: true
  100062. });
  100063. return TextureCube;
  100064. }());
  100065. exports.TextureCube = TextureCube;
  100066. /**
  100067. * A static class providing methods to aid working with Bablyon textures.
  100068. */
  100069. var TextureUtils = /** @class */ (function () {
  100070. function TextureUtils() {
  100071. }
  100072. /**
  100073. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  100074. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  100075. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  100076. * @param scene A Babylon Scene instance
  100077. * @param textureCube A Spectre TextureCube object
  100078. * @param parameters WebGL texture sampling parameters
  100079. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  100080. * @param environment Specifies that the texture will be used as an environment
  100081. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  100082. * @return Babylon cube texture
  100083. */
  100084. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  100085. if (environment === void 0) { environment = false; }
  100086. if (singleLod === void 0) { singleLod = false; }
  100087. if (!textureCube)
  100088. throw new Error("no texture cube provided");
  100089. var parameters;
  100090. if (environment) {
  100091. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  100092. }
  100093. else {
  100094. parameters = {
  100095. magFilter: 9728 /* NEAREST */,
  100096. minFilter: 9728 /* NEAREST */,
  100097. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100098. wrapT: 33071 /* CLAMP_TO_EDGE */
  100099. };
  100100. }
  100101. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  100102. var babylonTexture = textureCube[key];
  100103. if (!babylonTexture) {
  100104. //initialize babylon texture
  100105. babylonTexture = new BABYLON.CubeTexture('', scene);
  100106. if (environment) {
  100107. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  100108. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  100109. }
  100110. babylonTexture.gammaSpace = false;
  100111. var internalTexture_1 = new BABYLON.InternalTexture(scene.getEngine(), BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  100112. var glTexture_1 = internalTexture_1._webGLTexture;
  100113. //babylon properties
  100114. internalTexture_1.isCube = true;
  100115. internalTexture_1.generateMipMaps = false;
  100116. babylonTexture._texture = internalTexture_1;
  100117. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  100118. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  100119. var texturesUploaded_1 = 0;
  100120. var textureComplete = function () {
  100121. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  100122. };
  100123. var uploadFace = function (i, level, face) {
  100124. if (!glTexture_1)
  100125. return;
  100126. if (i === 0 && level === 0) {
  100127. internalTexture_1.width = face.width;
  100128. internalTexture_1.height = face.height;
  100129. }
  100130. var gl = (scene.getEngine())._gl;
  100131. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  100132. gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL, 0);
  100133. if (face instanceof HTMLElement || face instanceof ImageData) {
  100134. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  100135. }
  100136. else {
  100137. var textureData = face;
  100138. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  100139. }
  100140. texturesUploaded_1++;
  100141. if (textureComplete()) {
  100142. //generate mipmaps
  100143. if (automaticMipmaps) {
  100144. var w = face.width;
  100145. var h = face.height;
  100146. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  100147. if (isPot) {
  100148. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  100149. }
  100150. }
  100151. // Upload Separate lods in case there is no support for texture lod.
  100152. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  100153. var mipSlices = 3;
  100154. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  100155. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  100156. var lod = textureCube[lodKey];
  100157. //initialize lod texture if it doesn't already exist
  100158. if (lod == null && textureCube.Width) {
  100159. //compute LOD from even spacing in smoothness (matching shader calculation)
  100160. var smoothness = i_1 / (mipSlices - 1);
  100161. var roughness = 1 - smoothness;
  100162. var kMinimumVariance = 0.0005;
  100163. var alphaG = roughness * roughness + kMinimumVariance;
  100164. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  100165. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (BABYLON.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  100166. var maxLODIndex = textureCube.source.length - 1;
  100167. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  100168. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  100169. if (i_1 === 0) {
  100170. internalTexture_1._lodTextureLow = lod;
  100171. }
  100172. else if (i_1 === 1) {
  100173. internalTexture_1._lodTextureMid = lod;
  100174. }
  100175. else {
  100176. internalTexture_1._lodTextureHigh = lod;
  100177. }
  100178. textureCube[lodKey] = lod;
  100179. }
  100180. }
  100181. }
  100182. internalTexture_1.isReady = true;
  100183. }
  100184. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  100185. scene.getEngine().resetTextureCache();
  100186. };
  100187. var _loop_1 = function (i) {
  100188. var faces = textureCube.source[i];
  100189. var _loop_2 = function (j) {
  100190. var face = faces[j];
  100191. if (face instanceof HTMLImageElement && !face.complete) {
  100192. face.addEventListener('load', function () {
  100193. uploadFace(j, i, face);
  100194. }, false);
  100195. }
  100196. else {
  100197. uploadFace(j, i, face);
  100198. }
  100199. };
  100200. for (var j = 0; j < faces.length; j++) {
  100201. _loop_2(j);
  100202. }
  100203. };
  100204. for (var i = 0; i <= maxMipLevel_1; i++) {
  100205. _loop_1(i);
  100206. }
  100207. scene.getEngine().resetTextureCache();
  100208. babylonTexture.isReady = function () {
  100209. return textureComplete();
  100210. };
  100211. textureCube[key] = babylonTexture;
  100212. }
  100213. return babylonTexture;
  100214. };
  100215. /**
  100216. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  100217. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  100218. * @param parameters Spectre SamplingParameters to apply
  100219. */
  100220. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  100221. var scene = babylonTexture.getScene();
  100222. if (!scene)
  100223. return;
  100224. var gl = (scene.getEngine())._gl;
  100225. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  100226. var internalTexture = babylonTexture._texture;
  100227. if (!internalTexture)
  100228. return;
  100229. var glTexture = internalTexture._webGLTexture;
  100230. gl.bindTexture(target, glTexture);
  100231. if (parameters.magFilter != null)
  100232. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  100233. if (parameters.minFilter != null)
  100234. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  100235. if (parameters.wrapS != null)
  100236. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  100237. if (parameters.wrapT != null)
  100238. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  100239. //set babylon wrap modes from sampling parameter
  100240. switch (parameters.wrapS) {
  100241. case 10497 /* REPEAT */:
  100242. babylonTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  100243. break;
  100244. case 33071 /* CLAMP_TO_EDGE */:
  100245. babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100246. break;
  100247. case 33648 /* MIRRORED_REPEAT */:
  100248. babylonTexture.wrapU = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100249. break;
  100250. default: babylonTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100251. }
  100252. switch (parameters.wrapT) {
  100253. case 10497 /* REPEAT */:
  100254. babylonTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  100255. break;
  100256. case 33071 /* CLAMP_TO_EDGE */:
  100257. babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100258. break;
  100259. case 33648 /* MIRRORED_REPEAT */:
  100260. babylonTexture.wrapV = BABYLON.Texture.MIRROR_ADDRESSMODE;
  100261. break;
  100262. default: babylonTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  100263. }
  100264. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  100265. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  100266. if (anisotropicExt) {
  100267. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  100268. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  100269. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  100270. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  100271. }
  100272. }
  100273. gl.bindTexture(target, null);
  100274. scene.getEngine().resetTextureCache();
  100275. };
  100276. /**
  100277. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  100278. */
  100279. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  100280. /**
  100281. * Controls anisotropic filtering for deserialized textures.
  100282. */
  100283. TextureUtils.MaxAnisotropy = 4;
  100284. TextureUtils._EnvironmentSampling = {
  100285. magFilter: 9729 /* LINEAR */,
  100286. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  100287. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100288. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100289. maxAnisotropy: 1
  100290. };
  100291. TextureUtils._EnvironmentSingleMipSampling = {
  100292. magFilter: 9729 /* LINEAR */,
  100293. minFilter: 9729 /* LINEAR */,
  100294. wrapS: 33071 /* CLAMP_TO_EDGE */,
  100295. wrapT: 33071 /* CLAMP_TO_EDGE */,
  100296. maxAnisotropy: 1
  100297. };
  100298. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  100299. /**
  100300. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  100301. */
  100302. TextureUtils.EnvironmentLODScale = 0.8;
  100303. /**
  100304. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  100305. */
  100306. TextureUtils.EnvironmentLODOffset = 1.0;
  100307. return TextureUtils;
  100308. }());
  100309. exports.TextureUtils = TextureUtils;
  100310. /***/ }),
  100311. /* 12 */
  100312. /***/ (function(module, exports) {
  100313. 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>";
  100314. /***/ }),
  100315. /* 13 */
  100316. /***/ (function(module, exports) {
  100317. 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}}>";
  100318. /***/ }),
  100319. /* 14 */
  100320. /***/ (function(module, exports) {
  100321. 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=="
  100322. /***/ }),
  100323. /* 15 */
  100324. /***/ (function(module, exports) {
  100325. 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>";
  100326. /***/ }),
  100327. /* 16 */
  100328. /***/ (function(module, exports) {
  100329. 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>";
  100330. /***/ }),
  100331. /* 17 */
  100332. /***/ (function(module, exports) {
  100333. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  100334. /***/ }),
  100335. /* 18 */
  100336. /***/ (function(module, exports) {
  100337. module.exports = "Error loading the model";
  100338. /***/ }),
  100339. /* 19 */
  100340. /***/ (function(module, exports, __webpack_require__) {
  100341. "use strict";
  100342. Object.defineProperty(exports, "__esModule", { value: true });
  100343. var babylonjs_1 = __webpack_require__(0);
  100344. var babylonjs_loaders_1 = __webpack_require__(20);
  100345. var viewerModel_1 = __webpack_require__(4);
  100346. var _1 = __webpack_require__(49);
  100347. /**
  100348. * An instance of the class is in charge of loading the model correctly.
  100349. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  100350. *
  100351. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  100352. */
  100353. var ModelLoader = /** @class */ (function () {
  100354. /**
  100355. * Create a new Model loader
  100356. * @param _viewer the viewer using this model loader
  100357. */
  100358. function ModelLoader(_viewer) {
  100359. this._viewer = _viewer;
  100360. this._disposed = false;
  100361. this._loaders = [];
  100362. this._loadId = 0;
  100363. this._plugins = [];
  100364. }
  100365. ModelLoader.prototype.addPlugin = function (plugin) {
  100366. var actualPlugin = {};
  100367. if (typeof plugin === 'string') {
  100368. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  100369. if (loadedPlugin) {
  100370. actualPlugin = loadedPlugin;
  100371. }
  100372. }
  100373. else {
  100374. actualPlugin = plugin;
  100375. }
  100376. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  100377. this._plugins.push(actualPlugin);
  100378. }
  100379. };
  100380. /**
  100381. * Load a model using predefined configuration
  100382. * @param modelConfiguration the modelConfiguration to use to load the model
  100383. */
  100384. ModelLoader.prototype.load = function (modelConfiguration) {
  100385. var _this = this;
  100386. var model = new viewerModel_1.ViewerModel(this._viewer, modelConfiguration);
  100387. model.loadId = this._loadId++;
  100388. if (!modelConfiguration.url) {
  100389. model.state = viewerModel_1.ModelState.ERROR;
  100390. babylonjs_1.Tools.Error("No URL provided");
  100391. return model;
  100392. }
  100393. var base;
  100394. var filename;
  100395. if (modelConfiguration.file) {
  100396. base = "file:";
  100397. filename = modelConfiguration.file;
  100398. }
  100399. else {
  100400. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  100401. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  100402. }
  100403. var plugin = modelConfiguration.loader;
  100404. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, this._viewer.sceneManager.scene, function (meshes, particleSystems, skeletons, animationGroups) {
  100405. meshes.forEach(function (mesh) {
  100406. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  100407. model.addMesh(mesh);
  100408. });
  100409. model.particleSystems = particleSystems;
  100410. model.skeletons = skeletons;
  100411. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  100412. var animationGroup = animationGroups_1[_i];
  100413. model.addAnimationGroup(animationGroup);
  100414. }
  100415. _this._checkAndRun("onLoaded", model);
  100416. _this._viewer.sceneManager.scene.executeWhenReady(function () {
  100417. model.onLoadedObservable.notifyObservers(model);
  100418. });
  100419. }, function (progressEvent) {
  100420. _this._checkAndRun("onProgress", progressEvent);
  100421. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  100422. }, function (scene, m, exception) {
  100423. model.state = viewerModel_1.ModelState.ERROR;
  100424. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  100425. _this._checkAndRun("onError", m, exception);
  100426. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  100427. }, plugin);
  100428. if (model.loader.name === "gltf") {
  100429. var gltfLoader_1 = model.loader;
  100430. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  100431. gltfLoader_1.compileMaterials = true;
  100432. if (!modelConfiguration.file) {
  100433. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  100434. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  100435. };
  100436. }
  100437. // if ground is set to "mirror":
  100438. if (this._viewer.configuration.ground && typeof this._viewer.configuration.ground === 'object' && this._viewer.configuration.ground.mirror) {
  100439. gltfLoader_1.useClipPlane = true;
  100440. }
  100441. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  100442. gltfLoader_1[functionName].add(function (payload) {
  100443. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  100444. });
  100445. });
  100446. gltfLoader_1.onParsedObservable.add(function (data) {
  100447. if (data && data.json && data.json['asset']) {
  100448. model.loadInfo = data.json['asset'];
  100449. }
  100450. });
  100451. gltfLoader_1.onCompleteObservable.add(function () {
  100452. model.loaderDone = true;
  100453. });
  100454. }
  100455. else {
  100456. model.loaderDone = true;
  100457. }
  100458. this._checkAndRun("onInit", model.loader, model);
  100459. this._loaders.push(model.loader);
  100460. return model;
  100461. };
  100462. ModelLoader.prototype.cancelLoad = function (model) {
  100463. var loader = model.loader || this._loaders[model.loadId];
  100464. // ATM only available in the GLTF Loader
  100465. if (loader && loader.name === "gltf") {
  100466. var gltfLoader = loader;
  100467. gltfLoader.dispose();
  100468. model.state = viewerModel_1.ModelState.CANCELED;
  100469. }
  100470. else {
  100471. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  100472. }
  100473. };
  100474. /**
  100475. * dispose the model loader.
  100476. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  100477. */
  100478. ModelLoader.prototype.dispose = function () {
  100479. this._loaders.forEach(function (loader) {
  100480. if (loader.name === "gltf") {
  100481. loader.dispose();
  100482. }
  100483. });
  100484. this._loaders.length = 0;
  100485. this._disposed = true;
  100486. };
  100487. ModelLoader.prototype._checkAndRun = function (functionName) {
  100488. var _this = this;
  100489. var payload = [];
  100490. for (var _i = 1; _i < arguments.length; _i++) {
  100491. payload[_i - 1] = arguments[_i];
  100492. }
  100493. if (this._disposed)
  100494. return;
  100495. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  100496. try {
  100497. plugin[functionName].apply(_this, payload);
  100498. }
  100499. catch (e) { }
  100500. });
  100501. };
  100502. return ModelLoader;
  100503. }());
  100504. exports.ModelLoader = ModelLoader;
  100505. /***/ }),
  100506. /* 20 */
  100507. /***/ (function(module, exports, __webpack_require__) {
  100508. (function universalModuleDefinition(root, factory) {
  100509. var amdDependencies = [];
  100510. var BABYLON = root.BABYLON || this.BABYLON;
  100511. if(true) {
  100512. BABYLON = BABYLON || __webpack_require__(0);
  100513. module.exports = factory(BABYLON);
  100514. } else if(typeof define === 'function' && define.amd) {
  100515. amdDependencies.push("babylonjs");
  100516. define("babylonjs-loaders", amdDependencies, factory);
  100517. } else if(typeof exports === 'object') {
  100518. BABYLON = BABYLON || require("babylonjs");
  100519. exports["babylonjs-loaders"] = factory(BABYLON);
  100520. } else {
  100521. root["BABYLON"] = factory(BABYLON);
  100522. }
  100523. })(this, function(BABYLON) {
  100524. BABYLON = BABYLON || this.BABYLON;
  100525. 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};
  100526. 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)}}();
  100527. var BABYLON;
  100528. (function (BABYLON) {
  100529. var STLFileLoader = /** @class */ (function () {
  100530. function STLFileLoader() {
  100531. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  100532. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  100533. 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;
  100534. 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;
  100535. this.name = "stl";
  100536. // force data to come in as an ArrayBuffer
  100537. // we'll convert to string if it looks like it's an ASCII .stl
  100538. this.extensions = {
  100539. ".stl": { isBinary: true },
  100540. };
  100541. }
  100542. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100543. var matches;
  100544. if (this.isBinary(data)) {
  100545. // binary .stl
  100546. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  100547. this.parseBinary(babylonMesh, data);
  100548. if (meshes) {
  100549. meshes.push(babylonMesh);
  100550. }
  100551. return true;
  100552. }
  100553. // ASCII .stl
  100554. // convert to string
  100555. var array_buffer = new Uint8Array(data);
  100556. var str = '';
  100557. for (var i = 0; i < data.byteLength; i++) {
  100558. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  100559. }
  100560. data = str;
  100561. while (matches = this.solidPattern.exec(data)) {
  100562. var meshName = matches[1];
  100563. var meshNameFromEnd = matches[3];
  100564. if (meshName != meshNameFromEnd) {
  100565. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  100566. return false;
  100567. }
  100568. // check meshesNames
  100569. if (meshesNames && meshName) {
  100570. if (meshesNames instanceof Array) {
  100571. if (!meshesNames.indexOf(meshName)) {
  100572. continue;
  100573. }
  100574. }
  100575. else {
  100576. if (meshName !== meshesNames) {
  100577. continue;
  100578. }
  100579. }
  100580. }
  100581. // stl mesh name can be empty as well
  100582. meshName = meshName || "stlmesh";
  100583. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  100584. this.parseASCII(babylonMesh, matches[2]);
  100585. if (meshes) {
  100586. meshes.push(babylonMesh);
  100587. }
  100588. }
  100589. return true;
  100590. };
  100591. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  100592. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  100593. if (result) {
  100594. scene.createDefaultCameraOrLight();
  100595. }
  100596. return result;
  100597. };
  100598. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100599. var container = new BABYLON.AssetContainer(scene);
  100600. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100601. container.removeAllFromScene();
  100602. return container;
  100603. };
  100604. STLFileLoader.prototype.isBinary = function (data) {
  100605. // check if file size is correct for binary stl
  100606. var faceSize, nFaces, reader;
  100607. reader = new DataView(data);
  100608. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  100609. nFaces = reader.getUint32(80, true);
  100610. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  100611. return true;
  100612. }
  100613. // check characters higher than ASCII to confirm binary
  100614. var fileLength = reader.byteLength;
  100615. for (var index = 0; index < fileLength; index++) {
  100616. if (reader.getUint8(index) > 127) {
  100617. return true;
  100618. }
  100619. }
  100620. return false;
  100621. };
  100622. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  100623. var reader = new DataView(data);
  100624. var faces = reader.getUint32(80, true);
  100625. var dataOffset = 84;
  100626. var faceLength = 12 * 4 + 2;
  100627. var offset = 0;
  100628. var positions = new Float32Array(faces * 3 * 3);
  100629. var normals = new Float32Array(faces * 3 * 3);
  100630. var indices = new Uint32Array(faces * 3);
  100631. var indicesCount = 0;
  100632. for (var face = 0; face < faces; face++) {
  100633. var start = dataOffset + face * faceLength;
  100634. var normalX = reader.getFloat32(start, true);
  100635. var normalY = reader.getFloat32(start + 4, true);
  100636. var normalZ = reader.getFloat32(start + 8, true);
  100637. for (var i = 1; i <= 3; i++) {
  100638. var vertexstart = start + i * 12;
  100639. // ordering is intentional to match ascii import
  100640. positions[offset] = reader.getFloat32(vertexstart, true);
  100641. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  100642. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  100643. normals[offset] = normalX;
  100644. normals[offset + 2] = normalY;
  100645. normals[offset + 1] = normalZ;
  100646. offset += 3;
  100647. }
  100648. indices[indicesCount] = indicesCount++;
  100649. indices[indicesCount] = indicesCount++;
  100650. indices[indicesCount] = indicesCount++;
  100651. }
  100652. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100653. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100654. mesh.setIndices(indices);
  100655. mesh.computeWorldMatrix(true);
  100656. };
  100657. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  100658. var positions = [];
  100659. var normals = [];
  100660. var indices = [];
  100661. var indicesCount = 0;
  100662. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  100663. var matches;
  100664. while (matches = this.facetsPattern.exec(solidData)) {
  100665. var facet = matches[1];
  100666. //one normal per face
  100667. var normalMatches = this.normalPattern.exec(facet);
  100668. this.normalPattern.lastIndex = 0;
  100669. if (!normalMatches) {
  100670. continue;
  100671. }
  100672. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  100673. var vertexMatch;
  100674. while (vertexMatch = this.vertexPattern.exec(facet)) {
  100675. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  100676. normals.push(normal[0], normal[1], normal[2]);
  100677. }
  100678. indices.push(indicesCount++, indicesCount++, indicesCount++);
  100679. this.vertexPattern.lastIndex = 0;
  100680. }
  100681. this.facetsPattern.lastIndex = 0;
  100682. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  100683. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  100684. mesh.setIndices(indices);
  100685. mesh.computeWorldMatrix(true);
  100686. };
  100687. return STLFileLoader;
  100688. }());
  100689. BABYLON.STLFileLoader = STLFileLoader;
  100690. if (BABYLON.SceneLoader) {
  100691. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  100692. }
  100693. })(BABYLON || (BABYLON = {}));
  100694. //# sourceMappingURL=babylon.stlFileLoader.js.map
  100695. var BABYLON;
  100696. (function (BABYLON) {
  100697. /**
  100698. * Class reading and parsing the MTL file bundled with the obj file.
  100699. */
  100700. var MTLFileLoader = /** @class */ (function () {
  100701. function MTLFileLoader() {
  100702. // All material loaded from the mtl will be set here
  100703. this.materials = [];
  100704. }
  100705. /**
  100706. * This function will read the mtl file and create each material described inside
  100707. * This function could be improve by adding :
  100708. * -some component missing (Ni, Tf...)
  100709. * -including the specific options available
  100710. *
  100711. * @param scene
  100712. * @param data
  100713. * @param rootUrl
  100714. */
  100715. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  100716. if (data instanceof ArrayBuffer) {
  100717. return;
  100718. }
  100719. //Split the lines from the file
  100720. var lines = data.split('\n');
  100721. //Space char
  100722. var delimiter_pattern = /\s+/;
  100723. //Array with RGB colors
  100724. var color;
  100725. //New material
  100726. var material = null;
  100727. //Look at each line
  100728. for (var i = 0; i < lines.length; i++) {
  100729. var line = lines[i].trim();
  100730. // Blank line or comment
  100731. if (line.length === 0 || line.charAt(0) === '#') {
  100732. continue;
  100733. }
  100734. //Get the first parameter (keyword)
  100735. var pos = line.indexOf(' ');
  100736. var key = (pos >= 0) ? line.substring(0, pos) : line;
  100737. key = key.toLowerCase();
  100738. //Get the data following the key
  100739. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  100740. //This mtl keyword will create the new material
  100741. if (key === "newmtl") {
  100742. //Check if it is the first material.
  100743. // Materials specifications are described after this keyword.
  100744. if (material) {
  100745. //Add the previous material in the material array.
  100746. this.materials.push(material);
  100747. }
  100748. //Create a new material.
  100749. // value is the name of the material read in the mtl file
  100750. material = new BABYLON.StandardMaterial(value, scene);
  100751. }
  100752. else if (key === "kd" && material) {
  100753. // Diffuse color (color under white light) using RGB values
  100754. //value = "r g b"
  100755. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100756. //color = [r,g,b]
  100757. //Set tghe color into the material
  100758. material.diffuseColor = BABYLON.Color3.FromArray(color);
  100759. }
  100760. else if (key === "ka" && material) {
  100761. // Ambient color (color under shadow) using RGB values
  100762. //value = "r g b"
  100763. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100764. //color = [r,g,b]
  100765. //Set tghe color into the material
  100766. material.ambientColor = BABYLON.Color3.FromArray(color);
  100767. }
  100768. else if (key === "ks" && material) {
  100769. // Specular color (color when light is reflected from shiny surface) using RGB values
  100770. //value = "r g b"
  100771. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100772. //color = [r,g,b]
  100773. //Set the color into the material
  100774. material.specularColor = BABYLON.Color3.FromArray(color);
  100775. }
  100776. else if (key === "ke" && material) {
  100777. // Emissive color using RGB values
  100778. color = value.split(delimiter_pattern, 3).map(parseFloat);
  100779. material.emissiveColor = BABYLON.Color3.FromArray(color);
  100780. }
  100781. else if (key === "ns" && material) {
  100782. //value = "Integer"
  100783. material.specularPower = parseFloat(value);
  100784. }
  100785. else if (key === "d" && material) {
  100786. //d is dissolve for current material. It mean alpha for BABYLON
  100787. material.alpha = parseFloat(value);
  100788. //Texture
  100789. //This part can be improved by adding the possible options of texture
  100790. }
  100791. else if (key === "map_ka" && material) {
  100792. // ambient texture map with a loaded image
  100793. //We must first get the folder of the image
  100794. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100795. }
  100796. else if (key === "map_kd" && material) {
  100797. // Diffuse texture map with a loaded image
  100798. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100799. }
  100800. else if (key === "map_ks" && material) {
  100801. // Specular texture map with a loaded image
  100802. //We must first get the folder of the image
  100803. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100804. }
  100805. else if (key === "map_ns") {
  100806. //Specular
  100807. //Specular highlight component
  100808. //We must first get the folder of the image
  100809. //
  100810. //Not supported by BABYLON
  100811. //
  100812. // continue;
  100813. }
  100814. else if (key === "map_bump" && material) {
  100815. //The bump texture
  100816. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100817. }
  100818. else if (key === "map_d" && material) {
  100819. // The dissolve of the material
  100820. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  100821. //Options for illumination
  100822. }
  100823. else if (key === "illum") {
  100824. //Illumination
  100825. if (value === "0") {
  100826. //That mean Kd == Kd
  100827. }
  100828. else if (value === "1") {
  100829. //Color on and Ambient on
  100830. }
  100831. else if (value === "2") {
  100832. //Highlight on
  100833. }
  100834. else if (value === "3") {
  100835. //Reflection on and Ray trace on
  100836. }
  100837. else if (value === "4") {
  100838. //Transparency: Glass on, Reflection: Ray trace on
  100839. }
  100840. else if (value === "5") {
  100841. //Reflection: Fresnel on and Ray trace on
  100842. }
  100843. else if (value === "6") {
  100844. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  100845. }
  100846. else if (value === "7") {
  100847. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  100848. }
  100849. else if (value === "8") {
  100850. //Reflection on and Ray trace off
  100851. }
  100852. else if (value === "9") {
  100853. //Transparency: Glass on, Reflection: Ray trace off
  100854. }
  100855. else if (value === "10") {
  100856. //Casts shadows onto invisible surfaces
  100857. }
  100858. }
  100859. else {
  100860. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  100861. }
  100862. }
  100863. //At the end of the file, add the last material
  100864. if (material) {
  100865. this.materials.push(material);
  100866. }
  100867. };
  100868. /**
  100869. * Gets the texture for the material.
  100870. *
  100871. * If the material is imported from input file,
  100872. * We sanitize the url to ensure it takes the textre from aside the material.
  100873. *
  100874. * @param rootUrl The root url to load from
  100875. * @param value The value stored in the mtl
  100876. * @return The Texture
  100877. */
  100878. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  100879. if (!value) {
  100880. return null;
  100881. }
  100882. var url = rootUrl;
  100883. // Load from input file.
  100884. if (rootUrl === "file:") {
  100885. var lastDelimiter = value.lastIndexOf("\\");
  100886. if (lastDelimiter === -1) {
  100887. lastDelimiter = value.lastIndexOf("/");
  100888. }
  100889. if (lastDelimiter > -1) {
  100890. url += value.substr(lastDelimiter + 1);
  100891. }
  100892. else {
  100893. url += value;
  100894. }
  100895. }
  100896. // Not from input file.
  100897. else {
  100898. url += value;
  100899. }
  100900. return new BABYLON.Texture(url, scene);
  100901. };
  100902. return MTLFileLoader;
  100903. }());
  100904. BABYLON.MTLFileLoader = MTLFileLoader;
  100905. var OBJFileLoader = /** @class */ (function () {
  100906. function OBJFileLoader() {
  100907. this.name = "obj";
  100908. this.extensions = ".obj";
  100909. this.obj = /^o/;
  100910. this.group = /^g/;
  100911. this.mtllib = /^mtllib /;
  100912. this.usemtl = /^usemtl /;
  100913. this.smooth = /^s /;
  100914. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100915. // vn float float float
  100916. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100917. // vt float float
  100918. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  100919. // f vertex vertex vertex ...
  100920. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  100921. // f vertex/uvs vertex/uvs vertex/uvs ...
  100922. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100923. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  100924. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  100925. // f vertex//normal vertex//normal vertex//normal ...
  100926. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  100927. }
  100928. /**
  100929. * Calls synchronously the MTL file attached to this obj.
  100930. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  100931. * Without this function materials are not displayed in the first frame (but displayed after).
  100932. * In consequence it is impossible to get material information in your HTML file
  100933. *
  100934. * @param url The URL of the MTL file
  100935. * @param rootUrl
  100936. * @param onSuccess Callback function to be called when the MTL file is loaded
  100937. * @private
  100938. */
  100939. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  100940. //The complete path to the mtl file
  100941. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  100942. // Loads through the babylon tools to allow fileInput search.
  100943. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  100944. };
  100945. OBJFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  100946. //get the meshes from OBJ file
  100947. var loadedMeshes = this._parseSolid(meshesNames, scene, data, rootUrl);
  100948. //Push meshes from OBJ file into the variable mesh of this function
  100949. if (meshes) {
  100950. loadedMeshes.forEach(function (mesh) {
  100951. meshes.push(mesh);
  100952. });
  100953. }
  100954. return true;
  100955. };
  100956. OBJFileLoader.prototype.load = function (scene, data, rootUrl) {
  100957. //Get the 3D model
  100958. return this.importMesh(null, scene, data, rootUrl, null, null, null);
  100959. };
  100960. OBJFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  100961. var container = new BABYLON.AssetContainer(scene);
  100962. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  100963. container.removeAllFromScene();
  100964. return container;
  100965. };
  100966. /**
  100967. * Read the OBJ file and create an Array of meshes.
  100968. * Each mesh contains all information given by the OBJ and the MTL file.
  100969. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  100970. *
  100971. * @param meshesNames
  100972. * @param scene BABYLON.Scene The scene where are displayed the data
  100973. * @param data String The content of the obj file
  100974. * @param rootUrl String The path to the folder
  100975. * @returns Array<AbstractMesh>
  100976. * @private
  100977. */
  100978. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  100979. var positions = []; //values for the positions of vertices
  100980. var normals = []; //Values for the normals
  100981. var uvs = []; //Values for the textures
  100982. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  100983. var handledMesh; //The current mesh of meshes array
  100984. var indicesForBabylon = []; //The list of indices for VertexData
  100985. var wrappedPositionForBabylon = []; //The list of position in vectors
  100986. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  100987. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  100988. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  100989. var curPositionInIndices = 0;
  100990. var hasMeshes = false; //Meshes are defined in the file
  100991. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  100992. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  100993. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  100994. var triangles = []; //Indices from new triangles coming from polygons
  100995. var materialNameFromObj = ""; //The name of the current material
  100996. var fileToLoad = ""; //The name of the mtlFile to load
  100997. var materialsFromMTLFile = new MTLFileLoader();
  100998. var objMeshName = ""; //The name of the current obj mesh
  100999. var increment = 1; //Id for meshes created by the multimaterial
  101000. var isFirstMaterial = true;
  101001. /**
  101002. * Search for obj in the given array.
  101003. * This function is called to check if a couple of data already exists in an array.
  101004. *
  101005. * If found, returns the index of the founded tuple index. Returns -1 if not found
  101006. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  101007. * @param obj Array<number>
  101008. * @returns {boolean}
  101009. */
  101010. var isInArray = function (arr, obj) {
  101011. if (!arr[obj[0]])
  101012. arr[obj[0]] = { normals: [], idx: [] };
  101013. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101014. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  101015. };
  101016. var isInArrayUV = function (arr, obj) {
  101017. if (!arr[obj[0]])
  101018. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  101019. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  101020. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  101021. return arr[obj[0]].idx[idx];
  101022. }
  101023. return -1;
  101024. };
  101025. /**
  101026. * This function set the data for each triangle.
  101027. * Data are position, normals and uvs
  101028. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  101029. * If the tuple already exist, add only their indice
  101030. *
  101031. * @param indicePositionFromObj Integer The index in positions array
  101032. * @param indiceUvsFromObj Integer The index in uvs array
  101033. * @param indiceNormalFromObj Integer The index in normals array
  101034. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  101035. * @param textureVectorFromOBJ Vector3 The value of uvs
  101036. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  101037. */
  101038. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  101039. //Check if this tuple already exists in the list of tuples
  101040. var _index;
  101041. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  101042. _index = isInArrayUV(tuplePosNorm, [
  101043. indicePositionFromObj,
  101044. indiceNormalFromObj,
  101045. indiceUvsFromObj
  101046. ]);
  101047. }
  101048. else {
  101049. _index = isInArray(tuplePosNorm, [
  101050. indicePositionFromObj,
  101051. indiceNormalFromObj
  101052. ]);
  101053. }
  101054. //If it not exists
  101055. if (_index == -1) {
  101056. //Add an new indice.
  101057. //The array of indices is only an array with his length equal to the number of triangles - 1.
  101058. //We add vertices data in this order
  101059. indicesForBabylon.push(wrappedPositionForBabylon.length);
  101060. //Push the position of vertice for Babylon
  101061. //Each element is a BABYLON.Vector3(x,y,z)
  101062. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  101063. //Push the uvs for Babylon
  101064. //Each element is a BABYLON.Vector3(u,v)
  101065. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  101066. //Push the normals for Babylon
  101067. //Each element is a BABYLON.Vector3(x,y,z)
  101068. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  101069. //Add the tuple in the comparison list
  101070. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  101071. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  101072. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  101073. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  101074. }
  101075. else {
  101076. //The tuple already exists
  101077. //Add the index of the already existing tuple
  101078. //At this index we can get the value of position, normal and uvs of vertex
  101079. indicesForBabylon.push(_index);
  101080. }
  101081. };
  101082. /**
  101083. * Transform BABYLON.Vector() object onto 3 digits in an array
  101084. */
  101085. var unwrapData = function () {
  101086. //Every array has the same length
  101087. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  101088. //Push the x, y, z values of each element in the unwrapped array
  101089. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  101090. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  101091. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  101092. }
  101093. // Reset arrays for the next new meshes
  101094. wrappedPositionForBabylon = [];
  101095. wrappedNormalsForBabylon = [];
  101096. wrappedUvsForBabylon = [];
  101097. tuplePosNorm = [];
  101098. curPositionInIndices = 0;
  101099. };
  101100. /**
  101101. * Create triangles from polygons by recursion
  101102. * The best to understand how it works is to draw it in the same time you get the recursion.
  101103. * It is important to notice that a triangle is a polygon
  101104. * We get 4 patterns of face defined in OBJ File :
  101105. * facePattern1 = ["1","2","3","4","5","6"]
  101106. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  101107. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  101108. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  101109. * Each pattern is divided by the same method
  101110. * @param face Array[String] The indices of elements
  101111. * @param v Integer The variable to increment
  101112. */
  101113. var getTriangles = function (face, v) {
  101114. //Work for each element of the array
  101115. if (v + 1 < face.length) {
  101116. //Add on the triangle variable the indexes to obtain triangles
  101117. triangles.push(face[0], face[v], face[v + 1]);
  101118. //Incrementation for recursion
  101119. v += 1;
  101120. //Recursion
  101121. getTriangles(face, v);
  101122. }
  101123. //Result obtained after 2 iterations:
  101124. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  101125. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  101126. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  101127. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  101128. };
  101129. /**
  101130. * Create triangles and push the data for each polygon for the pattern 1
  101131. * In this pattern we get vertice positions
  101132. * @param face
  101133. * @param v
  101134. */
  101135. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  101136. //Get the indices of triangles for each polygon
  101137. getTriangles(face, v);
  101138. //For each element in the triangles array.
  101139. //This var could contains 1 to an infinity of triangles
  101140. for (var k = 0; k < triangles.length; k++) {
  101141. // Set position indice
  101142. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  101143. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  101144. positions[indicePositionFromObj], //Get the vectors data
  101145. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  101146. );
  101147. }
  101148. //Reset variable for the next line
  101149. triangles = [];
  101150. };
  101151. /**
  101152. * Create triangles and push the data for each polygon for the pattern 2
  101153. * In this pattern we get vertice positions and uvsu
  101154. * @param face
  101155. * @param v
  101156. */
  101157. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  101158. //Get the indices of triangles for each polygon
  101159. getTriangles(face, v);
  101160. for (var k = 0; k < triangles.length; k++) {
  101161. //triangle[k] = "1/1"
  101162. //Split the data for getting position and uv
  101163. var point = triangles[k].split("/"); // ["1", "1"]
  101164. //Set position indice
  101165. var indicePositionFromObj = parseInt(point[0]) - 1;
  101166. //Set uv indice
  101167. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101168. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  101169. positions[indicePositionFromObj], //Get the values for each element
  101170. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  101171. );
  101172. }
  101173. //Reset variable for the next line
  101174. triangles = [];
  101175. };
  101176. /**
  101177. * Create triangles and push the data for each polygon for the pattern 3
  101178. * In this pattern we get vertice positions, uvs and normals
  101179. * @param face
  101180. * @param v
  101181. */
  101182. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  101183. //Get the indices of triangles for each polygon
  101184. getTriangles(face, v);
  101185. for (var k = 0; k < triangles.length; k++) {
  101186. //triangle[k] = "1/1/1"
  101187. //Split the data for getting position, uv, and normals
  101188. var point = triangles[k].split("/"); // ["1", "1", "1"]
  101189. // Set position indice
  101190. var indicePositionFromObj = parseInt(point[0]) - 1;
  101191. // Set uv indice
  101192. var indiceUvsFromObj = parseInt(point[1]) - 1;
  101193. // Set normal indice
  101194. var indiceNormalFromObj = parseInt(point[2]) - 1;
  101195. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  101196. );
  101197. }
  101198. //Reset variable for the next line
  101199. triangles = [];
  101200. };
  101201. /**
  101202. * Create triangles and push the data for each polygon for the pattern 4
  101203. * In this pattern we get vertice positions and normals
  101204. * @param face
  101205. * @param v
  101206. */
  101207. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  101208. getTriangles(face, v);
  101209. for (var k = 0; k < triangles.length; k++) {
  101210. //triangle[k] = "1//1"
  101211. //Split the data for getting position and normals
  101212. var point = triangles[k].split("//"); // ["1", "1"]
  101213. // We check indices, and normals
  101214. var indicePositionFromObj = parseInt(point[0]) - 1;
  101215. var indiceNormalFromObj = parseInt(point[1]) - 1;
  101216. setData(indicePositionFromObj, 1, //Default value for uv
  101217. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  101218. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  101219. }
  101220. //Reset variable for the next line
  101221. triangles = [];
  101222. };
  101223. var addPreviousObjMesh = function () {
  101224. //Check if it is not the first mesh. Otherwise we don't have data.
  101225. if (meshesFromObj.length > 0) {
  101226. //Get the previous mesh for applying the data about the faces
  101227. //=> in obj file, faces definition append after the name of the mesh
  101228. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101229. //Set the data into Array for the mesh
  101230. unwrapData();
  101231. // Reverse tab. Otherwise face are displayed in the wrong sens
  101232. indicesForBabylon.reverse();
  101233. //Set the information for the mesh
  101234. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  101235. handledMesh.indices = indicesForBabylon.slice();
  101236. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  101237. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  101238. handledMesh.uvs = unwrappedUVForBabylon.slice();
  101239. //Reset the array for the next mesh
  101240. indicesForBabylon = [];
  101241. unwrappedPositionsForBabylon = [];
  101242. unwrappedNormalsForBabylon = [];
  101243. unwrappedUVForBabylon = [];
  101244. }
  101245. };
  101246. //Main function
  101247. //Split the file into lines
  101248. var lines = data.split('\n');
  101249. //Look at each line
  101250. for (var i = 0; i < lines.length; i++) {
  101251. var line = lines[i].trim();
  101252. var result;
  101253. //Comment or newLine
  101254. if (line.length === 0 || line.charAt(0) === '#') {
  101255. continue;
  101256. //Get information about one position possible for the vertices
  101257. }
  101258. else if ((result = this.vertexPattern.exec(line)) !== null) {
  101259. //Create a Vector3 with the position x, y, z
  101260. //Value of result:
  101261. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101262. //Add the Vector in the list of positions
  101263. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101264. }
  101265. else if ((result = this.normalPattern.exec(line)) !== null) {
  101266. //Create a Vector3 with the normals x, y, z
  101267. //Value of result
  101268. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  101269. //Add the Vector in the list of normals
  101270. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  101271. }
  101272. else if ((result = this.uvPattern.exec(line)) !== null) {
  101273. //Create a Vector2 with the normals u, v
  101274. //Value of result
  101275. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  101276. //Add the Vector in the list of uvs
  101277. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  101278. //Identify patterns of faces
  101279. //Face could be defined in different type of pattern
  101280. }
  101281. else if ((result = this.facePattern3.exec(line)) !== null) {
  101282. //Value of result:
  101283. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  101284. //Set the data for this face
  101285. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  101286. 1);
  101287. }
  101288. else if ((result = this.facePattern4.exec(line)) !== null) {
  101289. //Value of result:
  101290. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  101291. //Set the data for this face
  101292. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  101293. 1);
  101294. }
  101295. else if ((result = this.facePattern2.exec(line)) !== null) {
  101296. //Value of result:
  101297. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  101298. //Set the data for this face
  101299. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  101300. 1);
  101301. }
  101302. else if ((result = this.facePattern1.exec(line)) !== null) {
  101303. //Value of result
  101304. //["f 1 2 3", "1 2 3"...]
  101305. //Set the data for this face
  101306. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  101307. 1);
  101308. //Define a mesh or an object
  101309. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  101310. }
  101311. else if (this.group.test(line) || this.obj.test(line)) {
  101312. //Create a new mesh corresponding to the name of the group.
  101313. //Definition of the mesh
  101314. var objMesh =
  101315. //Set the name of the current obj mesh
  101316. {
  101317. name: line.substring(2).trim(),
  101318. indices: undefined,
  101319. positions: undefined,
  101320. normals: undefined,
  101321. uvs: undefined,
  101322. materialName: ""
  101323. };
  101324. addPreviousObjMesh();
  101325. //Push the last mesh created with only the name
  101326. meshesFromObj.push(objMesh);
  101327. //Set this variable to indicate that now meshesFromObj has objects defined inside
  101328. hasMeshes = true;
  101329. isFirstMaterial = true;
  101330. increment = 1;
  101331. //Keyword for applying a material
  101332. }
  101333. else if (this.usemtl.test(line)) {
  101334. //Get the name of the material
  101335. materialNameFromObj = line.substring(7).trim();
  101336. //If this new material is in the same mesh
  101337. if (!isFirstMaterial) {
  101338. //Set the data for the previous mesh
  101339. addPreviousObjMesh();
  101340. //Create a new mesh
  101341. var objMesh =
  101342. //Set the name of the current obj mesh
  101343. {
  101344. name: objMeshName + "_mm" + increment.toString(),
  101345. indices: undefined,
  101346. positions: undefined,
  101347. normals: undefined,
  101348. uvs: undefined,
  101349. materialName: materialNameFromObj
  101350. };
  101351. increment++;
  101352. //If meshes are already defined
  101353. meshesFromObj.push(objMesh);
  101354. }
  101355. //Set the material name if the previous line define a mesh
  101356. if (hasMeshes && isFirstMaterial) {
  101357. //Set the material name to the previous mesh (1 material per mesh)
  101358. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  101359. isFirstMaterial = false;
  101360. }
  101361. //Keyword for loading the mtl file
  101362. }
  101363. else if (this.mtllib.test(line)) {
  101364. //Get the name of mtl file
  101365. fileToLoad = line.substring(7).trim();
  101366. //Apply smoothing
  101367. }
  101368. else if (this.smooth.test(line)) {
  101369. // smooth shading => apply smoothing
  101370. //Toda y I don't know it work with babylon and with obj.
  101371. //With the obj file an integer is set
  101372. }
  101373. else {
  101374. //If there is another possibility
  101375. console.log("Unhandled expression at line : " + line);
  101376. }
  101377. }
  101378. //At the end of the file, add the last mesh into the meshesFromObj array
  101379. if (hasMeshes) {
  101380. //Set the data for the last mesh
  101381. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  101382. //Reverse indices for displaying faces in the good sens
  101383. indicesForBabylon.reverse();
  101384. //Get the good array
  101385. unwrapData();
  101386. //Set array
  101387. handledMesh.indices = indicesForBabylon;
  101388. handledMesh.positions = unwrappedPositionsForBabylon;
  101389. handledMesh.normals = unwrappedNormalsForBabylon;
  101390. handledMesh.uvs = unwrappedUVForBabylon;
  101391. }
  101392. //If any o or g keyword found, create a mesj with a random id
  101393. if (!hasMeshes) {
  101394. // reverse tab of indices
  101395. indicesForBabylon.reverse();
  101396. //Get positions normals uvs
  101397. unwrapData();
  101398. //Set data for one mesh
  101399. meshesFromObj.push({
  101400. name: BABYLON.Geometry.RandomId(),
  101401. indices: indicesForBabylon,
  101402. positions: unwrappedPositionsForBabylon,
  101403. normals: unwrappedNormalsForBabylon,
  101404. uvs: unwrappedUVForBabylon,
  101405. materialName: materialNameFromObj
  101406. });
  101407. }
  101408. //Create a BABYLON.Mesh list
  101409. var babylonMeshesArray = []; //The mesh for babylon
  101410. var materialToUse = new Array();
  101411. //Set data for each mesh
  101412. for (var j = 0; j < meshesFromObj.length; j++) {
  101413. //check meshesNames (stlFileLoader)
  101414. if (meshesNames && meshesFromObj[j].name) {
  101415. if (meshesNames instanceof Array) {
  101416. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  101417. continue;
  101418. }
  101419. }
  101420. else {
  101421. if (meshesFromObj[j].name !== meshesNames) {
  101422. continue;
  101423. }
  101424. }
  101425. }
  101426. //Get the current mesh
  101427. //Set the data with VertexBuffer for each mesh
  101428. handledMesh = meshesFromObj[j];
  101429. //Create a BABYLON.Mesh with the name of the obj mesh
  101430. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  101431. //Push the name of the material to an array
  101432. //This is indispensable for the importMesh function
  101433. materialToUse.push(meshesFromObj[j].materialName);
  101434. var vertexData = new BABYLON.VertexData(); //The container for the values
  101435. //Set the data for the babylonMesh
  101436. vertexData.positions = handledMesh.positions;
  101437. vertexData.normals = handledMesh.normals;
  101438. vertexData.uvs = handledMesh.uvs;
  101439. vertexData.indices = handledMesh.indices;
  101440. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  101441. vertexData.applyToMesh(babylonMesh);
  101442. if (OBJFileLoader.INVERT_Y) {
  101443. babylonMesh.scaling.y *= -1;
  101444. }
  101445. //Push the mesh into an array
  101446. babylonMeshesArray.push(babylonMesh);
  101447. }
  101448. //load the materials
  101449. //Check if we have a file to load
  101450. if (fileToLoad !== "") {
  101451. //Load the file synchronously
  101452. this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  101453. //Create materials thanks MTLLoader function
  101454. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  101455. //Look at each material loaded in the mtl file
  101456. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  101457. //Three variables to get all meshes with the same material
  101458. var startIndex = 0;
  101459. var _indices = [];
  101460. var _index;
  101461. //The material from MTL file is used in the meshes loaded
  101462. //Push the indice in an array
  101463. //Check if the material is not used for another mesh
  101464. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  101465. _indices.push(_index);
  101466. startIndex = _index + 1;
  101467. }
  101468. //If the material is not used dispose it
  101469. if (_index == -1 && _indices.length == 0) {
  101470. //If the material is not needed, remove it
  101471. materialsFromMTLFile.materials[n].dispose();
  101472. }
  101473. else {
  101474. for (var o = 0; o < _indices.length; o++) {
  101475. //Apply the material to the BABYLON.Mesh for each mesh with the material
  101476. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  101477. }
  101478. }
  101479. }
  101480. });
  101481. }
  101482. //Return an array with all BABYLON.Mesh
  101483. return babylonMeshesArray;
  101484. };
  101485. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  101486. OBJFileLoader.INVERT_Y = false;
  101487. return OBJFileLoader;
  101488. }());
  101489. BABYLON.OBJFileLoader = OBJFileLoader;
  101490. if (BABYLON.SceneLoader) {
  101491. //Add this loader into the register plugin
  101492. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  101493. }
  101494. })(BABYLON || (BABYLON = {}));
  101495. //# sourceMappingURL=babylon.objFileLoader.js.map
  101496. var BABYLON;
  101497. (function (BABYLON) {
  101498. /**
  101499. * Mode that determines the coordinate system to use.
  101500. */
  101501. var GLTFLoaderCoordinateSystemMode;
  101502. (function (GLTFLoaderCoordinateSystemMode) {
  101503. /**
  101504. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  101505. */
  101506. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  101507. /**
  101508. * Sets the useRightHandedSystem flag on the scene.
  101509. */
  101510. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  101511. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  101512. /**
  101513. * Mode that determines what animations will start.
  101514. */
  101515. var GLTFLoaderAnimationStartMode;
  101516. (function (GLTFLoaderAnimationStartMode) {
  101517. /**
  101518. * No animation will start.
  101519. */
  101520. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  101521. /**
  101522. * The first animation will start.
  101523. */
  101524. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  101525. /**
  101526. * All animations will start.
  101527. */
  101528. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  101529. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  101530. /**
  101531. * Loader state.
  101532. */
  101533. var GLTFLoaderState;
  101534. (function (GLTFLoaderState) {
  101535. /**
  101536. * The asset is loading.
  101537. */
  101538. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  101539. /**
  101540. * The asset is ready for rendering.
  101541. */
  101542. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  101543. /**
  101544. * The asset is completely loaded.
  101545. */
  101546. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  101547. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  101548. /**
  101549. * File loader for loading glTF files into a scene.
  101550. */
  101551. var GLTFFileLoader = /** @class */ (function () {
  101552. function GLTFFileLoader() {
  101553. // #region Common options
  101554. /**
  101555. * Raised when the asset has been parsed
  101556. */
  101557. this.onParsedObservable = new BABYLON.Observable();
  101558. // #endregion
  101559. // #region V2 options
  101560. /**
  101561. * The coordinate system mode. Defaults to AUTO.
  101562. */
  101563. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  101564. /**
  101565. * The animation start mode. Defaults to FIRST.
  101566. */
  101567. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  101568. /**
  101569. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  101570. */
  101571. this.compileMaterials = false;
  101572. /**
  101573. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  101574. */
  101575. this.useClipPlane = false;
  101576. /**
  101577. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  101578. */
  101579. this.compileShadowGenerators = false;
  101580. /**
  101581. * Defines if the Alpha blended materials are only applied as coverage.
  101582. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  101583. * If true, no extra effects are applied to transparent pixels.
  101584. */
  101585. this.transparencyAsCoverage = false;
  101586. /** @hidden */
  101587. this._normalizeAnimationGroupsToBeginAtZero = true;
  101588. /**
  101589. * Function called before loading a url referenced by the asset.
  101590. */
  101591. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101592. /**
  101593. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101594. */
  101595. this.onMeshLoadedObservable = new BABYLON.Observable();
  101596. /**
  101597. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  101598. */
  101599. this.onTextureLoadedObservable = new BABYLON.Observable();
  101600. /**
  101601. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  101602. */
  101603. this.onMaterialLoadedObservable = new BABYLON.Observable();
  101604. /**
  101605. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  101606. */
  101607. this.onCameraLoadedObservable = new BABYLON.Observable();
  101608. /**
  101609. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  101610. * For assets with LODs, raised when all of the LODs are complete.
  101611. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  101612. */
  101613. this.onCompleteObservable = new BABYLON.Observable();
  101614. /**
  101615. * Observable raised after the loader is disposed.
  101616. */
  101617. this.onDisposeObservable = new BABYLON.Observable();
  101618. /**
  101619. * Observable raised after a loader extension is created.
  101620. * Set additional options for a loader extension in this event.
  101621. */
  101622. this.onExtensionLoadedObservable = new BABYLON.Observable();
  101623. // #endregion
  101624. this._loader = null;
  101625. /**
  101626. * Name of the loader ("gltf")
  101627. */
  101628. this.name = "gltf";
  101629. /**
  101630. * Supported file extensions of the loader (.gltf, .glb)
  101631. */
  101632. this.extensions = {
  101633. ".gltf": { isBinary: false },
  101634. ".glb": { isBinary: true }
  101635. };
  101636. }
  101637. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  101638. /**
  101639. * Raised when the asset has been parsed
  101640. */
  101641. set: function (callback) {
  101642. if (this._onParsedObserver) {
  101643. this.onParsedObservable.remove(this._onParsedObserver);
  101644. }
  101645. this._onParsedObserver = this.onParsedObservable.add(callback);
  101646. },
  101647. enumerable: true,
  101648. configurable: true
  101649. });
  101650. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  101651. /**
  101652. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  101653. */
  101654. set: function (callback) {
  101655. if (this._onMeshLoadedObserver) {
  101656. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  101657. }
  101658. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  101659. },
  101660. enumerable: true,
  101661. configurable: true
  101662. });
  101663. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  101664. /**
  101665. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  101666. */
  101667. set: function (callback) {
  101668. if (this._onTextureLoadedObserver) {
  101669. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  101670. }
  101671. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  101672. },
  101673. enumerable: true,
  101674. configurable: true
  101675. });
  101676. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  101677. /**
  101678. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  101679. */
  101680. set: function (callback) {
  101681. if (this._onMaterialLoadedObserver) {
  101682. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  101683. }
  101684. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  101685. },
  101686. enumerable: true,
  101687. configurable: true
  101688. });
  101689. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  101690. /**
  101691. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  101692. */
  101693. set: function (callback) {
  101694. if (this._onCameraLoadedObserver) {
  101695. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  101696. }
  101697. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  101698. },
  101699. enumerable: true,
  101700. configurable: true
  101701. });
  101702. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  101703. /**
  101704. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  101705. */
  101706. set: function (callback) {
  101707. if (this._onCompleteObserver) {
  101708. this.onCompleteObservable.remove(this._onCompleteObserver);
  101709. }
  101710. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  101711. },
  101712. enumerable: true,
  101713. configurable: true
  101714. });
  101715. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  101716. /**
  101717. * Callback raised after the loader is disposed.
  101718. */
  101719. set: function (callback) {
  101720. if (this._onDisposeObserver) {
  101721. this.onDisposeObservable.remove(this._onDisposeObserver);
  101722. }
  101723. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  101724. },
  101725. enumerable: true,
  101726. configurable: true
  101727. });
  101728. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  101729. /**
  101730. * Callback raised after a loader extension is created.
  101731. */
  101732. set: function (callback) {
  101733. if (this._onExtensionLoadedObserver) {
  101734. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  101735. }
  101736. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  101737. },
  101738. enumerable: true,
  101739. configurable: true
  101740. });
  101741. /**
  101742. * Returns a promise that resolves when the asset is completely loaded.
  101743. * @returns a promise that resolves when the asset is completely loaded.
  101744. */
  101745. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  101746. var _this = this;
  101747. return new Promise(function (resolve) {
  101748. _this.onCompleteObservable.add(function () {
  101749. resolve();
  101750. }, undefined, undefined, undefined, true);
  101751. });
  101752. };
  101753. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  101754. /**
  101755. * The loader state or null if the loader is not active.
  101756. */
  101757. get: function () {
  101758. return this._loader ? this._loader.state : null;
  101759. },
  101760. enumerable: true,
  101761. configurable: true
  101762. });
  101763. /**
  101764. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  101765. */
  101766. GLTFFileLoader.prototype.dispose = function () {
  101767. if (this._loader) {
  101768. this._loader.dispose();
  101769. this._loader = null;
  101770. }
  101771. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  101772. this.onMeshLoadedObservable.clear();
  101773. this.onTextureLoadedObservable.clear();
  101774. this.onMaterialLoadedObservable.clear();
  101775. this.onCameraLoadedObservable.clear();
  101776. this.onCompleteObservable.clear();
  101777. this.onExtensionLoadedObservable.clear();
  101778. this.onDisposeObservable.notifyObservers(this);
  101779. this.onDisposeObservable.clear();
  101780. };
  101781. /**
  101782. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  101783. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  101784. * @param scene the scene the meshes should be added to
  101785. * @param data the glTF data to load
  101786. * @param rootUrl root url to load from
  101787. * @param onProgress event that fires when loading progress has occured
  101788. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  101789. */
  101790. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  101791. var _this = this;
  101792. return Promise.resolve().then(function () {
  101793. var loaderData = _this._parse(data);
  101794. _this._loader = _this._getLoader(loaderData);
  101795. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  101796. });
  101797. };
  101798. /**
  101799. * Imports all objects from the loaded glTF data and adds them to the scene
  101800. * @param scene the scene the objects should be added to
  101801. * @param data the glTF data to load
  101802. * @param rootUrl root url to load from
  101803. * @param onProgress event that fires when loading progress has occured
  101804. * @returns a promise which completes when objects have been loaded to the scene
  101805. */
  101806. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  101807. var _this = this;
  101808. return Promise.resolve().then(function () {
  101809. var loaderData = _this._parse(data);
  101810. _this._loader = _this._getLoader(loaderData);
  101811. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  101812. });
  101813. };
  101814. /**
  101815. * Load into an asset container.
  101816. * @param scene The scene to load into
  101817. * @param data The data to import
  101818. * @param rootUrl The root url for scene and resources
  101819. * @param onProgress The callback when the load progresses
  101820. * @returns The loaded asset container
  101821. */
  101822. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  101823. var _this = this;
  101824. return Promise.resolve().then(function () {
  101825. var loaderData = _this._parse(data);
  101826. _this._loader = _this._getLoader(loaderData);
  101827. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  101828. var container = new BABYLON.AssetContainer(scene);
  101829. Array.prototype.push.apply(container.meshes, result.meshes);
  101830. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  101831. Array.prototype.push.apply(container.skeletons, result.skeletons);
  101832. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  101833. container.removeAllFromScene();
  101834. return container;
  101835. });
  101836. });
  101837. };
  101838. /**
  101839. * If the data string can be loaded directly.
  101840. * @param data string contianing the file data
  101841. * @returns if the data can be loaded directly
  101842. */
  101843. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  101844. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  101845. };
  101846. /**
  101847. * Instantiates a glTF file loader plugin.
  101848. * @returns the created plugin
  101849. */
  101850. GLTFFileLoader.prototype.createPlugin = function () {
  101851. return new GLTFFileLoader();
  101852. };
  101853. GLTFFileLoader.prototype._parse = function (data) {
  101854. var parsedData;
  101855. if (data instanceof ArrayBuffer) {
  101856. parsedData = GLTFFileLoader._parseBinary(data);
  101857. }
  101858. else {
  101859. parsedData = {
  101860. json: JSON.parse(data),
  101861. bin: null
  101862. };
  101863. }
  101864. this.onParsedObservable.notifyObservers(parsedData);
  101865. this.onParsedObservable.clear();
  101866. return parsedData;
  101867. };
  101868. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  101869. var _this = this;
  101870. var loaderVersion = { major: 2, minor: 0 };
  101871. var asset = loaderData.json.asset || {};
  101872. var version = GLTFFileLoader._parseVersion(asset.version);
  101873. if (!version) {
  101874. throw new Error("Invalid version: " + asset.version);
  101875. }
  101876. if (asset.minVersion !== undefined) {
  101877. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  101878. if (!minVersion) {
  101879. throw new Error("Invalid minimum version: " + asset.minVersion);
  101880. }
  101881. if (GLTFFileLoader._compareVersion(minVersion, loaderVersion) > 0) {
  101882. throw new Error("Incompatible minimum version: " + asset.minVersion);
  101883. }
  101884. }
  101885. var createLoaders = {
  101886. 1: GLTFFileLoader.CreateGLTFLoaderV1,
  101887. 2: GLTFFileLoader.CreateGLTFLoaderV2
  101888. };
  101889. var createLoader = createLoaders[version.major];
  101890. if (!createLoader) {
  101891. throw new Error("Unsupported version: " + asset.version);
  101892. }
  101893. var loader = createLoader();
  101894. loader.coordinateSystemMode = this.coordinateSystemMode;
  101895. loader.animationStartMode = this.animationStartMode;
  101896. loader.compileMaterials = this.compileMaterials;
  101897. loader.useClipPlane = this.useClipPlane;
  101898. loader.compileShadowGenerators = this.compileShadowGenerators;
  101899. loader.transparencyAsCoverage = this.transparencyAsCoverage;
  101900. loader._normalizeAnimationGroupsToBeginAtZero = this._normalizeAnimationGroupsToBeginAtZero;
  101901. loader.preprocessUrlAsync = this.preprocessUrlAsync;
  101902. loader.onMeshLoadedObservable.add(function (mesh) { return _this.onMeshLoadedObservable.notifyObservers(mesh); });
  101903. loader.onTextureLoadedObservable.add(function (texture) { return _this.onTextureLoadedObservable.notifyObservers(texture); });
  101904. loader.onMaterialLoadedObservable.add(function (material) { return _this.onMaterialLoadedObservable.notifyObservers(material); });
  101905. loader.onCameraLoadedObservable.add(function (camera) { return _this.onCameraLoadedObservable.notifyObservers(camera); });
  101906. loader.onExtensionLoadedObservable.add(function (extension) { return _this.onExtensionLoadedObservable.notifyObservers(extension); });
  101907. loader.onCompleteObservable.add(function () {
  101908. _this.onMeshLoadedObservable.clear();
  101909. _this.onTextureLoadedObservable.clear();
  101910. _this.onMaterialLoadedObservable.clear();
  101911. _this.onCameraLoadedObservable.clear();
  101912. _this.onExtensionLoadedObservable.clear();
  101913. _this.onCompleteObservable.notifyObservers(_this);
  101914. _this.onCompleteObservable.clear();
  101915. });
  101916. return loader;
  101917. };
  101918. GLTFFileLoader._parseBinary = function (data) {
  101919. var Binary = {
  101920. Magic: 0x46546C67
  101921. };
  101922. var binaryReader = new BinaryReader(data);
  101923. var magic = binaryReader.readUint32();
  101924. if (magic !== Binary.Magic) {
  101925. throw new Error("Unexpected magic: " + magic);
  101926. }
  101927. var version = binaryReader.readUint32();
  101928. switch (version) {
  101929. case 1: return GLTFFileLoader._parseV1(binaryReader);
  101930. case 2: return GLTFFileLoader._parseV2(binaryReader);
  101931. }
  101932. throw new Error("Unsupported version: " + version);
  101933. };
  101934. GLTFFileLoader._parseV1 = function (binaryReader) {
  101935. var ContentFormat = {
  101936. JSON: 0
  101937. };
  101938. var length = binaryReader.readUint32();
  101939. if (length != binaryReader.getLength()) {
  101940. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101941. }
  101942. var contentLength = binaryReader.readUint32();
  101943. var contentFormat = binaryReader.readUint32();
  101944. var content;
  101945. switch (contentFormat) {
  101946. case ContentFormat.JSON: {
  101947. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  101948. break;
  101949. }
  101950. default: {
  101951. throw new Error("Unexpected content format: " + contentFormat);
  101952. }
  101953. }
  101954. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  101955. var body = binaryReader.readUint8Array(bytesRemaining);
  101956. return {
  101957. json: content,
  101958. bin: body
  101959. };
  101960. };
  101961. GLTFFileLoader._parseV2 = function (binaryReader) {
  101962. var ChunkFormat = {
  101963. JSON: 0x4E4F534A,
  101964. BIN: 0x004E4942
  101965. };
  101966. var length = binaryReader.readUint32();
  101967. if (length !== binaryReader.getLength()) {
  101968. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  101969. }
  101970. // JSON chunk
  101971. var chunkLength = binaryReader.readUint32();
  101972. var chunkFormat = binaryReader.readUint32();
  101973. if (chunkFormat !== ChunkFormat.JSON) {
  101974. throw new Error("First chunk format is not JSON");
  101975. }
  101976. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  101977. // Look for BIN chunk
  101978. var bin = null;
  101979. while (binaryReader.getPosition() < binaryReader.getLength()) {
  101980. var chunkLength_1 = binaryReader.readUint32();
  101981. var chunkFormat_1 = binaryReader.readUint32();
  101982. switch (chunkFormat_1) {
  101983. case ChunkFormat.JSON: {
  101984. throw new Error("Unexpected JSON chunk");
  101985. }
  101986. case ChunkFormat.BIN: {
  101987. bin = binaryReader.readUint8Array(chunkLength_1);
  101988. break;
  101989. }
  101990. default: {
  101991. // ignore unrecognized chunkFormat
  101992. binaryReader.skipBytes(chunkLength_1);
  101993. break;
  101994. }
  101995. }
  101996. }
  101997. return {
  101998. json: json,
  101999. bin: bin
  102000. };
  102001. };
  102002. GLTFFileLoader._parseVersion = function (version) {
  102003. if (version === "1.0" || version === "1.0.1") {
  102004. return {
  102005. major: 1,
  102006. minor: 0
  102007. };
  102008. }
  102009. var match = (version + "").match(/^(\d+)\.(\d+)/);
  102010. if (!match) {
  102011. return null;
  102012. }
  102013. return {
  102014. major: parseInt(match[1]),
  102015. minor: parseInt(match[2])
  102016. };
  102017. };
  102018. GLTFFileLoader._compareVersion = function (a, b) {
  102019. if (a.major > b.major)
  102020. return 1;
  102021. if (a.major < b.major)
  102022. return -1;
  102023. if (a.minor > b.minor)
  102024. return 1;
  102025. if (a.minor < b.minor)
  102026. return -1;
  102027. return 0;
  102028. };
  102029. GLTFFileLoader._decodeBufferToText = function (buffer) {
  102030. var result = "";
  102031. var length = buffer.byteLength;
  102032. for (var i = 0; i < length; i++) {
  102033. result += String.fromCharCode(buffer[i]);
  102034. }
  102035. return result;
  102036. };
  102037. // #endregion
  102038. // #region V1 options
  102039. /**
  102040. * 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.
  102041. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  102042. * Defaults to true.
  102043. */
  102044. GLTFFileLoader.IncrementalLoading = true;
  102045. /**
  102046. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  102047. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  102048. */
  102049. GLTFFileLoader.HomogeneousCoordinates = false;
  102050. return GLTFFileLoader;
  102051. }());
  102052. BABYLON.GLTFFileLoader = GLTFFileLoader;
  102053. var BinaryReader = /** @class */ (function () {
  102054. function BinaryReader(arrayBuffer) {
  102055. this._arrayBuffer = arrayBuffer;
  102056. this._dataView = new DataView(arrayBuffer);
  102057. this._byteOffset = 0;
  102058. }
  102059. BinaryReader.prototype.getPosition = function () {
  102060. return this._byteOffset;
  102061. };
  102062. BinaryReader.prototype.getLength = function () {
  102063. return this._arrayBuffer.byteLength;
  102064. };
  102065. BinaryReader.prototype.readUint32 = function () {
  102066. var value = this._dataView.getUint32(this._byteOffset, true);
  102067. this._byteOffset += 4;
  102068. return value;
  102069. };
  102070. BinaryReader.prototype.readUint8Array = function (length) {
  102071. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  102072. this._byteOffset += length;
  102073. return value;
  102074. };
  102075. BinaryReader.prototype.skipBytes = function (length) {
  102076. this._byteOffset += length;
  102077. };
  102078. return BinaryReader;
  102079. }());
  102080. if (BABYLON.SceneLoader) {
  102081. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  102082. }
  102083. })(BABYLON || (BABYLON = {}));
  102084. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  102085. var BABYLON;
  102086. (function (BABYLON) {
  102087. var GLTF1;
  102088. (function (GLTF1) {
  102089. /**
  102090. * Enums
  102091. */
  102092. var EComponentType;
  102093. (function (EComponentType) {
  102094. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  102095. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102096. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  102097. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102098. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  102099. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  102100. var EShaderType;
  102101. (function (EShaderType) {
  102102. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  102103. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  102104. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  102105. var EParameterType;
  102106. (function (EParameterType) {
  102107. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  102108. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  102109. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  102110. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  102111. EParameterType[EParameterType["INT"] = 5124] = "INT";
  102112. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  102113. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  102114. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  102115. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  102116. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  102117. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  102118. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  102119. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  102120. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  102121. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  102122. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  102123. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  102124. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  102125. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  102126. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  102127. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  102128. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  102129. var ETextureWrapMode;
  102130. (function (ETextureWrapMode) {
  102131. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  102132. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  102133. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  102134. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  102135. var ETextureFilterType;
  102136. (function (ETextureFilterType) {
  102137. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  102138. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  102139. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  102140. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  102141. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  102142. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  102143. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  102144. var ETextureFormat;
  102145. (function (ETextureFormat) {
  102146. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  102147. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  102148. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  102149. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  102150. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  102151. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  102152. var ECullingType;
  102153. (function (ECullingType) {
  102154. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  102155. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  102156. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  102157. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  102158. var EBlendingFunction;
  102159. (function (EBlendingFunction) {
  102160. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  102161. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  102162. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  102163. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  102164. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  102165. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  102166. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  102167. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  102168. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  102169. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  102170. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  102171. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  102172. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  102173. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  102174. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  102175. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  102176. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  102177. })(BABYLON || (BABYLON = {}));
  102178. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  102179. var BABYLON;
  102180. (function (BABYLON) {
  102181. var GLTF1;
  102182. (function (GLTF1) {
  102183. /**
  102184. * Tokenizer. Used for shaders compatibility
  102185. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  102186. */
  102187. var ETokenType;
  102188. (function (ETokenType) {
  102189. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  102190. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  102191. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  102192. })(ETokenType || (ETokenType = {}));
  102193. var Tokenizer = /** @class */ (function () {
  102194. function Tokenizer(toParse) {
  102195. this._pos = 0;
  102196. this.currentToken = ETokenType.UNKNOWN;
  102197. this.currentIdentifier = "";
  102198. this.currentString = "";
  102199. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  102200. this._toParse = toParse;
  102201. this._maxPos = toParse.length;
  102202. }
  102203. Tokenizer.prototype.getNextToken = function () {
  102204. if (this.isEnd())
  102205. return ETokenType.END_OF_INPUT;
  102206. this.currentString = this.read();
  102207. this.currentToken = ETokenType.UNKNOWN;
  102208. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  102209. this.currentToken = ETokenType.IDENTIFIER;
  102210. this.currentIdentifier = this.currentString;
  102211. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  102212. this.currentIdentifier += this.currentString;
  102213. this.forward();
  102214. }
  102215. }
  102216. return this.currentToken;
  102217. };
  102218. Tokenizer.prototype.peek = function () {
  102219. return this._toParse[this._pos];
  102220. };
  102221. Tokenizer.prototype.read = function () {
  102222. return this._toParse[this._pos++];
  102223. };
  102224. Tokenizer.prototype.forward = function () {
  102225. this._pos++;
  102226. };
  102227. Tokenizer.prototype.isEnd = function () {
  102228. return this._pos >= this._maxPos;
  102229. };
  102230. return Tokenizer;
  102231. }());
  102232. /**
  102233. * Values
  102234. */
  102235. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  102236. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  102237. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  102238. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  102239. /**
  102240. * Parse
  102241. */
  102242. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  102243. for (var buf in parsedBuffers) {
  102244. var parsedBuffer = parsedBuffers[buf];
  102245. gltfRuntime.buffers[buf] = parsedBuffer;
  102246. gltfRuntime.buffersCount++;
  102247. }
  102248. };
  102249. var parseShaders = function (parsedShaders, gltfRuntime) {
  102250. for (var sha in parsedShaders) {
  102251. var parsedShader = parsedShaders[sha];
  102252. gltfRuntime.shaders[sha] = parsedShader;
  102253. gltfRuntime.shaderscount++;
  102254. }
  102255. };
  102256. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  102257. for (var object in parsedObjects) {
  102258. var parsedObject = parsedObjects[object];
  102259. gltfRuntime[runtimeProperty][object] = parsedObject;
  102260. }
  102261. };
  102262. /**
  102263. * Utils
  102264. */
  102265. var normalizeUVs = function (buffer) {
  102266. if (!buffer) {
  102267. return;
  102268. }
  102269. for (var i = 0; i < buffer.length / 2; i++) {
  102270. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  102271. }
  102272. };
  102273. var getAttribute = function (attributeParameter) {
  102274. if (attributeParameter.semantic === "NORMAL") {
  102275. return "normal";
  102276. }
  102277. else if (attributeParameter.semantic === "POSITION") {
  102278. return "position";
  102279. }
  102280. else if (attributeParameter.semantic === "JOINT") {
  102281. return "matricesIndices";
  102282. }
  102283. else if (attributeParameter.semantic === "WEIGHT") {
  102284. return "matricesWeights";
  102285. }
  102286. else if (attributeParameter.semantic === "COLOR") {
  102287. return "color";
  102288. }
  102289. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  102290. var channel = Number(attributeParameter.semantic.split("_")[1]);
  102291. return "uv" + (channel === 0 ? "" : channel + 1);
  102292. }
  102293. return null;
  102294. };
  102295. /**
  102296. * Loads and creates animations
  102297. */
  102298. var loadAnimations = function (gltfRuntime) {
  102299. for (var anim in gltfRuntime.animations) {
  102300. var animation = gltfRuntime.animations[anim];
  102301. if (!animation.channels || !animation.samplers) {
  102302. continue;
  102303. }
  102304. var lastAnimation = null;
  102305. for (var i = 0; i < animation.channels.length; i++) {
  102306. // Get parameters and load buffers
  102307. var channel = animation.channels[i];
  102308. var sampler = animation.samplers[channel.sampler];
  102309. if (!sampler) {
  102310. continue;
  102311. }
  102312. var inputData = null;
  102313. var outputData = null;
  102314. if (animation.parameters) {
  102315. inputData = animation.parameters[sampler.input];
  102316. outputData = animation.parameters[sampler.output];
  102317. }
  102318. else {
  102319. inputData = sampler.input;
  102320. outputData = sampler.output;
  102321. }
  102322. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  102323. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  102324. var targetID = channel.target.id;
  102325. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  102326. if (targetNode === null) {
  102327. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  102328. }
  102329. if (targetNode === null) {
  102330. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  102331. continue;
  102332. }
  102333. var isBone = targetNode instanceof BABYLON.Bone;
  102334. // Get target path (position, rotation or scaling)
  102335. var targetPath = channel.target.path;
  102336. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  102337. if (targetPathIndex !== -1) {
  102338. targetPath = babylonAnimationPaths[targetPathIndex];
  102339. }
  102340. // Determine animation type
  102341. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  102342. if (!isBone) {
  102343. if (targetPath === "rotationQuaternion") {
  102344. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  102345. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  102346. }
  102347. else {
  102348. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  102349. }
  102350. }
  102351. // Create animation and key frames
  102352. var babylonAnimation = null;
  102353. var keys = [];
  102354. var arrayOffset = 0;
  102355. var modifyKey = false;
  102356. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  102357. babylonAnimation = lastAnimation;
  102358. modifyKey = true;
  102359. }
  102360. if (!modifyKey) {
  102361. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  102362. }
  102363. // For each frame
  102364. for (var j = 0; j < bufferInput.length; j++) {
  102365. var value = null;
  102366. if (targetPath === "rotationQuaternion") { // VEC4
  102367. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  102368. arrayOffset += 4;
  102369. }
  102370. else { // Position and scaling are VEC3
  102371. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  102372. arrayOffset += 3;
  102373. }
  102374. if (isBone) {
  102375. var bone = targetNode;
  102376. var translation = BABYLON.Vector3.Zero();
  102377. var rotationQuaternion = new BABYLON.Quaternion();
  102378. var scaling = BABYLON.Vector3.Zero();
  102379. // Warning on decompose
  102380. var mat = bone.getBaseMatrix();
  102381. if (modifyKey && lastAnimation) {
  102382. mat = lastAnimation.getKeys()[j].value;
  102383. }
  102384. mat.decompose(scaling, rotationQuaternion, translation);
  102385. if (targetPath === "position") {
  102386. translation = value;
  102387. }
  102388. else if (targetPath === "rotationQuaternion") {
  102389. rotationQuaternion = value;
  102390. }
  102391. else {
  102392. scaling = value;
  102393. }
  102394. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  102395. }
  102396. if (!modifyKey) {
  102397. keys.push({
  102398. frame: bufferInput[j],
  102399. value: value
  102400. });
  102401. }
  102402. else if (lastAnimation) {
  102403. lastAnimation.getKeys()[j].value = value;
  102404. }
  102405. }
  102406. // Finish
  102407. if (!modifyKey && babylonAnimation) {
  102408. babylonAnimation.setKeys(keys);
  102409. targetNode.animations.push(babylonAnimation);
  102410. }
  102411. lastAnimation = babylonAnimation;
  102412. gltfRuntime.scene.stopAnimation(targetNode);
  102413. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  102414. }
  102415. }
  102416. };
  102417. /**
  102418. * Returns the bones transformation matrix
  102419. */
  102420. var configureBoneTransformation = function (node) {
  102421. var mat = null;
  102422. if (node.translation || node.rotation || node.scale) {
  102423. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  102424. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  102425. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  102426. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  102427. }
  102428. else {
  102429. mat = BABYLON.Matrix.FromArray(node.matrix);
  102430. }
  102431. return mat;
  102432. };
  102433. /**
  102434. * Returns the parent bone
  102435. */
  102436. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  102437. // Try to find
  102438. for (var i = 0; i < newSkeleton.bones.length; i++) {
  102439. if (newSkeleton.bones[i].name === jointName) {
  102440. return newSkeleton.bones[i];
  102441. }
  102442. }
  102443. // Not found, search in gltf nodes
  102444. var nodes = gltfRuntime.nodes;
  102445. for (var nde in nodes) {
  102446. var node = nodes[nde];
  102447. if (!node.jointName) {
  102448. continue;
  102449. }
  102450. var children = node.children;
  102451. for (var i = 0; i < children.length; i++) {
  102452. var child = gltfRuntime.nodes[children[i]];
  102453. if (!child.jointName) {
  102454. continue;
  102455. }
  102456. if (child.jointName === jointName) {
  102457. var mat = configureBoneTransformation(node);
  102458. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  102459. bone.id = nde;
  102460. return bone;
  102461. }
  102462. }
  102463. }
  102464. return null;
  102465. };
  102466. /**
  102467. * Returns the appropriate root node
  102468. */
  102469. var getNodeToRoot = function (nodesToRoot, id) {
  102470. for (var i = 0; i < nodesToRoot.length; i++) {
  102471. var nodeToRoot = nodesToRoot[i];
  102472. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  102473. var child = nodeToRoot.node.children[j];
  102474. if (child === id) {
  102475. return nodeToRoot.bone;
  102476. }
  102477. }
  102478. }
  102479. return null;
  102480. };
  102481. /**
  102482. * Returns the node with the joint name
  102483. */
  102484. var getJointNode = function (gltfRuntime, jointName) {
  102485. var nodes = gltfRuntime.nodes;
  102486. var node = nodes[jointName];
  102487. if (node) {
  102488. return {
  102489. node: node,
  102490. id: jointName
  102491. };
  102492. }
  102493. for (var nde in nodes) {
  102494. node = nodes[nde];
  102495. if (node.jointName === jointName) {
  102496. return {
  102497. node: node,
  102498. id: nde
  102499. };
  102500. }
  102501. }
  102502. return null;
  102503. };
  102504. /**
  102505. * Checks if a nodes is in joints
  102506. */
  102507. var nodeIsInJoints = function (skins, id) {
  102508. for (var i = 0; i < skins.jointNames.length; i++) {
  102509. if (skins.jointNames[i] === id) {
  102510. return true;
  102511. }
  102512. }
  102513. return false;
  102514. };
  102515. /**
  102516. * Fills the nodes to root for bones and builds hierarchy
  102517. */
  102518. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  102519. // Creates nodes for root
  102520. for (var nde in gltfRuntime.nodes) {
  102521. var node = gltfRuntime.nodes[nde];
  102522. var id = nde;
  102523. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  102524. continue;
  102525. }
  102526. // Create node to root bone
  102527. var mat = configureBoneTransformation(node);
  102528. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  102529. bone.id = id;
  102530. nodesToRoot.push({ bone: bone, node: node, id: id });
  102531. }
  102532. // Parenting
  102533. for (var i = 0; i < nodesToRoot.length; i++) {
  102534. var nodeToRoot = nodesToRoot[i];
  102535. var children = nodeToRoot.node.children;
  102536. for (var j = 0; j < children.length; j++) {
  102537. var child = null;
  102538. for (var k = 0; k < nodesToRoot.length; k++) {
  102539. if (nodesToRoot[k].id === children[j]) {
  102540. child = nodesToRoot[k];
  102541. break;
  102542. }
  102543. }
  102544. if (child) {
  102545. child.bone._parent = nodeToRoot.bone;
  102546. nodeToRoot.bone.children.push(child.bone);
  102547. }
  102548. }
  102549. }
  102550. };
  102551. /**
  102552. * Imports a skeleton
  102553. */
  102554. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  102555. if (!newSkeleton) {
  102556. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  102557. }
  102558. if (!skins.babylonSkeleton) {
  102559. return newSkeleton;
  102560. }
  102561. // Find the root bones
  102562. var nodesToRoot = [];
  102563. var nodesToRootToAdd = [];
  102564. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  102565. newSkeleton.bones = [];
  102566. // Joints
  102567. for (var i = 0; i < skins.jointNames.length; i++) {
  102568. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102569. if (!jointNode) {
  102570. continue;
  102571. }
  102572. var node = jointNode.node;
  102573. if (!node) {
  102574. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  102575. continue;
  102576. }
  102577. var id = jointNode.id;
  102578. // Optimize, if the bone already exists...
  102579. var existingBone = gltfRuntime.scene.getBoneByID(id);
  102580. if (existingBone) {
  102581. newSkeleton.bones.push(existingBone);
  102582. continue;
  102583. }
  102584. // Search for parent bone
  102585. var foundBone = false;
  102586. var parentBone = null;
  102587. for (var j = 0; j < i; j++) {
  102588. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  102589. if (!jointNode_1) {
  102590. continue;
  102591. }
  102592. var joint = jointNode_1.node;
  102593. if (!joint) {
  102594. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  102595. continue;
  102596. }
  102597. var children = joint.children;
  102598. if (!children) {
  102599. continue;
  102600. }
  102601. foundBone = false;
  102602. for (var k = 0; k < children.length; k++) {
  102603. if (children[k] === id) {
  102604. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  102605. foundBone = true;
  102606. break;
  102607. }
  102608. }
  102609. if (foundBone) {
  102610. break;
  102611. }
  102612. }
  102613. // Create bone
  102614. var mat = configureBoneTransformation(node);
  102615. if (!parentBone && nodesToRoot.length > 0) {
  102616. parentBone = getNodeToRoot(nodesToRoot, id);
  102617. if (parentBone) {
  102618. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  102619. nodesToRootToAdd.push(parentBone);
  102620. }
  102621. }
  102622. }
  102623. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  102624. bone.id = id;
  102625. }
  102626. // Polish
  102627. var bones = newSkeleton.bones;
  102628. newSkeleton.bones = [];
  102629. for (var i = 0; i < skins.jointNames.length; i++) {
  102630. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  102631. if (!jointNode) {
  102632. continue;
  102633. }
  102634. for (var j = 0; j < bones.length; j++) {
  102635. if (bones[j].id === jointNode.id) {
  102636. newSkeleton.bones.push(bones[j]);
  102637. break;
  102638. }
  102639. }
  102640. }
  102641. newSkeleton.prepare();
  102642. // Finish
  102643. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  102644. newSkeleton.bones.push(nodesToRootToAdd[i]);
  102645. }
  102646. return newSkeleton;
  102647. };
  102648. /**
  102649. * Imports a mesh and its geometries
  102650. */
  102651. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  102652. if (!newMesh) {
  102653. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102654. newMesh.id = id;
  102655. }
  102656. if (!node.babylonNode) {
  102657. return newMesh;
  102658. }
  102659. var subMaterials = [];
  102660. var vertexData = null;
  102661. var verticesStarts = new Array();
  102662. var verticesCounts = new Array();
  102663. var indexStarts = new Array();
  102664. var indexCounts = new Array();
  102665. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102666. var meshID = meshes[meshIndex];
  102667. var mesh = gltfRuntime.meshes[meshID];
  102668. if (!mesh) {
  102669. continue;
  102670. }
  102671. // Positions, normals and UVs
  102672. for (var i = 0; i < mesh.primitives.length; i++) {
  102673. // Temporary vertex data
  102674. var tempVertexData = new BABYLON.VertexData();
  102675. var primitive = mesh.primitives[i];
  102676. if (primitive.mode !== 4) {
  102677. // continue;
  102678. }
  102679. var attributes = primitive.attributes;
  102680. var accessor = null;
  102681. var buffer = null;
  102682. // Set positions, normal and uvs
  102683. for (var semantic in attributes) {
  102684. // Link accessor and buffer view
  102685. accessor = gltfRuntime.accessors[attributes[semantic]];
  102686. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102687. if (semantic === "NORMAL") {
  102688. tempVertexData.normals = new Float32Array(buffer.length);
  102689. tempVertexData.normals.set(buffer);
  102690. }
  102691. else if (semantic === "POSITION") {
  102692. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  102693. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  102694. for (var j = 0; j < buffer.length; j += 4) {
  102695. tempVertexData.positions[j] = buffer[j];
  102696. tempVertexData.positions[j + 1] = buffer[j + 1];
  102697. tempVertexData.positions[j + 2] = buffer[j + 2];
  102698. }
  102699. }
  102700. else {
  102701. tempVertexData.positions = new Float32Array(buffer.length);
  102702. tempVertexData.positions.set(buffer);
  102703. }
  102704. verticesCounts.push(tempVertexData.positions.length);
  102705. }
  102706. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  102707. var channel = Number(semantic.split("_")[1]);
  102708. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  102709. var uvs = new Float32Array(buffer.length);
  102710. uvs.set(buffer);
  102711. normalizeUVs(uvs);
  102712. tempVertexData.set(uvs, uvKind);
  102713. }
  102714. else if (semantic === "JOINT") {
  102715. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  102716. tempVertexData.matricesIndices.set(buffer);
  102717. }
  102718. else if (semantic === "WEIGHT") {
  102719. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  102720. tempVertexData.matricesWeights.set(buffer);
  102721. }
  102722. else if (semantic === "COLOR") {
  102723. tempVertexData.colors = new Float32Array(buffer.length);
  102724. tempVertexData.colors.set(buffer);
  102725. }
  102726. }
  102727. // Indices
  102728. accessor = gltfRuntime.accessors[primitive.indices];
  102729. if (accessor) {
  102730. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  102731. tempVertexData.indices = new Int32Array(buffer.length);
  102732. tempVertexData.indices.set(buffer);
  102733. indexCounts.push(tempVertexData.indices.length);
  102734. }
  102735. else {
  102736. // Set indices on the fly
  102737. var indices = [];
  102738. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  102739. indices.push(j);
  102740. }
  102741. tempVertexData.indices = new Int32Array(indices);
  102742. indexCounts.push(tempVertexData.indices.length);
  102743. }
  102744. if (!vertexData) {
  102745. vertexData = tempVertexData;
  102746. }
  102747. else {
  102748. vertexData.merge(tempVertexData);
  102749. }
  102750. // Sub material
  102751. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  102752. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  102753. // Update vertices start and index start
  102754. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  102755. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  102756. }
  102757. }
  102758. var material;
  102759. if (subMaterials.length > 1) {
  102760. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  102761. material.subMaterials = subMaterials;
  102762. }
  102763. else {
  102764. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  102765. }
  102766. if (subMaterials.length === 1) {
  102767. material = subMaterials[0];
  102768. }
  102769. if (!newMesh.material) {
  102770. newMesh.material = material;
  102771. }
  102772. // Apply geometry
  102773. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  102774. newMesh.computeWorldMatrix(true);
  102775. // Apply submeshes
  102776. newMesh.subMeshes = [];
  102777. var index = 0;
  102778. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  102779. var meshID = meshes[meshIndex];
  102780. var mesh = gltfRuntime.meshes[meshID];
  102781. if (!mesh) {
  102782. continue;
  102783. }
  102784. for (var i = 0; i < mesh.primitives.length; i++) {
  102785. if (mesh.primitives[i].mode !== 4) {
  102786. //continue;
  102787. }
  102788. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  102789. index++;
  102790. }
  102791. }
  102792. // Finish
  102793. return newMesh;
  102794. };
  102795. /**
  102796. * Configure node transformation from position, rotation and scaling
  102797. */
  102798. var configureNode = function (newNode, position, rotation, scaling) {
  102799. if (newNode.position) {
  102800. newNode.position = position;
  102801. }
  102802. if (newNode.rotationQuaternion || newNode.rotation) {
  102803. newNode.rotationQuaternion = rotation;
  102804. }
  102805. if (newNode.scaling) {
  102806. newNode.scaling = scaling;
  102807. }
  102808. };
  102809. /**
  102810. * Configures node from transformation matrix
  102811. */
  102812. var configureNodeFromMatrix = function (newNode, node, parent) {
  102813. if (node.matrix) {
  102814. var position = new BABYLON.Vector3(0, 0, 0);
  102815. var rotation = new BABYLON.Quaternion();
  102816. var scaling = new BABYLON.Vector3(0, 0, 0);
  102817. var mat = BABYLON.Matrix.FromArray(node.matrix);
  102818. mat.decompose(scaling, rotation, position);
  102819. configureNode(newNode, position, rotation, scaling);
  102820. }
  102821. else if (node.translation && node.rotation && node.scale) {
  102822. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  102823. }
  102824. newNode.computeWorldMatrix(true);
  102825. };
  102826. /**
  102827. * Imports a node
  102828. */
  102829. var importNode = function (gltfRuntime, node, id, parent) {
  102830. var lastNode = null;
  102831. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  102832. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  102833. return null;
  102834. }
  102835. }
  102836. // Meshes
  102837. if (node.skin) {
  102838. if (node.meshes) {
  102839. var skin = gltfRuntime.skins[node.skin];
  102840. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  102841. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  102842. if (newMesh.skeleton === null) {
  102843. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  102844. if (!skin.babylonSkeleton) {
  102845. skin.babylonSkeleton = newMesh.skeleton;
  102846. }
  102847. }
  102848. lastNode = newMesh;
  102849. }
  102850. }
  102851. else if (node.meshes) {
  102852. /**
  102853. * Improve meshes property
  102854. */
  102855. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  102856. lastNode = newMesh;
  102857. }
  102858. // Lights
  102859. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102860. var light = gltfRuntime.lights[node.light];
  102861. if (light) {
  102862. if (light.type === "ambient") {
  102863. var ambienLight = light[light.type];
  102864. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102865. hemiLight.name = node.name || "";
  102866. if (ambienLight.color) {
  102867. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  102868. }
  102869. lastNode = hemiLight;
  102870. }
  102871. else if (light.type === "directional") {
  102872. var directionalLight = light[light.type];
  102873. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102874. dirLight.name = node.name || "";
  102875. if (directionalLight.color) {
  102876. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  102877. }
  102878. lastNode = dirLight;
  102879. }
  102880. else if (light.type === "point") {
  102881. var pointLight = light[light.type];
  102882. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  102883. ptLight.name = node.name || "";
  102884. if (pointLight.color) {
  102885. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  102886. }
  102887. lastNode = ptLight;
  102888. }
  102889. else if (light.type === "spot") {
  102890. var spotLight = light[light.type];
  102891. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  102892. spLight.name = node.name || "";
  102893. if (spotLight.color) {
  102894. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  102895. }
  102896. if (spotLight.fallOfAngle) {
  102897. spLight.angle = spotLight.fallOfAngle;
  102898. }
  102899. if (spotLight.fallOffExponent) {
  102900. spLight.exponent = spotLight.fallOffExponent;
  102901. }
  102902. lastNode = spLight;
  102903. }
  102904. }
  102905. }
  102906. // Cameras
  102907. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  102908. var camera = gltfRuntime.cameras[node.camera];
  102909. if (camera) {
  102910. if (camera.type === "orthographic") {
  102911. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  102912. orthoCamera.name = node.name || "";
  102913. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  102914. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102915. lastNode = orthoCamera;
  102916. }
  102917. else if (camera.type === "perspective") {
  102918. var perspectiveCamera = camera[camera.type];
  102919. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  102920. persCamera.name = node.name || "";
  102921. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  102922. if (!perspectiveCamera.aspectRatio) {
  102923. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  102924. }
  102925. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  102926. persCamera.maxZ = perspectiveCamera.zfar;
  102927. persCamera.minZ = perspectiveCamera.znear;
  102928. }
  102929. lastNode = persCamera;
  102930. }
  102931. }
  102932. }
  102933. // Empty node
  102934. if (!node.jointName) {
  102935. if (node.babylonNode) {
  102936. return node.babylonNode;
  102937. }
  102938. else if (lastNode === null) {
  102939. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  102940. node.babylonNode = dummy;
  102941. lastNode = dummy;
  102942. }
  102943. }
  102944. if (lastNode !== null) {
  102945. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  102946. configureNodeFromMatrix(lastNode, node, parent);
  102947. }
  102948. else {
  102949. var translation = node.translation || [0, 0, 0];
  102950. var rotation = node.rotation || [0, 0, 0, 1];
  102951. var scale = node.scale || [1, 1, 1];
  102952. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  102953. }
  102954. lastNode.updateCache(true);
  102955. node.babylonNode = lastNode;
  102956. }
  102957. return lastNode;
  102958. };
  102959. /**
  102960. * Traverses nodes and creates them
  102961. */
  102962. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  102963. if (meshIncluded === void 0) { meshIncluded = false; }
  102964. var node = gltfRuntime.nodes[id];
  102965. var newNode = null;
  102966. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  102967. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  102968. meshIncluded = true;
  102969. }
  102970. else {
  102971. meshIncluded = false;
  102972. }
  102973. }
  102974. else {
  102975. meshIncluded = true;
  102976. }
  102977. if (!node.jointName && meshIncluded) {
  102978. newNode = importNode(gltfRuntime, node, id, parent);
  102979. if (newNode !== null) {
  102980. newNode.id = id;
  102981. newNode.parent = parent;
  102982. }
  102983. }
  102984. if (node.children) {
  102985. for (var i = 0; i < node.children.length; i++) {
  102986. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  102987. }
  102988. }
  102989. };
  102990. /**
  102991. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  102992. */
  102993. var postLoad = function (gltfRuntime) {
  102994. // Nodes
  102995. var currentScene = gltfRuntime.currentScene;
  102996. if (currentScene) {
  102997. for (var i = 0; i < currentScene.nodes.length; i++) {
  102998. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  102999. }
  103000. }
  103001. else {
  103002. for (var thing in gltfRuntime.scenes) {
  103003. currentScene = gltfRuntime.scenes[thing];
  103004. for (var i = 0; i < currentScene.nodes.length; i++) {
  103005. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103006. }
  103007. }
  103008. }
  103009. // Set animations
  103010. loadAnimations(gltfRuntime);
  103011. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  103012. var skeleton = gltfRuntime.scene.skeletons[i];
  103013. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  103014. }
  103015. };
  103016. /**
  103017. * onBind shaderrs callback to set uniforms and matrices
  103018. */
  103019. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  103020. var materialValues = material.values || technique.parameters;
  103021. for (var unif in unTreatedUniforms) {
  103022. var uniform = unTreatedUniforms[unif];
  103023. var type = uniform.type;
  103024. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  103025. if (uniform.semantic && !uniform.source && !uniform.node) {
  103026. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  103027. }
  103028. else if (uniform.semantic && (uniform.source || uniform.node)) {
  103029. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  103030. if (source === null) {
  103031. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  103032. }
  103033. if (source === null) {
  103034. continue;
  103035. }
  103036. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  103037. }
  103038. }
  103039. else {
  103040. var value = materialValues[technique.uniforms[unif]];
  103041. if (!value) {
  103042. continue;
  103043. }
  103044. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103045. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  103046. if (texture === null || texture === undefined) {
  103047. continue;
  103048. }
  103049. shaderMaterial.getEffect().setTexture(unif, texture);
  103050. }
  103051. else {
  103052. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  103053. }
  103054. }
  103055. }
  103056. onSuccess(shaderMaterial);
  103057. };
  103058. /**
  103059. * Prepare uniforms to send the only one time
  103060. * Loads the appropriate textures
  103061. */
  103062. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  103063. var materialValues = material.values || technique.parameters;
  103064. var techniqueUniforms = technique.uniforms;
  103065. /**
  103066. * Prepare values here (not matrices)
  103067. */
  103068. for (var unif in unTreatedUniforms) {
  103069. var uniform = unTreatedUniforms[unif];
  103070. var type = uniform.type;
  103071. var value = materialValues[techniqueUniforms[unif]];
  103072. if (value === undefined) {
  103073. // In case the value is the same for all materials
  103074. value = uniform.value;
  103075. }
  103076. if (!value) {
  103077. continue;
  103078. }
  103079. var onLoadTexture = function (uniformName) {
  103080. return function (texture) {
  103081. if (uniform.value && uniformName) {
  103082. // Static uniform
  103083. shaderMaterial.setTexture(uniformName, texture);
  103084. delete unTreatedUniforms[uniformName];
  103085. }
  103086. };
  103087. };
  103088. // Texture (sampler2D)
  103089. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  103090. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  103091. }
  103092. // Others
  103093. else {
  103094. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  103095. // Static uniform
  103096. delete unTreatedUniforms[unif];
  103097. }
  103098. }
  103099. }
  103100. };
  103101. /**
  103102. * Shader compilation failed
  103103. */
  103104. var onShaderCompileError = function (program, shaderMaterial, onError) {
  103105. return function (effect, error) {
  103106. shaderMaterial.dispose(true);
  103107. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  103108. };
  103109. };
  103110. /**
  103111. * Shader compilation success
  103112. */
  103113. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  103114. return function (_) {
  103115. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  103116. shaderMaterial.onBind = function (mesh) {
  103117. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  103118. };
  103119. };
  103120. };
  103121. /**
  103122. * Returns the appropriate uniform if already handled by babylon
  103123. */
  103124. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  103125. for (var unif in technique.uniforms) {
  103126. var uniform = technique.uniforms[unif];
  103127. var uniformParameter = technique.parameters[uniform];
  103128. if (tokenizer.currentIdentifier === unif) {
  103129. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  103130. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103131. if (transformIndex !== -1) {
  103132. delete unTreatedUniforms[unif];
  103133. return babylonTransforms[transformIndex];
  103134. }
  103135. }
  103136. }
  103137. }
  103138. return tokenizer.currentIdentifier;
  103139. };
  103140. /**
  103141. * All shaders loaded. Create materials one by one
  103142. */
  103143. var importMaterials = function (gltfRuntime) {
  103144. // Create materials
  103145. for (var mat in gltfRuntime.materials) {
  103146. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  103147. }
  103148. };
  103149. /**
  103150. * Implementation of the base glTF spec
  103151. */
  103152. var GLTFLoaderBase = /** @class */ (function () {
  103153. function GLTFLoaderBase() {
  103154. }
  103155. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  103156. var gltfRuntime = {
  103157. extensions: {},
  103158. accessors: {},
  103159. buffers: {},
  103160. bufferViews: {},
  103161. meshes: {},
  103162. lights: {},
  103163. cameras: {},
  103164. nodes: {},
  103165. images: {},
  103166. textures: {},
  103167. shaders: {},
  103168. programs: {},
  103169. samplers: {},
  103170. techniques: {},
  103171. materials: {},
  103172. animations: {},
  103173. skins: {},
  103174. extensionsUsed: [],
  103175. scenes: {},
  103176. buffersCount: 0,
  103177. shaderscount: 0,
  103178. scene: scene,
  103179. rootUrl: rootUrl,
  103180. loadedBufferCount: 0,
  103181. loadedBufferViews: {},
  103182. loadedShaderCount: 0,
  103183. importOnlyMeshes: false,
  103184. dummyNodes: []
  103185. };
  103186. // Parse
  103187. if (parsedData.extensions) {
  103188. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  103189. }
  103190. if (parsedData.extensionsUsed) {
  103191. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  103192. }
  103193. if (parsedData.buffers) {
  103194. parseBuffers(parsedData.buffers, gltfRuntime);
  103195. }
  103196. if (parsedData.bufferViews) {
  103197. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  103198. }
  103199. if (parsedData.accessors) {
  103200. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  103201. }
  103202. if (parsedData.meshes) {
  103203. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  103204. }
  103205. if (parsedData.lights) {
  103206. parseObject(parsedData.lights, "lights", gltfRuntime);
  103207. }
  103208. if (parsedData.cameras) {
  103209. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  103210. }
  103211. if (parsedData.nodes) {
  103212. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  103213. }
  103214. if (parsedData.images) {
  103215. parseObject(parsedData.images, "images", gltfRuntime);
  103216. }
  103217. if (parsedData.textures) {
  103218. parseObject(parsedData.textures, "textures", gltfRuntime);
  103219. }
  103220. if (parsedData.shaders) {
  103221. parseShaders(parsedData.shaders, gltfRuntime);
  103222. }
  103223. if (parsedData.programs) {
  103224. parseObject(parsedData.programs, "programs", gltfRuntime);
  103225. }
  103226. if (parsedData.samplers) {
  103227. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  103228. }
  103229. if (parsedData.techniques) {
  103230. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  103231. }
  103232. if (parsedData.materials) {
  103233. parseObject(parsedData.materials, "materials", gltfRuntime);
  103234. }
  103235. if (parsedData.animations) {
  103236. parseObject(parsedData.animations, "animations", gltfRuntime);
  103237. }
  103238. if (parsedData.skins) {
  103239. parseObject(parsedData.skins, "skins", gltfRuntime);
  103240. }
  103241. if (parsedData.scenes) {
  103242. gltfRuntime.scenes = parsedData.scenes;
  103243. }
  103244. if (parsedData.scene && parsedData.scenes) {
  103245. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  103246. }
  103247. return gltfRuntime;
  103248. };
  103249. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103250. var buffer = gltfRuntime.buffers[id];
  103251. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  103252. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  103253. }
  103254. else {
  103255. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  103256. if (request) {
  103257. onError(request.status + " " + request.statusText);
  103258. }
  103259. });
  103260. }
  103261. };
  103262. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103263. var texture = gltfRuntime.textures[id];
  103264. if (!texture || !texture.source) {
  103265. onError("");
  103266. return;
  103267. }
  103268. if (texture.babylonTexture) {
  103269. onSuccess(null);
  103270. return;
  103271. }
  103272. var source = gltfRuntime.images[texture.source];
  103273. if (BABYLON.Tools.IsBase64(source.uri)) {
  103274. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  103275. }
  103276. else {
  103277. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  103278. if (request) {
  103279. onError(request.status + " " + request.statusText);
  103280. }
  103281. });
  103282. }
  103283. };
  103284. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103285. var texture = gltfRuntime.textures[id];
  103286. if (texture.babylonTexture) {
  103287. onSuccess(texture.babylonTexture);
  103288. return;
  103289. }
  103290. var sampler = gltfRuntime.samplers[texture.sampler];
  103291. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  103292. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  103293. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  103294. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  103295. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103296. var blob = new Blob([buffer]);
  103297. var blobURL = URL.createObjectURL(blob);
  103298. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  103299. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  103300. if (sampler.wrapS !== undefined) {
  103301. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  103302. }
  103303. if (sampler.wrapT !== undefined) {
  103304. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  103305. }
  103306. newTexture.name = id;
  103307. texture.babylonTexture = newTexture;
  103308. onSuccess(newTexture);
  103309. };
  103310. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103311. var shader = gltfRuntime.shaders[id];
  103312. if (BABYLON.Tools.IsBase64(shader.uri)) {
  103313. var shaderString = atob(shader.uri.split(",")[1]);
  103314. if (onSuccess) {
  103315. onSuccess(shaderString);
  103316. }
  103317. }
  103318. else {
  103319. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  103320. if (request && onError) {
  103321. onError(request.status + " " + request.statusText);
  103322. }
  103323. });
  103324. }
  103325. };
  103326. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103327. var material = gltfRuntime.materials[id];
  103328. if (!material.technique) {
  103329. if (onError) {
  103330. onError("No technique found.");
  103331. }
  103332. return;
  103333. }
  103334. var technique = gltfRuntime.techniques[material.technique];
  103335. if (!technique) {
  103336. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  103337. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  103338. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103339. onSuccess(defaultMaterial);
  103340. return;
  103341. }
  103342. var program = gltfRuntime.programs[technique.program];
  103343. var states = technique.states;
  103344. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  103345. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  103346. var newVertexShader = "";
  103347. var newPixelShader = "";
  103348. var vertexTokenizer = new Tokenizer(vertexShader);
  103349. var pixelTokenizer = new Tokenizer(pixelShader);
  103350. var unTreatedUniforms = {};
  103351. var uniforms = [];
  103352. var attributes = [];
  103353. var samplers = [];
  103354. // Fill uniform, sampler2D and attributes
  103355. for (var unif in technique.uniforms) {
  103356. var uniform = technique.uniforms[unif];
  103357. var uniformParameter = technique.parameters[uniform];
  103358. unTreatedUniforms[unif] = uniformParameter;
  103359. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  103360. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  103361. if (transformIndex !== -1) {
  103362. uniforms.push(babylonTransforms[transformIndex]);
  103363. delete unTreatedUniforms[unif];
  103364. }
  103365. else {
  103366. uniforms.push(unif);
  103367. }
  103368. }
  103369. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  103370. samplers.push(unif);
  103371. }
  103372. else {
  103373. uniforms.push(unif);
  103374. }
  103375. }
  103376. for (var attr in technique.attributes) {
  103377. var attribute = technique.attributes[attr];
  103378. var attributeParameter = technique.parameters[attribute];
  103379. if (attributeParameter.semantic) {
  103380. attributes.push(getAttribute(attributeParameter));
  103381. }
  103382. }
  103383. // Configure vertex shader
  103384. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  103385. var tokenType = vertexTokenizer.currentToken;
  103386. if (tokenType !== ETokenType.IDENTIFIER) {
  103387. newVertexShader += vertexTokenizer.currentString;
  103388. continue;
  103389. }
  103390. var foundAttribute = false;
  103391. for (var attr in technique.attributes) {
  103392. var attribute = technique.attributes[attr];
  103393. var attributeParameter = technique.parameters[attribute];
  103394. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  103395. newVertexShader += getAttribute(attributeParameter);
  103396. foundAttribute = true;
  103397. break;
  103398. }
  103399. }
  103400. if (foundAttribute) {
  103401. continue;
  103402. }
  103403. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  103404. }
  103405. // Configure pixel shader
  103406. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  103407. var tokenType = pixelTokenizer.currentToken;
  103408. if (tokenType !== ETokenType.IDENTIFIER) {
  103409. newPixelShader += pixelTokenizer.currentString;
  103410. continue;
  103411. }
  103412. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  103413. }
  103414. // Create shader material
  103415. var shaderPath = {
  103416. vertex: program.vertexShader + id,
  103417. fragment: program.fragmentShader + id
  103418. };
  103419. var options = {
  103420. attributes: attributes,
  103421. uniforms: uniforms,
  103422. samplers: samplers,
  103423. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  103424. };
  103425. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  103426. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  103427. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  103428. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  103429. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  103430. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  103431. if (states && states.functions) {
  103432. var functions = states.functions;
  103433. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  103434. shaderMaterial.backFaceCulling = false;
  103435. }
  103436. var blendFunc = functions.blendFuncSeparate;
  103437. if (blendFunc) {
  103438. 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) {
  103439. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  103440. }
  103441. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103442. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  103443. }
  103444. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103445. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  103446. }
  103447. 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) {
  103448. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  103449. }
  103450. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  103451. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  103452. }
  103453. 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) {
  103454. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  103455. }
  103456. }
  103457. }
  103458. };
  103459. return GLTFLoaderBase;
  103460. }());
  103461. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  103462. /**
  103463. * glTF V1 Loader
  103464. */
  103465. var GLTFLoader = /** @class */ (function () {
  103466. function GLTFLoader() {
  103467. // #region Stubs for IGLTFLoader interface
  103468. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  103469. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  103470. this.compileMaterials = false;
  103471. this.useClipPlane = false;
  103472. this.compileShadowGenerators = false;
  103473. this.transparencyAsCoverage = false;
  103474. this._normalizeAnimationGroupsToBeginAtZero = true;
  103475. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  103476. this.onMeshLoadedObservable = new BABYLON.Observable();
  103477. this.onTextureLoadedObservable = new BABYLON.Observable();
  103478. this.onMaterialLoadedObservable = new BABYLON.Observable();
  103479. this.onCameraLoadedObservable = new BABYLON.Observable();
  103480. this.onCompleteObservable = new BABYLON.Observable();
  103481. this.onDisposeObservable = new BABYLON.Observable();
  103482. this.onExtensionLoadedObservable = new BABYLON.Observable();
  103483. this.state = null;
  103484. }
  103485. GLTFLoader.RegisterExtension = function (extension) {
  103486. if (GLTFLoader.Extensions[extension.name]) {
  103487. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  103488. return;
  103489. }
  103490. GLTFLoader.Extensions[extension.name] = extension;
  103491. };
  103492. GLTFLoader.prototype.dispose = function () { };
  103493. // #endregion
  103494. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  103495. var _this = this;
  103496. scene.useRightHandedSystem = true;
  103497. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103498. gltfRuntime.importOnlyMeshes = true;
  103499. if (meshesNames === "") {
  103500. gltfRuntime.importMeshesNames = [];
  103501. }
  103502. else if (typeof meshesNames === "string") {
  103503. gltfRuntime.importMeshesNames = [meshesNames];
  103504. }
  103505. else if (meshesNames && !(meshesNames instanceof Array)) {
  103506. gltfRuntime.importMeshesNames = [meshesNames];
  103507. }
  103508. else {
  103509. gltfRuntime.importMeshesNames = [];
  103510. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  103511. }
  103512. // Create nodes
  103513. _this._createNodes(gltfRuntime);
  103514. var meshes = new Array();
  103515. var skeletons = new Array();
  103516. // Fill arrays of meshes and skeletons
  103517. for (var nde in gltfRuntime.nodes) {
  103518. var node = gltfRuntime.nodes[nde];
  103519. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  103520. meshes.push(node.babylonNode);
  103521. }
  103522. }
  103523. for (var skl in gltfRuntime.skins) {
  103524. var skin = gltfRuntime.skins[skl];
  103525. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  103526. skeletons.push(skin.babylonSkeleton);
  103527. }
  103528. }
  103529. // Load buffers, shaders, materials, etc.
  103530. _this._loadBuffersAsync(gltfRuntime, function () {
  103531. _this._loadShadersAsync(gltfRuntime, function () {
  103532. importMaterials(gltfRuntime);
  103533. postLoad(gltfRuntime);
  103534. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103535. onSuccess(meshes, skeletons);
  103536. }
  103537. });
  103538. }, onProgress);
  103539. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  103540. onSuccess(meshes, skeletons);
  103541. }
  103542. }, onError);
  103543. return true;
  103544. };
  103545. /**
  103546. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  103547. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  103548. * @param scene the scene the meshes should be added to
  103549. * @param data gltf data containing information of the meshes in a loaded file
  103550. * @param rootUrl root url to load from
  103551. * @param onProgress event that fires when loading progress has occured
  103552. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  103553. */
  103554. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  103555. var _this = this;
  103556. return new Promise(function (resolve, reject) {
  103557. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  103558. resolve({
  103559. meshes: meshes,
  103560. particleSystems: [],
  103561. skeletons: skeletons,
  103562. animationGroups: []
  103563. });
  103564. }, onProgress, function (message) {
  103565. reject(new Error(message));
  103566. });
  103567. });
  103568. };
  103569. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  103570. var _this = this;
  103571. scene.useRightHandedSystem = true;
  103572. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  103573. // Load runtime extensios
  103574. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  103575. // Create nodes
  103576. _this._createNodes(gltfRuntime);
  103577. // Load buffers, shaders, materials, etc.
  103578. _this._loadBuffersAsync(gltfRuntime, function () {
  103579. _this._loadShadersAsync(gltfRuntime, function () {
  103580. importMaterials(gltfRuntime);
  103581. postLoad(gltfRuntime);
  103582. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  103583. onSuccess();
  103584. }
  103585. });
  103586. });
  103587. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  103588. onSuccess();
  103589. }
  103590. }, onError);
  103591. }, onError);
  103592. };
  103593. /**
  103594. * Imports all objects from a loaded gltf file and adds them to the scene
  103595. * @param scene the scene the objects should be added to
  103596. * @param data gltf data containing information of the meshes in a loaded file
  103597. * @param rootUrl root url to load from
  103598. * @param onProgress event that fires when loading progress has occured
  103599. * @returns a promise which completes when objects have been loaded to the scene
  103600. */
  103601. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  103602. var _this = this;
  103603. return new Promise(function (resolve, reject) {
  103604. _this._loadAsync(scene, data, rootUrl, function () {
  103605. resolve();
  103606. }, onProgress, function (message) {
  103607. reject(new Error(message));
  103608. });
  103609. });
  103610. };
  103611. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  103612. var hasShaders = false;
  103613. var processShader = function (sha, shader) {
  103614. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  103615. if (shaderString instanceof ArrayBuffer) {
  103616. return;
  103617. }
  103618. gltfRuntime.loadedShaderCount++;
  103619. if (shaderString) {
  103620. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  103621. }
  103622. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  103623. onload();
  103624. }
  103625. }, function () {
  103626. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  103627. });
  103628. };
  103629. for (var sha in gltfRuntime.shaders) {
  103630. hasShaders = true;
  103631. var shader = gltfRuntime.shaders[sha];
  103632. if (shader) {
  103633. processShader.bind(this, sha, shader)();
  103634. }
  103635. else {
  103636. BABYLON.Tools.Error("No shader named: " + sha);
  103637. }
  103638. }
  103639. if (!hasShaders) {
  103640. onload();
  103641. }
  103642. };
  103643. ;
  103644. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  103645. var hasBuffers = false;
  103646. var processBuffer = function (buf, buffer) {
  103647. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  103648. gltfRuntime.loadedBufferCount++;
  103649. if (bufferView) {
  103650. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  103651. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  103652. }
  103653. gltfRuntime.loadedBufferViews[buf] = bufferView;
  103654. }
  103655. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  103656. onLoad();
  103657. }
  103658. }, function () {
  103659. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  103660. });
  103661. };
  103662. for (var buf in gltfRuntime.buffers) {
  103663. hasBuffers = true;
  103664. var buffer = gltfRuntime.buffers[buf];
  103665. if (buffer) {
  103666. processBuffer.bind(this, buf, buffer)();
  103667. }
  103668. else {
  103669. BABYLON.Tools.Error("No buffer named: " + buf);
  103670. }
  103671. }
  103672. if (!hasBuffers) {
  103673. onLoad();
  103674. }
  103675. };
  103676. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  103677. var currentScene = gltfRuntime.currentScene;
  103678. if (currentScene) {
  103679. // Only one scene even if multiple scenes are defined
  103680. for (var i = 0; i < currentScene.nodes.length; i++) {
  103681. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103682. }
  103683. }
  103684. else {
  103685. // Load all scenes
  103686. for (var thing in gltfRuntime.scenes) {
  103687. currentScene = gltfRuntime.scenes[thing];
  103688. for (var i = 0; i < currentScene.nodes.length; i++) {
  103689. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  103690. }
  103691. }
  103692. }
  103693. };
  103694. GLTFLoader.Extensions = {};
  103695. return GLTFLoader;
  103696. }());
  103697. GLTF1.GLTFLoader = GLTFLoader;
  103698. ;
  103699. BABYLON.GLTFFileLoader.CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  103700. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103701. })(BABYLON || (BABYLON = {}));
  103702. //# sourceMappingURL=babylon.glTFLoader.js.map
  103703. var BABYLON;
  103704. (function (BABYLON) {
  103705. var GLTF1;
  103706. (function (GLTF1) {
  103707. /**
  103708. * Utils functions for GLTF
  103709. */
  103710. var GLTFUtils = /** @class */ (function () {
  103711. function GLTFUtils() {
  103712. }
  103713. /**
  103714. * Sets the given "parameter" matrix
  103715. * @param scene: the {BABYLON.Scene} object
  103716. * @param source: the source node where to pick the matrix
  103717. * @param parameter: the GLTF technique parameter
  103718. * @param uniformName: the name of the shader's uniform
  103719. * @param shaderMaterial: the shader material
  103720. */
  103721. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  103722. var mat = null;
  103723. if (parameter.semantic === "MODEL") {
  103724. mat = source.getWorldMatrix();
  103725. }
  103726. else if (parameter.semantic === "PROJECTION") {
  103727. mat = scene.getProjectionMatrix();
  103728. }
  103729. else if (parameter.semantic === "VIEW") {
  103730. mat = scene.getViewMatrix();
  103731. }
  103732. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  103733. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  103734. }
  103735. else if (parameter.semantic === "MODELVIEW") {
  103736. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  103737. }
  103738. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  103739. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  103740. }
  103741. else if (parameter.semantic === "MODELINVERSE") {
  103742. mat = source.getWorldMatrix().invert();
  103743. }
  103744. else if (parameter.semantic === "VIEWINVERSE") {
  103745. mat = scene.getViewMatrix().invert();
  103746. }
  103747. else if (parameter.semantic === "PROJECTIONINVERSE") {
  103748. mat = scene.getProjectionMatrix().invert();
  103749. }
  103750. else if (parameter.semantic === "MODELVIEWINVERSE") {
  103751. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  103752. }
  103753. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  103754. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  103755. }
  103756. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  103757. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  103758. }
  103759. else {
  103760. debugger;
  103761. }
  103762. if (mat) {
  103763. switch (parameter.type) {
  103764. case GLTF1.EParameterType.FLOAT_MAT2:
  103765. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  103766. break;
  103767. case GLTF1.EParameterType.FLOAT_MAT3:
  103768. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  103769. break;
  103770. case GLTF1.EParameterType.FLOAT_MAT4:
  103771. shaderMaterial.setMatrix(uniformName, mat);
  103772. break;
  103773. default: break;
  103774. }
  103775. }
  103776. };
  103777. /**
  103778. * Sets the given "parameter" matrix
  103779. * @param shaderMaterial: the shader material
  103780. * @param uniform: the name of the shader's uniform
  103781. * @param value: the value of the uniform
  103782. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  103783. */
  103784. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  103785. switch (type) {
  103786. case GLTF1.EParameterType.FLOAT:
  103787. shaderMaterial.setFloat(uniform, value);
  103788. return true;
  103789. case GLTF1.EParameterType.FLOAT_VEC2:
  103790. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  103791. return true;
  103792. case GLTF1.EParameterType.FLOAT_VEC3:
  103793. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  103794. return true;
  103795. case GLTF1.EParameterType.FLOAT_VEC4:
  103796. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  103797. return true;
  103798. default: return false;
  103799. }
  103800. };
  103801. /**
  103802. * Returns the wrap mode of the texture
  103803. * @param mode: the mode value
  103804. */
  103805. GLTFUtils.GetWrapMode = function (mode) {
  103806. switch (mode) {
  103807. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  103808. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  103809. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103810. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  103811. }
  103812. };
  103813. /**
  103814. * Returns the byte stride giving an accessor
  103815. * @param accessor: the GLTF accessor objet
  103816. */
  103817. GLTFUtils.GetByteStrideFromType = function (accessor) {
  103818. // Needs this function since "byteStride" isn't requiered in glTF format
  103819. var type = accessor.type;
  103820. switch (type) {
  103821. case "VEC2": return 2;
  103822. case "VEC3": return 3;
  103823. case "VEC4": return 4;
  103824. case "MAT2": return 4;
  103825. case "MAT3": return 9;
  103826. case "MAT4": return 16;
  103827. default: return 1;
  103828. }
  103829. };
  103830. /**
  103831. * Returns the texture filter mode giving a mode value
  103832. * @param mode: the filter mode value
  103833. */
  103834. GLTFUtils.GetTextureFilterMode = function (mode) {
  103835. switch (mode) {
  103836. case GLTF1.ETextureFilterType.LINEAR:
  103837. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  103838. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  103839. case GLTF1.ETextureFilterType.NEAREST:
  103840. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  103841. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  103842. }
  103843. };
  103844. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  103845. var byteOffset = bufferView.byteOffset + byteOffset;
  103846. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  103847. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  103848. throw new Error("Buffer access is out of range");
  103849. }
  103850. var buffer = loadedBufferView.buffer;
  103851. byteOffset += loadedBufferView.byteOffset;
  103852. switch (componentType) {
  103853. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  103854. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  103855. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  103856. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  103857. default: return new Float32Array(buffer, byteOffset, byteLength);
  103858. }
  103859. };
  103860. /**
  103861. * Returns a buffer from its accessor
  103862. * @param gltfRuntime: the GLTF runtime
  103863. * @param accessor: the GLTF accessor
  103864. */
  103865. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  103866. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  103867. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  103868. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  103869. };
  103870. /**
  103871. * Decodes a buffer view into a string
  103872. * @param view: the buffer view
  103873. */
  103874. GLTFUtils.DecodeBufferToText = function (view) {
  103875. var result = "";
  103876. var length = view.byteLength;
  103877. for (var i = 0; i < length; ++i) {
  103878. result += String.fromCharCode(view[i]);
  103879. }
  103880. return result;
  103881. };
  103882. /**
  103883. * Returns the default material of gltf. Related to
  103884. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  103885. * @param scene: the Babylon.js scene
  103886. */
  103887. GLTFUtils.GetDefaultMaterial = function (scene) {
  103888. if (!GLTFUtils._DefaultMaterial) {
  103889. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  103890. "precision highp float;",
  103891. "",
  103892. "uniform mat4 worldView;",
  103893. "uniform mat4 projection;",
  103894. "",
  103895. "attribute vec3 position;",
  103896. "",
  103897. "void main(void)",
  103898. "{",
  103899. " gl_Position = projection * worldView * vec4(position, 1.0);",
  103900. "}"
  103901. ].join("\n");
  103902. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  103903. "precision highp float;",
  103904. "",
  103905. "uniform vec4 u_emission;",
  103906. "",
  103907. "void main(void)",
  103908. "{",
  103909. " gl_FragColor = u_emission;",
  103910. "}"
  103911. ].join("\n");
  103912. var shaderPath = {
  103913. vertex: "GLTFDefaultMaterial",
  103914. fragment: "GLTFDefaultMaterial"
  103915. };
  103916. var options = {
  103917. attributes: ["position"],
  103918. uniforms: ["worldView", "projection", "u_emission"],
  103919. samplers: new Array(),
  103920. needAlphaBlending: false
  103921. };
  103922. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  103923. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  103924. }
  103925. return GLTFUtils._DefaultMaterial;
  103926. };
  103927. // The GLTF default material
  103928. GLTFUtils._DefaultMaterial = null;
  103929. return GLTFUtils;
  103930. }());
  103931. GLTF1.GLTFUtils = GLTFUtils;
  103932. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  103933. })(BABYLON || (BABYLON = {}));
  103934. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  103935. var BABYLON;
  103936. (function (BABYLON) {
  103937. var GLTF1;
  103938. (function (GLTF1) {
  103939. var GLTFLoaderExtension = /** @class */ (function () {
  103940. function GLTFLoaderExtension(name) {
  103941. this._name = name;
  103942. }
  103943. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  103944. get: function () {
  103945. return this._name;
  103946. },
  103947. enumerable: true,
  103948. configurable: true
  103949. });
  103950. /**
  103951. * Defines an override for loading the runtime
  103952. * Return true to stop further extensions from loading the runtime
  103953. */
  103954. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  103955. return false;
  103956. };
  103957. /**
  103958. * Defines an onverride for creating gltf runtime
  103959. * Return true to stop further extensions from creating the runtime
  103960. */
  103961. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  103962. return false;
  103963. };
  103964. /**
  103965. * Defines an override for loading buffers
  103966. * Return true to stop further extensions from loading this buffer
  103967. */
  103968. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  103969. return false;
  103970. };
  103971. /**
  103972. * Defines an override for loading texture buffers
  103973. * Return true to stop further extensions from loading this texture data
  103974. */
  103975. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  103976. return false;
  103977. };
  103978. /**
  103979. * Defines an override for creating textures
  103980. * Return true to stop further extensions from loading this texture
  103981. */
  103982. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  103983. return false;
  103984. };
  103985. /**
  103986. * Defines an override for loading shader strings
  103987. * Return true to stop further extensions from loading this shader data
  103988. */
  103989. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  103990. return false;
  103991. };
  103992. /**
  103993. * Defines an override for loading materials
  103994. * Return true to stop further extensions from loading this material
  103995. */
  103996. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  103997. return false;
  103998. };
  103999. // ---------
  104000. // Utilities
  104001. // ---------
  104002. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104003. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104004. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  104005. }, function () {
  104006. setTimeout(function () {
  104007. if (!onSuccess) {
  104008. return;
  104009. }
  104010. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104011. });
  104012. });
  104013. };
  104014. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104015. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104016. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  104017. }, function () {
  104018. setTimeout(function () {
  104019. onSuccess();
  104020. });
  104021. });
  104022. };
  104023. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  104024. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104025. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104026. }, function () {
  104027. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  104028. });
  104029. };
  104030. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  104031. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104032. if (buffer) {
  104033. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104034. }
  104035. }, onError);
  104036. };
  104037. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104038. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104039. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104040. }, function () {
  104041. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  104042. });
  104043. };
  104044. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104045. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104046. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104047. }, function () {
  104048. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  104049. });
  104050. };
  104051. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104052. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104053. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104054. }, function () {
  104055. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  104056. });
  104057. };
  104058. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  104059. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  104060. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104061. }, function () {
  104062. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  104063. });
  104064. };
  104065. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  104066. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  104067. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  104068. if (func(loaderExtension)) {
  104069. return;
  104070. }
  104071. }
  104072. defaultFunc();
  104073. };
  104074. return GLTFLoaderExtension;
  104075. }());
  104076. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  104077. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104078. })(BABYLON || (BABYLON = {}));
  104079. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  104080. var BABYLON;
  104081. (function (BABYLON) {
  104082. var GLTF1;
  104083. (function (GLTF1) {
  104084. var BinaryExtensionBufferName = "binary_glTF";
  104085. ;
  104086. ;
  104087. var GLTFBinaryExtension = /** @class */ (function (_super) {
  104088. __extends(GLTFBinaryExtension, _super);
  104089. function GLTFBinaryExtension() {
  104090. return _super.call(this, "KHR_binary_glTF") || this;
  104091. }
  104092. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  104093. var extensionsUsed = data.json.extensionsUsed;
  104094. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  104095. return false;
  104096. }
  104097. this._bin = data.bin;
  104098. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  104099. return true;
  104100. };
  104101. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104102. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  104103. return false;
  104104. }
  104105. if (id !== BinaryExtensionBufferName) {
  104106. return false;
  104107. }
  104108. onSuccess(this._bin);
  104109. return true;
  104110. };
  104111. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  104112. var texture = gltfRuntime.textures[id];
  104113. var source = gltfRuntime.images[texture.source];
  104114. if (!source.extensions || !(this.name in source.extensions)) {
  104115. return false;
  104116. }
  104117. var sourceExt = source.extensions[this.name];
  104118. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  104119. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104120. onSuccess(buffer);
  104121. return true;
  104122. };
  104123. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  104124. var shader = gltfRuntime.shaders[id];
  104125. if (!shader.extensions || !(this.name in shader.extensions)) {
  104126. return false;
  104127. }
  104128. var binaryExtensionShader = shader.extensions[this.name];
  104129. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  104130. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  104131. setTimeout(function () {
  104132. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  104133. onSuccess(shaderString);
  104134. });
  104135. return true;
  104136. };
  104137. return GLTFBinaryExtension;
  104138. }(GLTF1.GLTFLoaderExtension));
  104139. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  104140. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  104141. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104142. })(BABYLON || (BABYLON = {}));
  104143. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  104144. var BABYLON;
  104145. (function (BABYLON) {
  104146. var GLTF1;
  104147. (function (GLTF1) {
  104148. ;
  104149. ;
  104150. ;
  104151. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  104152. __extends(GLTFMaterialsCommonExtension, _super);
  104153. function GLTFMaterialsCommonExtension() {
  104154. return _super.call(this, "KHR_materials_common") || this;
  104155. }
  104156. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  104157. if (!gltfRuntime.extensions)
  104158. return false;
  104159. var extension = gltfRuntime.extensions[this.name];
  104160. if (!extension)
  104161. return false;
  104162. // Create lights
  104163. var lights = extension.lights;
  104164. if (lights) {
  104165. for (var thing in lights) {
  104166. var light = lights[thing];
  104167. switch (light.type) {
  104168. case "ambient":
  104169. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  104170. var ambient = light.ambient;
  104171. if (ambient) {
  104172. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  104173. }
  104174. break;
  104175. case "point":
  104176. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  104177. var point = light.point;
  104178. if (point) {
  104179. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  104180. }
  104181. break;
  104182. case "directional":
  104183. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  104184. var directional = light.directional;
  104185. if (directional) {
  104186. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  104187. }
  104188. break;
  104189. case "spot":
  104190. var spot = light.spot;
  104191. if (spot) {
  104192. 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);
  104193. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  104194. }
  104195. break;
  104196. default:
  104197. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  104198. break;
  104199. }
  104200. }
  104201. }
  104202. return false;
  104203. };
  104204. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  104205. var material = gltfRuntime.materials[id];
  104206. if (!material || !material.extensions)
  104207. return false;
  104208. var extension = material.extensions[this.name];
  104209. if (!extension)
  104210. return false;
  104211. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  104212. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  104213. if (extension.technique === "CONSTANT") {
  104214. standardMaterial.disableLighting = true;
  104215. }
  104216. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  104217. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  104218. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  104219. // Ambient
  104220. if (typeof extension.values.ambient === "string") {
  104221. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  104222. }
  104223. else {
  104224. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  104225. }
  104226. // Diffuse
  104227. if (typeof extension.values.diffuse === "string") {
  104228. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  104229. }
  104230. else {
  104231. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  104232. }
  104233. // Emission
  104234. if (typeof extension.values.emission === "string") {
  104235. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  104236. }
  104237. else {
  104238. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  104239. }
  104240. // Specular
  104241. if (typeof extension.values.specular === "string") {
  104242. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  104243. }
  104244. else {
  104245. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  104246. }
  104247. return true;
  104248. };
  104249. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  104250. // Create buffer from texture url
  104251. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  104252. // Create texture from buffer
  104253. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  104254. }, onError);
  104255. };
  104256. return GLTFMaterialsCommonExtension;
  104257. }(GLTF1.GLTFLoaderExtension));
  104258. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  104259. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  104260. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  104261. })(BABYLON || (BABYLON = {}));
  104262. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  104263. var BABYLON;
  104264. (function (BABYLON) {
  104265. var GLTF2;
  104266. (function (GLTF2) {
  104267. /** @hidden */
  104268. var _ArrayItem = /** @class */ (function () {
  104269. function _ArrayItem() {
  104270. }
  104271. /** @hidden */
  104272. _ArrayItem.Assign = function (values) {
  104273. if (values) {
  104274. for (var index = 0; index < values.length; index++) {
  104275. values[index]._index = index;
  104276. }
  104277. }
  104278. };
  104279. return _ArrayItem;
  104280. }());
  104281. GLTF2._ArrayItem = _ArrayItem;
  104282. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  104283. })(BABYLON || (BABYLON = {}));
  104284. //# sourceMappingURL=babylon.glTFLoaderUtilities.js.map
  104285. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  104286. /**
  104287. * Defines the module used to import/export glTF 2.0 assets
  104288. */
  104289. var BABYLON;
  104290. (function (BABYLON) {
  104291. var GLTF2;
  104292. (function (GLTF2) {
  104293. /**
  104294. * Loader for loading a glTF 2.0 asset
  104295. */
  104296. var GLTFLoader = /** @class */ (function () {
  104297. function GLTFLoader() {
  104298. /** @hidden */
  104299. this._completePromises = new Array();
  104300. this._disposed = false;
  104301. this._state = null;
  104302. this._extensions = {};
  104303. this._defaultSampler = {};
  104304. this._defaultBabylonMaterials = {};
  104305. this._requests = new Array();
  104306. /**
  104307. * Mode that determines the coordinate system to use.
  104308. */
  104309. this.coordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode.AUTO;
  104310. /**
  104311. * Mode that determines what animations will start.
  104312. */
  104313. this.animationStartMode = BABYLON.GLTFLoaderAnimationStartMode.FIRST;
  104314. /**
  104315. * Defines if the loader should compile materials.
  104316. */
  104317. this.compileMaterials = false;
  104318. /**
  104319. * Defines if the loader should also compile materials with clip planes.
  104320. */
  104321. this.useClipPlane = false;
  104322. /**
  104323. * Defines if the loader should compile shadow generators.
  104324. */
  104325. this.compileShadowGenerators = false;
  104326. /**
  104327. * Defines if the Alpha blended materials are only applied as coverage.
  104328. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  104329. * If true, no extra effects are applied to transparent pixels.
  104330. */
  104331. this.transparencyAsCoverage = false;
  104332. /** @hidden */
  104333. this._normalizeAnimationGroupsToBeginAtZero = true;
  104334. /**
  104335. * Function called before loading a url referenced by the asset.
  104336. */
  104337. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  104338. /**
  104339. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  104340. */
  104341. this.onMeshLoadedObservable = new BABYLON.Observable();
  104342. /**
  104343. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  104344. */
  104345. this.onTextureLoadedObservable = new BABYLON.Observable();
  104346. /**
  104347. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  104348. */
  104349. this.onMaterialLoadedObservable = new BABYLON.Observable();
  104350. /**
  104351. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  104352. */
  104353. this.onCameraLoadedObservable = new BABYLON.Observable();
  104354. /**
  104355. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  104356. * For assets with LODs, raised when all of the LODs are complete.
  104357. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  104358. */
  104359. this.onCompleteObservable = new BABYLON.Observable();
  104360. /**
  104361. * Observable raised after the loader is disposed.
  104362. */
  104363. this.onDisposeObservable = new BABYLON.Observable();
  104364. /**
  104365. * Observable raised after a loader extension is created.
  104366. * Set additional options for a loader extension in this event.
  104367. */
  104368. this.onExtensionLoadedObservable = new BABYLON.Observable();
  104369. }
  104370. /** @hidden */
  104371. GLTFLoader._Register = function (name, factory) {
  104372. if (GLTFLoader._ExtensionFactories[name]) {
  104373. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  104374. return;
  104375. }
  104376. GLTFLoader._ExtensionFactories[name] = factory;
  104377. // Keep the order of registration so that extensions registered first are called first.
  104378. GLTFLoader._ExtensionNames.push(name);
  104379. };
  104380. Object.defineProperty(GLTFLoader.prototype, "state", {
  104381. /**
  104382. * Loader state or null if the loader is not active.
  104383. */
  104384. get: function () {
  104385. return this._state;
  104386. },
  104387. enumerable: true,
  104388. configurable: true
  104389. });
  104390. /**
  104391. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  104392. */
  104393. GLTFLoader.prototype.dispose = function () {
  104394. if (this._disposed) {
  104395. return;
  104396. }
  104397. this._disposed = true;
  104398. this.onDisposeObservable.notifyObservers(this);
  104399. this.onDisposeObservable.clear();
  104400. this._clear();
  104401. };
  104402. /**
  104403. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  104404. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  104405. * @param scene the scene the meshes should be added to
  104406. * @param data the glTF data to load
  104407. * @param rootUrl root url to load from
  104408. * @param onProgress event that fires when loading progress has occured
  104409. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  104410. */
  104411. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  104412. var _this = this;
  104413. return Promise.resolve().then(function () {
  104414. var nodes = null;
  104415. if (meshesNames) {
  104416. var nodeMap_1 = {};
  104417. if (_this._gltf.nodes) {
  104418. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  104419. var node = _a[_i];
  104420. if (node.name) {
  104421. nodeMap_1[node.name] = node;
  104422. }
  104423. }
  104424. }
  104425. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  104426. nodes = names.map(function (name) {
  104427. var node = nodeMap_1[name];
  104428. if (!node) {
  104429. throw new Error("Failed to find node '" + name + "'");
  104430. }
  104431. return node;
  104432. });
  104433. }
  104434. return _this._loadAsync(nodes, scene, data, rootUrl, onProgress).then(function () {
  104435. return {
  104436. meshes: _this._getMeshes(),
  104437. particleSystems: [],
  104438. skeletons: _this._getSkeletons(),
  104439. animationGroups: _this._getAnimationGroups()
  104440. };
  104441. });
  104442. });
  104443. };
  104444. /**
  104445. * Imports all objects from the loaded glTF data and adds them to the scene
  104446. * @param scene the scene the objects should be added to
  104447. * @param data the glTF data to load
  104448. * @param rootUrl root url to load from
  104449. * @param onProgress event that fires when loading progress has occured
  104450. * @returns a promise which completes when objects have been loaded to the scene
  104451. */
  104452. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  104453. return this._loadAsync(null, scene, data, rootUrl, onProgress);
  104454. };
  104455. GLTFLoader.prototype._loadAsync = function (nodes, scene, data, rootUrl, onProgress) {
  104456. var _this = this;
  104457. return Promise.resolve().then(function () {
  104458. _this._babylonScene = scene;
  104459. _this._rootUrl = rootUrl;
  104460. _this._progressCallback = onProgress;
  104461. _this._state = BABYLON.GLTFLoaderState.LOADING;
  104462. _this._loadData(data);
  104463. _this._loadExtensions();
  104464. _this._checkExtensions();
  104465. var promises = new Array();
  104466. if (nodes) {
  104467. promises.push(_this._loadNodesAsync(nodes));
  104468. }
  104469. else {
  104470. var scene_1 = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  104471. promises.push(_this._loadSceneAsync("#/scenes/" + scene_1._index, scene_1));
  104472. }
  104473. if (_this.compileMaterials) {
  104474. promises.push(_this._compileMaterialsAsync());
  104475. }
  104476. if (_this.compileShadowGenerators) {
  104477. promises.push(_this._compileShadowGeneratorsAsync());
  104478. }
  104479. var resultPromise = Promise.all(promises).then(function () {
  104480. _this._state = BABYLON.GLTFLoaderState.READY;
  104481. _this._startAnimations();
  104482. });
  104483. resultPromise.then(function () {
  104484. _this._rootBabylonMesh.setEnabled(true);
  104485. BABYLON.Tools.SetImmediate(function () {
  104486. if (!_this._disposed) {
  104487. Promise.all(_this._completePromises).then(function () {
  104488. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  104489. _this.onCompleteObservable.notifyObservers(_this);
  104490. _this.onCompleteObservable.clear();
  104491. _this._clear();
  104492. }).catch(function (error) {
  104493. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104494. _this._clear();
  104495. });
  104496. }
  104497. });
  104498. });
  104499. return resultPromise;
  104500. }).catch(function (error) {
  104501. if (!_this._disposed) {
  104502. BABYLON.Tools.Error("glTF Loader: " + error.message);
  104503. _this._clear();
  104504. throw error;
  104505. }
  104506. });
  104507. };
  104508. GLTFLoader.prototype._loadData = function (data) {
  104509. this._gltf = data.json;
  104510. this._setupData();
  104511. if (data.bin) {
  104512. var buffers = this._gltf.buffers;
  104513. if (buffers && buffers[0] && !buffers[0].uri) {
  104514. var binaryBuffer = buffers[0];
  104515. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  104516. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  104517. }
  104518. binaryBuffer._data = Promise.resolve(data.bin);
  104519. }
  104520. else {
  104521. BABYLON.Tools.Warn("Unexpected BIN chunk");
  104522. }
  104523. }
  104524. };
  104525. GLTFLoader.prototype._setupData = function () {
  104526. GLTF2._ArrayItem.Assign(this._gltf.accessors);
  104527. GLTF2._ArrayItem.Assign(this._gltf.animations);
  104528. GLTF2._ArrayItem.Assign(this._gltf.buffers);
  104529. GLTF2._ArrayItem.Assign(this._gltf.bufferViews);
  104530. GLTF2._ArrayItem.Assign(this._gltf.cameras);
  104531. GLTF2._ArrayItem.Assign(this._gltf.images);
  104532. GLTF2._ArrayItem.Assign(this._gltf.materials);
  104533. GLTF2._ArrayItem.Assign(this._gltf.meshes);
  104534. GLTF2._ArrayItem.Assign(this._gltf.nodes);
  104535. GLTF2._ArrayItem.Assign(this._gltf.samplers);
  104536. GLTF2._ArrayItem.Assign(this._gltf.scenes);
  104537. GLTF2._ArrayItem.Assign(this._gltf.skins);
  104538. GLTF2._ArrayItem.Assign(this._gltf.textures);
  104539. if (this._gltf.nodes) {
  104540. var nodeParents = {};
  104541. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  104542. var node = _a[_i];
  104543. if (node.children) {
  104544. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  104545. var index = _c[_b];
  104546. nodeParents[index] = node._index;
  104547. }
  104548. }
  104549. }
  104550. var rootNode = this._createRootNode();
  104551. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  104552. var node = _e[_d];
  104553. var parentIndex = nodeParents[node._index];
  104554. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  104555. }
  104556. }
  104557. };
  104558. GLTFLoader.prototype._loadExtensions = function () {
  104559. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  104560. var name_1 = _a[_i];
  104561. var extension = GLTFLoader._ExtensionFactories[name_1](this);
  104562. this._extensions[name_1] = extension;
  104563. this.onExtensionLoadedObservable.notifyObservers(extension);
  104564. }
  104565. this.onExtensionLoadedObservable.clear();
  104566. };
  104567. GLTFLoader.prototype._checkExtensions = function () {
  104568. if (this._gltf.extensionsRequired) {
  104569. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  104570. var name_2 = _a[_i];
  104571. var extension = this._extensions[name_2];
  104572. if (!extension || !extension.enabled) {
  104573. throw new Error("Require extension " + name_2 + " is not available");
  104574. }
  104575. }
  104576. }
  104577. };
  104578. GLTFLoader.prototype._createRootNode = function () {
  104579. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  104580. this._rootBabylonMesh.setEnabled(false);
  104581. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  104582. switch (this.coordinateSystemMode) {
  104583. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  104584. if (!this._babylonScene.useRightHandedSystem) {
  104585. rootNode.rotation = [0, 1, 0, 0];
  104586. rootNode.scale = [1, 1, -1];
  104587. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  104588. }
  104589. break;
  104590. }
  104591. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  104592. this._babylonScene.useRightHandedSystem = true;
  104593. break;
  104594. }
  104595. default: {
  104596. throw new Error("Invalid coordinate system mode (" + this.coordinateSystemMode + ")");
  104597. }
  104598. }
  104599. this.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  104600. return rootNode;
  104601. };
  104602. GLTFLoader.prototype._loadNodesAsync = function (nodes) {
  104603. var promises = new Array();
  104604. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  104605. var node = nodes_1[_i];
  104606. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104607. }
  104608. promises.push(this._loadAnimationsAsync());
  104609. return Promise.all(promises).then(function () { });
  104610. };
  104611. /** @hidden */
  104612. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  104613. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  104614. if (promise) {
  104615. return promise;
  104616. }
  104617. var promises = new Array();
  104618. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  104619. var index = _a[_i];
  104620. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  104621. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  104622. }
  104623. promises.push(this._loadAnimationsAsync());
  104624. return Promise.all(promises).then(function () { });
  104625. };
  104626. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  104627. if (node._primitiveBabylonMeshes) {
  104628. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  104629. var babylonMesh = _a[_i];
  104630. callback(babylonMesh);
  104631. }
  104632. }
  104633. else {
  104634. callback(node._babylonMesh);
  104635. }
  104636. };
  104637. GLTFLoader.prototype._getMeshes = function () {
  104638. var meshes = new Array();
  104639. // Root mesh is always first.
  104640. meshes.push(this._rootBabylonMesh);
  104641. var nodes = this._gltf.nodes;
  104642. if (nodes) {
  104643. for (var _i = 0, nodes_2 = nodes; _i < nodes_2.length; _i++) {
  104644. var node = nodes_2[_i];
  104645. if (node._babylonMesh) {
  104646. meshes.push(node._babylonMesh);
  104647. }
  104648. if (node._primitiveBabylonMeshes) {
  104649. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  104650. var babylonMesh = _b[_a];
  104651. meshes.push(babylonMesh);
  104652. }
  104653. }
  104654. }
  104655. }
  104656. return meshes;
  104657. };
  104658. GLTFLoader.prototype._getSkeletons = function () {
  104659. var skeletons = new Array();
  104660. var skins = this._gltf.skins;
  104661. if (skins) {
  104662. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  104663. var skin = skins_1[_i];
  104664. if (skin._babylonSkeleton) {
  104665. skeletons.push(skin._babylonSkeleton);
  104666. }
  104667. }
  104668. }
  104669. return skeletons;
  104670. };
  104671. GLTFLoader.prototype._getAnimationGroups = function () {
  104672. var animationGroups = new Array();
  104673. var animations = this._gltf.animations;
  104674. if (animations) {
  104675. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  104676. var animation = animations_1[_i];
  104677. if (animation._babylonAnimationGroup) {
  104678. animationGroups.push(animation._babylonAnimationGroup);
  104679. }
  104680. }
  104681. }
  104682. return animationGroups;
  104683. };
  104684. GLTFLoader.prototype._startAnimations = function () {
  104685. switch (this.animationStartMode) {
  104686. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  104687. // do nothing
  104688. break;
  104689. }
  104690. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  104691. var babylonAnimationGroups = this._getAnimationGroups();
  104692. if (babylonAnimationGroups.length !== 0) {
  104693. babylonAnimationGroups[0].start(true);
  104694. }
  104695. break;
  104696. }
  104697. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  104698. var babylonAnimationGroups = this._getAnimationGroups();
  104699. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  104700. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  104701. babylonAnimationGroup.start(true);
  104702. }
  104703. break;
  104704. }
  104705. default: {
  104706. BABYLON.Tools.Error("Invalid animation start mode (" + this.animationStartMode + ")");
  104707. return;
  104708. }
  104709. }
  104710. };
  104711. /** @hidden */
  104712. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  104713. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  104714. if (promise) {
  104715. return promise;
  104716. }
  104717. if (node._babylonMesh) {
  104718. throw new Error(context + ": Invalid recursive node hierarchy");
  104719. }
  104720. var promises = new Array();
  104721. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent._babylonMesh);
  104722. node._babylonMesh = babylonMesh;
  104723. GLTFLoader._LoadTransform(node, babylonMesh);
  104724. if (node.mesh != undefined) {
  104725. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  104726. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  104727. }
  104728. if (node.camera != undefined) {
  104729. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  104730. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  104731. }
  104732. if (node.children) {
  104733. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  104734. var index = _a[_i];
  104735. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  104736. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  104737. }
  104738. }
  104739. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104740. return Promise.all(promises).then(function () { });
  104741. };
  104742. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  104743. var _this = this;
  104744. var promises = new Array();
  104745. var primitives = mesh.primitives;
  104746. if (!primitives || primitives.length === 0) {
  104747. throw new Error(context + ": Primitives are missing");
  104748. }
  104749. GLTF2._ArrayItem.Assign(primitives);
  104750. if (primitives.length === 1) {
  104751. var primitive = primitives[0];
  104752. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  104753. }
  104754. else {
  104755. node._primitiveBabylonMeshes = [];
  104756. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  104757. var primitive = primitives_1[_i];
  104758. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  104759. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  104760. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  104761. this.onMeshLoadedObservable.notifyObservers(babylonMesh);
  104762. }
  104763. }
  104764. if (node.skin != undefined) {
  104765. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  104766. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  104767. }
  104768. return Promise.all(promises).then(function () {
  104769. _this._forEachPrimitive(node, function (babylonMesh) {
  104770. babylonMesh._refreshBoundingInfo(true);
  104771. });
  104772. });
  104773. };
  104774. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  104775. var _this = this;
  104776. var promises = new Array();
  104777. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  104778. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  104779. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  104780. babylonGeometry.applyToMesh(babylonMesh);
  104781. });
  104782. }));
  104783. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  104784. if (primitive.material == undefined) {
  104785. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  104786. }
  104787. else {
  104788. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  104789. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  104790. babylonMesh.material = babylonMaterial;
  104791. }));
  104792. }
  104793. return Promise.all(promises).then(function () { });
  104794. };
  104795. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  104796. var _this = this;
  104797. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  104798. if (promise) {
  104799. return promise;
  104800. }
  104801. var attributes = primitive.attributes;
  104802. if (!attributes) {
  104803. throw new Error(context + ": Attributes are missing");
  104804. }
  104805. var promises = new Array();
  104806. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  104807. if (primitive.indices == undefined) {
  104808. babylonMesh.isUnIndexed = true;
  104809. }
  104810. else {
  104811. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  104812. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104813. babylonGeometry.setIndices(data);
  104814. }));
  104815. }
  104816. var loadAttribute = function (attribute, kind, callback) {
  104817. if (attributes[attribute] == undefined) {
  104818. return;
  104819. }
  104820. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  104821. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  104822. babylonMesh._delayInfo.push(kind);
  104823. }
  104824. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104825. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  104826. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  104827. }));
  104828. if (callback) {
  104829. callback(accessor);
  104830. }
  104831. };
  104832. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  104833. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  104834. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  104835. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  104836. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  104837. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  104838. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  104839. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  104840. if (accessor.type === "VEC4" /* VEC4 */) {
  104841. babylonMesh.hasVertexAlpha = true;
  104842. }
  104843. });
  104844. return Promise.all(promises).then(function () {
  104845. return babylonGeometry;
  104846. });
  104847. };
  104848. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  104849. if (!primitive.targets) {
  104850. return;
  104851. }
  104852. if (node._numMorphTargets == undefined) {
  104853. node._numMorphTargets = primitive.targets.length;
  104854. }
  104855. else if (primitive.targets.length !== node._numMorphTargets) {
  104856. throw new Error(context + ": Primitives do not have the same number of targets");
  104857. }
  104858. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  104859. for (var index = 0; index < primitive.targets.length; index++) {
  104860. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  104861. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  104862. // TODO: tell the target whether it has positions, normals, tangents
  104863. }
  104864. };
  104865. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  104866. if (!primitive.targets) {
  104867. return Promise.resolve();
  104868. }
  104869. var promises = new Array();
  104870. var morphTargetManager = babylonMesh.morphTargetManager;
  104871. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  104872. var babylonMorphTarget = morphTargetManager.getTarget(index);
  104873. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  104874. }
  104875. return Promise.all(promises).then(function () { });
  104876. };
  104877. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  104878. var _this = this;
  104879. var promises = new Array();
  104880. var loadAttribute = function (attribute, kind, setData) {
  104881. if (attributes[attribute] == undefined) {
  104882. return;
  104883. }
  104884. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  104885. if (!babylonVertexBuffer) {
  104886. return;
  104887. }
  104888. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  104889. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  104890. setData(babylonVertexBuffer, data);
  104891. }));
  104892. };
  104893. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  104894. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104895. data[index] += value;
  104896. });
  104897. babylonMorphTarget.setPositions(data);
  104898. });
  104899. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  104900. babylonVertexBuffer.forEach(data.length, function (value, index) {
  104901. data[index] += value;
  104902. });
  104903. babylonMorphTarget.setNormals(data);
  104904. });
  104905. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  104906. var dataIndex = 0;
  104907. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  104908. // Tangent data for morph targets is stored as xyz delta.
  104909. // The vertexData.tangent is stored as xyzw.
  104910. // So we need to skip every fourth vertexData.tangent.
  104911. if (((index + 1) % 4) !== 0) {
  104912. data[dataIndex++] += value;
  104913. }
  104914. });
  104915. babylonMorphTarget.setTangents(data);
  104916. });
  104917. return Promise.all(promises).then(function () { });
  104918. };
  104919. GLTFLoader._LoadTransform = function (node, babylonNode) {
  104920. var position = BABYLON.Vector3.Zero();
  104921. var rotation = BABYLON.Quaternion.Identity();
  104922. var scaling = BABYLON.Vector3.One();
  104923. if (node.matrix) {
  104924. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  104925. matrix.decompose(scaling, rotation, position);
  104926. }
  104927. else {
  104928. if (node.translation)
  104929. position = BABYLON.Vector3.FromArray(node.translation);
  104930. if (node.rotation)
  104931. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  104932. if (node.scale)
  104933. scaling = BABYLON.Vector3.FromArray(node.scale);
  104934. }
  104935. babylonNode.position = position;
  104936. babylonNode.rotationQuaternion = rotation;
  104937. babylonNode.scaling = scaling;
  104938. };
  104939. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  104940. var _this = this;
  104941. var assignSkeleton = function (skeleton) {
  104942. _this._forEachPrimitive(node, function (babylonMesh) {
  104943. babylonMesh.skeleton = skeleton;
  104944. });
  104945. // Ignore the TRS of skinned nodes.
  104946. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  104947. node._babylonMesh.parent = _this._rootBabylonMesh;
  104948. node._babylonMesh.position = BABYLON.Vector3.Zero();
  104949. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  104950. node._babylonMesh.scaling = BABYLON.Vector3.One();
  104951. };
  104952. if (skin._loaded) {
  104953. return skin._loaded.then(function () {
  104954. assignSkeleton(skin._babylonSkeleton);
  104955. });
  104956. }
  104957. var skeletonId = "skeleton" + skin._index;
  104958. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  104959. skin._babylonSkeleton = babylonSkeleton;
  104960. this._loadBones(context, skin);
  104961. assignSkeleton(babylonSkeleton);
  104962. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  104963. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  104964. }));
  104965. };
  104966. GLTFLoader.prototype._loadBones = function (context, skin) {
  104967. var babylonBones = {};
  104968. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  104969. var index = _a[_i];
  104970. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  104971. this._loadBone(node, skin, babylonBones);
  104972. }
  104973. };
  104974. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  104975. var babylonBone = babylonBones[node._index];
  104976. if (babylonBone) {
  104977. return babylonBone;
  104978. }
  104979. var babylonParentBone = null;
  104980. if (node._parent._babylonMesh !== this._rootBabylonMesh) {
  104981. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  104982. }
  104983. var boneIndex = skin.joints.indexOf(node._index);
  104984. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  104985. babylonBones[node._index] = babylonBone;
  104986. node._babylonBones = node._babylonBones || [];
  104987. node._babylonBones.push(babylonBone);
  104988. return babylonBone;
  104989. };
  104990. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  104991. if (skin.inverseBindMatrices == undefined) {
  104992. return Promise.resolve(null);
  104993. }
  104994. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  104995. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  104996. };
  104997. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  104998. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  104999. var babylonBone = _a[_i];
  105000. var baseMatrix = BABYLON.Matrix.Identity();
  105001. var boneIndex = babylonBone._index;
  105002. if (inverseBindMatricesData && boneIndex !== -1) {
  105003. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  105004. baseMatrix.invertToRef(baseMatrix);
  105005. }
  105006. var babylonParentBone = babylonBone.getParent();
  105007. if (babylonParentBone) {
  105008. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  105009. }
  105010. babylonBone.updateMatrix(baseMatrix, false, false);
  105011. babylonBone._updateDifferenceMatrix(undefined, false);
  105012. }
  105013. };
  105014. GLTFLoader.prototype._getNodeMatrix = function (node) {
  105015. return node.matrix ?
  105016. BABYLON.Matrix.FromArray(node.matrix) :
  105017. 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());
  105018. };
  105019. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  105020. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  105021. babylonCamera.parent = babylonMesh;
  105022. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  105023. switch (camera.type) {
  105024. case "perspective" /* PERSPECTIVE */: {
  105025. var perspective = camera.perspective;
  105026. if (!perspective) {
  105027. throw new Error(context + ": Camera perspective properties are missing");
  105028. }
  105029. babylonCamera.fov = perspective.yfov;
  105030. babylonCamera.minZ = perspective.znear;
  105031. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  105032. break;
  105033. }
  105034. case "orthographic" /* ORTHOGRAPHIC */: {
  105035. if (!camera.orthographic) {
  105036. throw new Error(context + ": Camera orthographic properties are missing");
  105037. }
  105038. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  105039. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  105040. babylonCamera.orthoRight = camera.orthographic.xmag;
  105041. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  105042. babylonCamera.orthoTop = camera.orthographic.ymag;
  105043. babylonCamera.minZ = camera.orthographic.znear;
  105044. babylonCamera.maxZ = camera.orthographic.zfar;
  105045. break;
  105046. }
  105047. default: {
  105048. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  105049. }
  105050. }
  105051. this.onCameraLoadedObservable.notifyObservers(babylonCamera);
  105052. };
  105053. GLTFLoader.prototype._loadAnimationsAsync = function () {
  105054. var animations = this._gltf.animations;
  105055. if (!animations) {
  105056. return Promise.resolve();
  105057. }
  105058. var promises = new Array();
  105059. for (var index = 0; index < animations.length; index++) {
  105060. var animation = animations[index];
  105061. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  105062. }
  105063. return Promise.all(promises).then(function () { });
  105064. };
  105065. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  105066. var _this = this;
  105067. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  105068. animation._babylonAnimationGroup = babylonAnimationGroup;
  105069. var promises = new Array();
  105070. GLTF2._ArrayItem.Assign(animation.channels);
  105071. GLTF2._ArrayItem.Assign(animation.samplers);
  105072. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  105073. var channel = _a[_i];
  105074. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  105075. }
  105076. return Promise.all(promises).then(function () {
  105077. babylonAnimationGroup.normalize(_this._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  105078. });
  105079. };
  105080. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  105081. var _this = this;
  105082. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  105083. // Ignore animations that have no animation targets.
  105084. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  105085. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  105086. return Promise.resolve();
  105087. }
  105088. // Ignore animations targeting TRS of skinned nodes.
  105089. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  105090. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  105091. return Promise.resolve();
  105092. }
  105093. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  105094. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  105095. var targetPath;
  105096. var animationType;
  105097. switch (channel.target.path) {
  105098. case "translation" /* TRANSLATION */: {
  105099. targetPath = "position";
  105100. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105101. break;
  105102. }
  105103. case "rotation" /* ROTATION */: {
  105104. targetPath = "rotationQuaternion";
  105105. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  105106. break;
  105107. }
  105108. case "scale" /* SCALE */: {
  105109. targetPath = "scaling";
  105110. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  105111. break;
  105112. }
  105113. case "weights" /* WEIGHTS */: {
  105114. targetPath = "influence";
  105115. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  105116. break;
  105117. }
  105118. default: {
  105119. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  105120. }
  105121. }
  105122. var outputBufferOffset = 0;
  105123. var getNextOutputValue;
  105124. switch (targetPath) {
  105125. case "position": {
  105126. getNextOutputValue = function () {
  105127. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105128. outputBufferOffset += 3;
  105129. return value;
  105130. };
  105131. break;
  105132. }
  105133. case "rotationQuaternion": {
  105134. getNextOutputValue = function () {
  105135. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  105136. outputBufferOffset += 4;
  105137. return value;
  105138. };
  105139. break;
  105140. }
  105141. case "scaling": {
  105142. getNextOutputValue = function () {
  105143. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  105144. outputBufferOffset += 3;
  105145. return value;
  105146. };
  105147. break;
  105148. }
  105149. case "influence": {
  105150. getNextOutputValue = function () {
  105151. var value = new Array(targetNode._numMorphTargets);
  105152. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  105153. value[i] = data.output[outputBufferOffset++];
  105154. }
  105155. return value;
  105156. };
  105157. break;
  105158. }
  105159. }
  105160. var getNextKey;
  105161. switch (data.interpolation) {
  105162. case "STEP" /* STEP */: {
  105163. getNextKey = function (frameIndex) { return ({
  105164. frame: data.input[frameIndex],
  105165. value: getNextOutputValue(),
  105166. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  105167. }); };
  105168. break;
  105169. }
  105170. case "LINEAR" /* LINEAR */: {
  105171. getNextKey = function (frameIndex) { return ({
  105172. frame: data.input[frameIndex],
  105173. value: getNextOutputValue()
  105174. }); };
  105175. break;
  105176. }
  105177. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105178. getNextKey = function (frameIndex) { return ({
  105179. frame: data.input[frameIndex],
  105180. inTangent: getNextOutputValue(),
  105181. value: getNextOutputValue(),
  105182. outTangent: getNextOutputValue()
  105183. }); };
  105184. break;
  105185. }
  105186. }
  105187. var keys = new Array(data.input.length);
  105188. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  105189. keys[frameIndex] = getNextKey(frameIndex);
  105190. }
  105191. if (targetPath === "influence") {
  105192. var _loop_1 = function (targetIndex) {
  105193. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105194. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105195. babylonAnimation.setKeys(keys.map(function (key) { return ({
  105196. frame: key.frame,
  105197. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  105198. value: key.value[targetIndex],
  105199. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  105200. }); }));
  105201. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  105202. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  105203. var babylonAnimationClone = babylonAnimation.clone();
  105204. morphTarget.animations.push(babylonAnimationClone);
  105205. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  105206. });
  105207. };
  105208. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  105209. _loop_1(targetIndex);
  105210. }
  105211. }
  105212. else {
  105213. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  105214. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  105215. babylonAnimation.setKeys(keys);
  105216. if (targetNode._babylonBones) {
  105217. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  105218. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  105219. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  105220. babylonAnimationTarget.animations.push(babylonAnimation);
  105221. }
  105222. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  105223. }
  105224. else {
  105225. targetNode._babylonMesh.animations.push(babylonAnimation);
  105226. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  105227. }
  105228. }
  105229. });
  105230. };
  105231. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  105232. if (sampler._data) {
  105233. return sampler._data;
  105234. }
  105235. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  105236. switch (interpolation) {
  105237. case "STEP" /* STEP */:
  105238. case "LINEAR" /* LINEAR */:
  105239. case "CUBICSPLINE" /* CUBICSPLINE */: {
  105240. break;
  105241. }
  105242. default: {
  105243. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  105244. }
  105245. }
  105246. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  105247. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  105248. sampler._data = Promise.all([
  105249. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  105250. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  105251. ]).then(function (_a) {
  105252. var inputData = _a[0], outputData = _a[1];
  105253. return {
  105254. input: inputData,
  105255. interpolation: interpolation,
  105256. output: outputData,
  105257. };
  105258. });
  105259. return sampler._data;
  105260. };
  105261. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  105262. if (buffer._data) {
  105263. return buffer._data;
  105264. }
  105265. if (!buffer.uri) {
  105266. throw new Error(context + ": Uri is missing");
  105267. }
  105268. buffer._data = this._loadUriAsync(context, buffer.uri);
  105269. return buffer._data;
  105270. };
  105271. /** @hidden */
  105272. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  105273. if (bufferView._data) {
  105274. return bufferView._data;
  105275. }
  105276. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  105277. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  105278. try {
  105279. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  105280. }
  105281. catch (e) {
  105282. throw new Error(context + ": " + e.message);
  105283. }
  105284. });
  105285. return bufferView._data;
  105286. };
  105287. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  105288. if (accessor.type !== "SCALAR" /* SCALAR */) {
  105289. throw new Error(context + ": Invalid type " + accessor.type);
  105290. }
  105291. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  105292. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  105293. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  105294. throw new Error(context + ": Invalid component type " + accessor.componentType);
  105295. }
  105296. if (accessor._data) {
  105297. return accessor._data;
  105298. }
  105299. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105300. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105301. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  105302. });
  105303. return accessor._data;
  105304. };
  105305. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  105306. // TODO: support normalized and stride
  105307. var _this = this;
  105308. if (accessor.componentType !== 5126 /* FLOAT */) {
  105309. throw new Error("Invalid component type " + accessor.componentType);
  105310. }
  105311. if (accessor._data) {
  105312. return accessor._data;
  105313. }
  105314. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  105315. var length = numComponents * accessor.count;
  105316. if (accessor.bufferView == undefined) {
  105317. accessor._data = Promise.resolve(new Float32Array(length));
  105318. }
  105319. else {
  105320. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105321. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  105322. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  105323. });
  105324. }
  105325. if (accessor.sparse) {
  105326. var sparse_1 = accessor.sparse;
  105327. accessor._data = accessor._data.then(function (data) {
  105328. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  105329. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  105330. return Promise.all([
  105331. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  105332. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  105333. ]).then(function (_a) {
  105334. var indicesData = _a[0], valuesData = _a[1];
  105335. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  105336. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  105337. var valuesIndex = 0;
  105338. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  105339. var dataIndex = indices[indicesIndex] * numComponents;
  105340. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  105341. data[dataIndex++] = values[valuesIndex++];
  105342. }
  105343. }
  105344. return data;
  105345. });
  105346. });
  105347. }
  105348. return accessor._data;
  105349. };
  105350. /** @hidden */
  105351. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  105352. var _this = this;
  105353. if (bufferView._babylonBuffer) {
  105354. return bufferView._babylonBuffer;
  105355. }
  105356. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  105357. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  105358. });
  105359. return bufferView._babylonBuffer;
  105360. };
  105361. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  105362. var _this = this;
  105363. if (accessor._babylonVertexBuffer) {
  105364. return accessor._babylonVertexBuffer;
  105365. }
  105366. if (accessor.sparse) {
  105367. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  105368. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  105369. });
  105370. }
  105371. else {
  105372. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  105373. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  105374. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  105375. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  105376. });
  105377. }
  105378. return accessor._babylonVertexBuffer;
  105379. };
  105380. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  105381. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  105382. if (!babylonMaterial) {
  105383. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  105384. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105385. babylonMaterial.metallic = 1;
  105386. babylonMaterial.roughness = 1;
  105387. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105388. }
  105389. return babylonMaterial;
  105390. };
  105391. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  105392. var promises = new Array();
  105393. // Ensure metallic workflow
  105394. babylonMaterial.metallic = 1;
  105395. babylonMaterial.roughness = 1;
  105396. var properties = material.pbrMetallicRoughness;
  105397. if (properties) {
  105398. if (properties.baseColorFactor) {
  105399. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  105400. babylonMaterial.alpha = properties.baseColorFactor[3];
  105401. }
  105402. else {
  105403. babylonMaterial.albedoColor = BABYLON.Color3.White();
  105404. }
  105405. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  105406. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  105407. if (properties.baseColorTexture) {
  105408. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  105409. babylonMaterial.albedoTexture = texture;
  105410. }));
  105411. }
  105412. if (properties.metallicRoughnessTexture) {
  105413. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  105414. babylonMaterial.metallicTexture = texture;
  105415. }));
  105416. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  105417. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  105418. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  105419. }
  105420. }
  105421. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  105422. return Promise.all(promises).then(function () { });
  105423. };
  105424. /** @hidden */
  105425. GLTFLoader.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105426. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, babylonMesh, babylonDrawMode, assign);
  105427. if (promise) {
  105428. return promise;
  105429. }
  105430. material._babylonData = material._babylonData || {};
  105431. var babylonData = material._babylonData[babylonDrawMode];
  105432. if (!babylonData) {
  105433. var promises = new Array();
  105434. var name_3 = material.name || "materialSG_" + material._index;
  105435. var babylonMaterial = this._createMaterial(name_3, babylonDrawMode);
  105436. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  105437. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  105438. this.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  105439. babylonData = {
  105440. material: babylonMaterial,
  105441. meshes: [],
  105442. loaded: Promise.all(promises).then(function () { })
  105443. };
  105444. material._babylonData[babylonDrawMode] = babylonData;
  105445. }
  105446. babylonData.meshes.push(babylonMesh);
  105447. assign(babylonData.material);
  105448. return babylonData.loaded;
  105449. };
  105450. /** @hidden */
  105451. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  105452. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  105453. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  105454. babylonMaterial.fillMode = drawMode;
  105455. babylonMaterial.enableSpecularAntiAliasing = true;
  105456. babylonMaterial.useRadianceOverAlpha = !this.transparencyAsCoverage;
  105457. babylonMaterial.useSpecularOverAlpha = !this.transparencyAsCoverage;
  105458. return babylonMaterial;
  105459. };
  105460. /** @hidden */
  105461. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  105462. var promises = new Array();
  105463. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  105464. if (material.doubleSided) {
  105465. babylonMaterial.backFaceCulling = false;
  105466. babylonMaterial.twoSidedLighting = true;
  105467. }
  105468. if (material.normalTexture) {
  105469. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  105470. babylonMaterial.bumpTexture = texture;
  105471. }));
  105472. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  105473. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  105474. if (material.normalTexture.scale != undefined) {
  105475. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  105476. }
  105477. }
  105478. if (material.occlusionTexture) {
  105479. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  105480. babylonMaterial.ambientTexture = texture;
  105481. }));
  105482. babylonMaterial.useAmbientInGrayScale = true;
  105483. if (material.occlusionTexture.strength != undefined) {
  105484. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  105485. }
  105486. }
  105487. if (material.emissiveTexture) {
  105488. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  105489. babylonMaterial.emissiveTexture = texture;
  105490. }));
  105491. }
  105492. return Promise.all(promises).then(function () { });
  105493. };
  105494. /** @hidden */
  105495. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  105496. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  105497. switch (alphaMode) {
  105498. case "OPAQUE" /* OPAQUE */: {
  105499. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  105500. break;
  105501. }
  105502. case "MASK" /* MASK */: {
  105503. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  105504. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  105505. if (babylonMaterial.albedoTexture) {
  105506. babylonMaterial.albedoTexture.hasAlpha = true;
  105507. }
  105508. break;
  105509. }
  105510. case "BLEND" /* BLEND */: {
  105511. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  105512. if (babylonMaterial.albedoTexture) {
  105513. babylonMaterial.albedoTexture.hasAlpha = true;
  105514. babylonMaterial.useAlphaFromAlbedoTexture = true;
  105515. }
  105516. break;
  105517. }
  105518. default: {
  105519. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  105520. }
  105521. }
  105522. };
  105523. /** @hidden */
  105524. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  105525. var _this = this;
  105526. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  105527. context = "#/textures/" + textureInfo.index;
  105528. var promises = new Array();
  105529. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  105530. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  105531. var deferred = new BABYLON.Deferred();
  105532. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  105533. if (!_this._disposed) {
  105534. deferred.resolve();
  105535. }
  105536. }, function (message, exception) {
  105537. if (!_this._disposed) {
  105538. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  105539. }
  105540. });
  105541. promises.push(deferred.promise);
  105542. babylonTexture.name = texture.name || "texture" + texture._index;
  105543. babylonTexture.wrapU = samplerData.wrapU;
  105544. babylonTexture.wrapV = samplerData.wrapV;
  105545. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  105546. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  105547. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (objectURL) {
  105548. babylonTexture.updateURL(objectURL);
  105549. }));
  105550. assign(babylonTexture);
  105551. this.onTextureLoadedObservable.notifyObservers(babylonTexture);
  105552. return Promise.all(promises).then(function () { });
  105553. };
  105554. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  105555. if (!sampler._data) {
  105556. sampler._data = {
  105557. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  105558. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  105559. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  105560. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  105561. };
  105562. }
  105563. ;
  105564. return sampler._data;
  105565. };
  105566. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  105567. if (image._objectURL) {
  105568. return image._objectURL;
  105569. }
  105570. var promise;
  105571. if (image.uri) {
  105572. promise = this._loadUriAsync(context, image.uri);
  105573. }
  105574. else {
  105575. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  105576. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  105577. }
  105578. image._objectURL = promise.then(function (data) {
  105579. return URL.createObjectURL(new Blob([data], { type: image.mimeType }));
  105580. });
  105581. return image._objectURL;
  105582. };
  105583. /** @hidden */
  105584. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  105585. var _this = this;
  105586. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  105587. if (promise) {
  105588. return promise;
  105589. }
  105590. if (!GLTFLoader._ValidateUri(uri)) {
  105591. throw new Error(context + ": Uri '" + uri + "' is invalid");
  105592. }
  105593. if (BABYLON.Tools.IsBase64(uri)) {
  105594. return Promise.resolve(new Uint8Array(BABYLON.Tools.DecodeBase64(uri)));
  105595. }
  105596. return this.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  105597. return new Promise(function (resolve, reject) {
  105598. if (!_this._disposed) {
  105599. var request_1 = BABYLON.Tools.LoadFile(url, function (data) {
  105600. if (!_this._disposed) {
  105601. resolve(new Uint8Array(data));
  105602. }
  105603. }, function (event) {
  105604. if (!_this._disposed) {
  105605. try {
  105606. if (request_1 && _this._state === BABYLON.GLTFLoaderState.LOADING) {
  105607. request_1._lengthComputable = event.lengthComputable;
  105608. request_1._loaded = event.loaded;
  105609. request_1._total = event.total;
  105610. _this._onProgress();
  105611. }
  105612. }
  105613. catch (e) {
  105614. reject(e);
  105615. }
  105616. }
  105617. }, _this._babylonScene.database, true, function (request, exception) {
  105618. if (!_this._disposed) {
  105619. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  105620. }
  105621. });
  105622. _this._requests.push(request_1);
  105623. }
  105624. });
  105625. });
  105626. };
  105627. GLTFLoader.prototype._onProgress = function () {
  105628. if (!this._progressCallback) {
  105629. return;
  105630. }
  105631. var lengthComputable = true;
  105632. var loaded = 0;
  105633. var total = 0;
  105634. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105635. var request = _a[_i];
  105636. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  105637. return;
  105638. }
  105639. lengthComputable = lengthComputable && request._lengthComputable;
  105640. loaded += request._loaded;
  105641. total += request._total;
  105642. }
  105643. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  105644. };
  105645. /** @hidden */
  105646. GLTFLoader._GetProperty = function (context, array, index) {
  105647. if (!array || index == undefined || !array[index]) {
  105648. throw new Error(context + ": Failed to find index (" + index + ")");
  105649. }
  105650. return array[index];
  105651. };
  105652. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  105653. // Set defaults if undefined
  105654. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  105655. switch (mode) {
  105656. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  105657. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  105658. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  105659. default:
  105660. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  105661. return BABYLON.Texture.WRAP_ADDRESSMODE;
  105662. }
  105663. };
  105664. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  105665. // Set defaults if undefined
  105666. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  105667. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  105668. if (magFilter === 9729 /* LINEAR */) {
  105669. switch (minFilter) {
  105670. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  105671. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  105672. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  105673. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  105674. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  105675. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105676. default:
  105677. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105678. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  105679. }
  105680. }
  105681. else {
  105682. if (magFilter !== 9728 /* NEAREST */) {
  105683. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  105684. }
  105685. switch (minFilter) {
  105686. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  105687. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  105688. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105689. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  105690. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  105691. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  105692. default:
  105693. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  105694. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  105695. }
  105696. }
  105697. };
  105698. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  105699. var buffer = bufferView.buffer;
  105700. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  105701. try {
  105702. switch (componentType) {
  105703. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  105704. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  105705. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  105706. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  105707. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  105708. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  105709. default: throw new Error("Invalid component type " + componentType);
  105710. }
  105711. }
  105712. catch (e) {
  105713. throw new Error(context + ": " + e);
  105714. }
  105715. };
  105716. GLTFLoader._GetNumComponents = function (context, type) {
  105717. switch (type) {
  105718. case "SCALAR": return 1;
  105719. case "VEC2": return 2;
  105720. case "VEC3": return 3;
  105721. case "VEC4": return 4;
  105722. case "MAT2": return 4;
  105723. case "MAT3": return 9;
  105724. case "MAT4": return 16;
  105725. }
  105726. throw new Error(context + ": Invalid type (" + type + ")");
  105727. };
  105728. GLTFLoader._ValidateUri = function (uri) {
  105729. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  105730. };
  105731. GLTFLoader._GetDrawMode = function (context, mode) {
  105732. if (mode == undefined) {
  105733. mode = 4 /* TRIANGLES */;
  105734. }
  105735. switch (mode) {
  105736. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  105737. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  105738. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  105739. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  105740. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  105741. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  105742. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  105743. }
  105744. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  105745. };
  105746. GLTFLoader.prototype._compileMaterialsAsync = function () {
  105747. var promises = new Array();
  105748. if (this._gltf.materials) {
  105749. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  105750. var material = _a[_i];
  105751. if (material._babylonData) {
  105752. for (var babylonDrawMode in material._babylonData) {
  105753. var babylonData = material._babylonData[babylonDrawMode];
  105754. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  105755. var babylonMesh = _c[_b];
  105756. // Ensure nonUniformScaling is set if necessary.
  105757. babylonMesh.computeWorldMatrix(true);
  105758. var babylonMaterial = babylonData.material;
  105759. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  105760. if (this.useClipPlane) {
  105761. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  105762. }
  105763. }
  105764. }
  105765. }
  105766. }
  105767. }
  105768. return Promise.all(promises).then(function () { });
  105769. };
  105770. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  105771. var promises = new Array();
  105772. var lights = this._babylonScene.lights;
  105773. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  105774. var light = lights_1[_i];
  105775. var generator = light.getShadowGenerator();
  105776. if (generator) {
  105777. promises.push(generator.forceCompilationAsync());
  105778. }
  105779. }
  105780. return Promise.all(promises).then(function () { });
  105781. };
  105782. GLTFLoader.prototype._clear = function () {
  105783. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  105784. var request = _a[_i];
  105785. request.abort();
  105786. }
  105787. this._requests.length = 0;
  105788. if (this._gltf && this._gltf.images) {
  105789. for (var _b = 0, _c = this._gltf.images; _b < _c.length; _b++) {
  105790. var image = _c[_b];
  105791. if (image._objectURL) {
  105792. image._objectURL.then(function (value) {
  105793. URL.revokeObjectURL(value);
  105794. });
  105795. image._objectURL = undefined;
  105796. }
  105797. }
  105798. }
  105799. delete this._gltf;
  105800. delete this._babylonScene;
  105801. this._completePromises.length = 0;
  105802. for (var name_4 in this._extensions) {
  105803. this._extensions[name_4].dispose();
  105804. }
  105805. this._extensions = {};
  105806. delete this._rootBabylonMesh;
  105807. delete this._progressCallback;
  105808. this.onMeshLoadedObservable.clear();
  105809. this.onTextureLoadedObservable.clear();
  105810. this.onMaterialLoadedObservable.clear();
  105811. this.onCameraLoadedObservable.clear();
  105812. };
  105813. /** @hidden */
  105814. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  105815. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  105816. var name_5 = _a[_i];
  105817. var extension = this._extensions[name_5];
  105818. if (extension.enabled) {
  105819. var promise = actionAsync(extension);
  105820. if (promise) {
  105821. return promise;
  105822. }
  105823. }
  105824. }
  105825. return null;
  105826. };
  105827. GLTFLoader._ExtensionNames = new Array();
  105828. GLTFLoader._ExtensionFactories = {};
  105829. return GLTFLoader;
  105830. }());
  105831. GLTF2.GLTFLoader = GLTFLoader;
  105832. BABYLON.GLTFFileLoader.CreateGLTFLoaderV2 = function () { return new GLTFLoader(); };
  105833. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105834. })(BABYLON || (BABYLON = {}));
  105835. //# sourceMappingURL=babylon.glTFLoader.js.map
  105836. var BABYLON;
  105837. (function (BABYLON) {
  105838. var GLTF2;
  105839. (function (GLTF2) {
  105840. /**
  105841. * Abstract class that can be implemented to extend existing glTF loader behavior.
  105842. */
  105843. var GLTFLoaderExtension = /** @class */ (function () {
  105844. function GLTFLoaderExtension(loader) {
  105845. this.enabled = true;
  105846. this._loader = loader;
  105847. }
  105848. GLTFLoaderExtension.prototype.dispose = function () {
  105849. delete this._loader;
  105850. };
  105851. // #region Overridable Methods
  105852. /** Override this method to modify the default behavior for loading scenes. */
  105853. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  105854. /** Override this method to modify the default behavior for loading nodes. */
  105855. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  105856. /** Override this method to modify the default behavior for loading mesh primitive vertex data. */
  105857. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  105858. /** Override this method to modify the default behavior for loading materials. */
  105859. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) { return null; };
  105860. /** Override this method to modify the default behavior for loading uris. */
  105861. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  105862. // #endregion
  105863. /** Helper method called by a loader extension to load an glTF extension. */
  105864. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  105865. if (!property.extensions) {
  105866. return null;
  105867. }
  105868. var extensions = property.extensions;
  105869. var extension = extensions[this.name];
  105870. if (!extension) {
  105871. return null;
  105872. }
  105873. // Clear out the extension before executing the action to avoid recursing into the same property.
  105874. delete extensions[this.name];
  105875. try {
  105876. return actionAsync(context + "/extensions/" + this.name, extension);
  105877. }
  105878. finally {
  105879. // Restore the extension after executing the action.
  105880. extensions[this.name] = extension;
  105881. }
  105882. };
  105883. /** Helper method called by the loader to allow extensions to override loading scenes. */
  105884. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  105885. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  105886. };
  105887. /** Helper method called by the loader to allow extensions to override loading nodes. */
  105888. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  105889. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  105890. };
  105891. /** Helper method called by the loader to allow extensions to override loading mesh primitive vertex data. */
  105892. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  105893. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  105894. };
  105895. /** Helper method called by the loader to allow extensions to override loading materials. */
  105896. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, babylonMesh, babylonDrawMode, assign) {
  105897. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, babylonMesh, babylonDrawMode, assign); });
  105898. };
  105899. /** Helper method called by the loader to allow extensions to override loading uris. */
  105900. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  105901. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  105902. };
  105903. return GLTFLoaderExtension;
  105904. }());
  105905. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  105906. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  105907. })(BABYLON || (BABYLON = {}));
  105908. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  105909. var BABYLON;
  105910. (function (BABYLON) {
  105911. var GLTF2;
  105912. (function (GLTF2) {
  105913. var Extensions;
  105914. (function (Extensions) {
  105915. var NAME = "MSFT_lod";
  105916. /**
  105917. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  105918. */
  105919. var MSFT_lod = /** @class */ (function (_super) {
  105920. __extends(MSFT_lod, _super);
  105921. function MSFT_lod() {
  105922. var _this = _super !== null && _super.apply(this, arguments) || this;
  105923. _this.name = NAME;
  105924. /**
  105925. * Maximum number of LODs to load, starting from the lowest LOD.
  105926. */
  105927. _this.maxLODsToLoad = Number.MAX_VALUE;
  105928. _this._loadingNodeLOD = null;
  105929. _this._loadNodeSignals = {};
  105930. _this._loadingMaterialLOD = null;
  105931. _this._loadMaterialSignals = {};
  105932. return _this;
  105933. }
  105934. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  105935. var _this = this;
  105936. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  105937. var firstPromise;
  105938. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  105939. var _loop_1 = function (indexLOD) {
  105940. var nodeLOD = nodeLODs[indexLOD];
  105941. if (indexLOD !== 0) {
  105942. _this._loadingNodeLOD = nodeLOD;
  105943. if (!_this._loadNodeSignals[nodeLOD._index]) {
  105944. _this._loadNodeSignals[nodeLOD._index] = new BABYLON.Deferred();
  105945. }
  105946. }
  105947. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  105948. if (indexLOD !== 0) {
  105949. var previousNodeLOD = nodeLODs[indexLOD - 1];
  105950. if (previousNodeLOD._babylonMesh) {
  105951. previousNodeLOD._babylonMesh.dispose(false, true);
  105952. delete previousNodeLOD._babylonMesh;
  105953. }
  105954. }
  105955. if (indexLOD !== nodeLODs.length - 1) {
  105956. var nodeIndex = nodeLODs[indexLOD + 1]._index;
  105957. if (_this._loadNodeSignals[nodeIndex]) {
  105958. _this._loadNodeSignals[nodeIndex].resolve();
  105959. delete _this._loadNodeSignals[nodeIndex];
  105960. }
  105961. }
  105962. });
  105963. if (indexLOD === 0) {
  105964. firstPromise = promise;
  105965. }
  105966. else {
  105967. _this._loader._completePromises.push(promise);
  105968. _this._loadingNodeLOD = null;
  105969. }
  105970. };
  105971. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  105972. _loop_1(indexLOD);
  105973. }
  105974. return firstPromise;
  105975. });
  105976. };
  105977. MSFT_lod.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  105978. var _this = this;
  105979. // Don't load material LODs if already loading a node LOD.
  105980. if (this._loadingNodeLOD) {
  105981. return null;
  105982. }
  105983. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  105984. var firstPromise;
  105985. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  105986. var _loop_2 = function (indexLOD) {
  105987. var materialLOD = materialLODs[indexLOD];
  105988. if (indexLOD !== 0) {
  105989. _this._loadingMaterialLOD = materialLOD;
  105990. if (!_this._loadMaterialSignals[materialLOD._index]) {
  105991. _this._loadMaterialSignals[materialLOD._index] = new BABYLON.Deferred();
  105992. }
  105993. }
  105994. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  105995. if (indexLOD !== 0) {
  105996. var babylonDataLOD = materialLOD._babylonData;
  105997. assign(babylonDataLOD[babylonDrawMode].material);
  105998. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  105999. if (previousBabylonDataLOD[babylonDrawMode]) {
  106000. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  106001. delete previousBabylonDataLOD[babylonDrawMode];
  106002. }
  106003. }
  106004. if (indexLOD !== materialLODs.length - 1) {
  106005. var materialIndex = materialLODs[indexLOD + 1]._index;
  106006. if (_this._loadMaterialSignals[materialIndex]) {
  106007. _this._loadMaterialSignals[materialIndex].resolve();
  106008. delete _this._loadMaterialSignals[materialIndex];
  106009. }
  106010. }
  106011. });
  106012. if (indexLOD === 0) {
  106013. firstPromise = promise;
  106014. }
  106015. else {
  106016. _this._loader._completePromises.push(promise);
  106017. _this._loadingMaterialLOD = null;
  106018. }
  106019. };
  106020. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  106021. _loop_2(indexLOD);
  106022. }
  106023. return firstPromise;
  106024. });
  106025. };
  106026. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  106027. var _this = this;
  106028. // Defer the loading of uris if loading a material or node LOD.
  106029. if (this._loadingMaterialLOD) {
  106030. var index = this._loadingMaterialLOD._index;
  106031. return this._loadMaterialSignals[index].promise.then(function () {
  106032. return _this._loader._loadUriAsync(context, uri);
  106033. });
  106034. }
  106035. else if (this._loadingNodeLOD) {
  106036. var index = this._loadingNodeLOD._index;
  106037. return this._loadNodeSignals[index].promise.then(function () {
  106038. return _this._loader._loadUriAsync(context, uri);
  106039. });
  106040. }
  106041. return null;
  106042. };
  106043. /**
  106044. * Gets an array of LOD properties from lowest to highest.
  106045. */
  106046. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  106047. if (this.maxLODsToLoad <= 0) {
  106048. throw new Error("maxLODsToLoad must be greater than zero");
  106049. }
  106050. var properties = new Array();
  106051. for (var i = ids.length - 1; i >= 0; i--) {
  106052. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  106053. if (properties.length === this.maxLODsToLoad) {
  106054. return properties;
  106055. }
  106056. }
  106057. properties.push(property);
  106058. return properties;
  106059. };
  106060. return MSFT_lod;
  106061. }(GLTF2.GLTFLoaderExtension));
  106062. Extensions.MSFT_lod = MSFT_lod;
  106063. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  106064. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106065. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106066. })(BABYLON || (BABYLON = {}));
  106067. //# sourceMappingURL=MSFT_lod.js.map
  106068. var BABYLON;
  106069. (function (BABYLON) {
  106070. var GLTF2;
  106071. (function (GLTF2) {
  106072. var Extensions;
  106073. (function (Extensions) {
  106074. var NAME = "MSFT_minecraftMesh";
  106075. /** @hidden */
  106076. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  106077. __extends(MSFT_minecraftMesh, _super);
  106078. function MSFT_minecraftMesh(loader) {
  106079. var _this = _super.call(this, loader) || this;
  106080. _this.name = NAME;
  106081. _this._onMaterialLoaded = function (material) {
  106082. if (material.needAlphaBlending()) {
  106083. material.forceDepthWrite = true;
  106084. material.separateCullingPass = true;
  106085. }
  106086. material.backFaceCulling = material.forceDepthWrite;
  106087. material.twoSidedLighting = true;
  106088. };
  106089. var meshes = loader._gltf.meshes;
  106090. if (meshes && meshes.length) {
  106091. for (var _i = 0, meshes_1 = meshes; _i < meshes_1.length; _i++) {
  106092. var mesh = meshes_1[_i];
  106093. if (mesh && mesh.extras && mesh.extras.MSFT_minecraftMesh) {
  106094. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106095. break;
  106096. }
  106097. }
  106098. }
  106099. return _this;
  106100. }
  106101. return MSFT_minecraftMesh;
  106102. }(GLTF2.GLTFLoaderExtension));
  106103. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  106104. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  106105. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106106. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106107. })(BABYLON || (BABYLON = {}));
  106108. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  106109. var BABYLON;
  106110. (function (BABYLON) {
  106111. var GLTF2;
  106112. (function (GLTF2) {
  106113. var Extensions;
  106114. (function (Extensions) {
  106115. var NAME = "MSFT_sRGBFactors";
  106116. /** @hidden */
  106117. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  106118. __extends(MSFT_sRGBFactors, _super);
  106119. function MSFT_sRGBFactors(loader) {
  106120. var _this = _super.call(this, loader) || this;
  106121. _this.name = NAME;
  106122. _this._onMaterialLoaded = function (material) {
  106123. if (!material.albedoTexture) {
  106124. material.albedoColor.toLinearSpaceToRef(material.albedoColor);
  106125. }
  106126. if (!material.reflectivityTexture) {
  106127. material.reflectivityColor.toLinearSpaceToRef(material.reflectivityColor);
  106128. }
  106129. };
  106130. var materials = loader._gltf.materials;
  106131. if (materials && materials.length) {
  106132. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  106133. var material = materials_1[_i];
  106134. if (material && material.extras && material.extras.MSFT_sRGBFactors) {
  106135. _this._loader.onMaterialLoadedObservable.add(_this._onMaterialLoaded);
  106136. break;
  106137. }
  106138. }
  106139. }
  106140. return _this;
  106141. }
  106142. return MSFT_sRGBFactors;
  106143. }(GLTF2.GLTFLoaderExtension));
  106144. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  106145. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  106146. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106147. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106148. })(BABYLON || (BABYLON = {}));
  106149. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  106150. var BABYLON;
  106151. (function (BABYLON) {
  106152. var GLTF2;
  106153. (function (GLTF2) {
  106154. var Extensions;
  106155. (function (Extensions) {
  106156. var NAME = "KHR_draco_mesh_compression";
  106157. /**
  106158. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  106159. */
  106160. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  106161. __extends(KHR_draco_mesh_compression, _super);
  106162. function KHR_draco_mesh_compression(loader) {
  106163. var _this = _super.call(this, loader) || this;
  106164. _this.name = NAME;
  106165. _this._dracoCompression = null;
  106166. // Disable extension if decoder is not available.
  106167. if (!BABYLON.DracoCompression.DecoderAvailable) {
  106168. _this.enabled = false;
  106169. }
  106170. return _this;
  106171. }
  106172. KHR_draco_mesh_compression.prototype.dispose = function () {
  106173. if (this._dracoCompression) {
  106174. this._dracoCompression.dispose();
  106175. }
  106176. _super.prototype.dispose.call(this);
  106177. };
  106178. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  106179. var _this = this;
  106180. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  106181. if (primitive.mode != undefined) {
  106182. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  106183. primitive.mode !== 4 /* TRIANGLES */) {
  106184. throw new Error(context + ": Unsupported mode " + primitive.mode);
  106185. }
  106186. // TODO: handle triangle strips
  106187. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  106188. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  106189. }
  106190. }
  106191. var attributes = {};
  106192. var loadAttribute = function (name, kind) {
  106193. var uniqueId = extension.attributes[name];
  106194. if (uniqueId == undefined) {
  106195. return;
  106196. }
  106197. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  106198. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  106199. babylonMesh._delayInfo.push(kind);
  106200. }
  106201. attributes[kind] = uniqueId;
  106202. };
  106203. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  106204. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  106205. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  106206. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  106207. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  106208. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  106209. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  106210. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  106211. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  106212. if (!bufferView._dracoBabylonGeometry) {
  106213. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  106214. if (!_this._dracoCompression) {
  106215. _this._dracoCompression = new BABYLON.DracoCompression();
  106216. }
  106217. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  106218. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  106219. babylonVertexData.applyToGeometry(babylonGeometry);
  106220. return babylonGeometry;
  106221. }).catch(function (error) {
  106222. throw new Error(context + ": " + error.message);
  106223. });
  106224. });
  106225. }
  106226. return bufferView._dracoBabylonGeometry;
  106227. });
  106228. };
  106229. return KHR_draco_mesh_compression;
  106230. }(GLTF2.GLTFLoaderExtension));
  106231. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  106232. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  106233. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106234. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106235. })(BABYLON || (BABYLON = {}));
  106236. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  106237. var BABYLON;
  106238. (function (BABYLON) {
  106239. var GLTF2;
  106240. (function (GLTF2) {
  106241. var Extensions;
  106242. (function (Extensions) {
  106243. var NAME = "KHR_materials_pbrSpecularGlossiness";
  106244. /**
  106245. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  106246. */
  106247. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  106248. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  106249. function KHR_materials_pbrSpecularGlossiness() {
  106250. var _this = _super !== null && _super.apply(this, arguments) || this;
  106251. _this.name = NAME;
  106252. return _this;
  106253. }
  106254. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106255. var _this = this;
  106256. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  106257. material._babylonData = material._babylonData || {};
  106258. var babylonData = material._babylonData[babylonDrawMode];
  106259. if (!babylonData) {
  106260. var promises = new Array();
  106261. var name_1 = material.name || "materialSG_" + material._index;
  106262. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106263. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  106264. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  106265. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106266. babylonData = {
  106267. material: babylonMaterial,
  106268. meshes: [],
  106269. loaded: Promise.all(promises).then(function () { })
  106270. };
  106271. material._babylonData[babylonDrawMode] = babylonData;
  106272. }
  106273. babylonData.meshes.push(babylonMesh);
  106274. assign(babylonData.material);
  106275. return babylonData.loaded;
  106276. });
  106277. };
  106278. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  106279. var promises = new Array();
  106280. if (properties.diffuseFactor) {
  106281. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  106282. babylonMaterial.alpha = properties.diffuseFactor[3];
  106283. }
  106284. else {
  106285. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106286. }
  106287. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  106288. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  106289. if (properties.diffuseTexture) {
  106290. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  106291. babylonMaterial.albedoTexture = texture;
  106292. }));
  106293. }
  106294. if (properties.specularGlossinessTexture) {
  106295. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  106296. babylonMaterial.reflectivityTexture = texture;
  106297. }));
  106298. babylonMaterial.reflectivityTexture.hasAlpha = true;
  106299. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  106300. }
  106301. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106302. return Promise.all(promises).then(function () { });
  106303. };
  106304. return KHR_materials_pbrSpecularGlossiness;
  106305. }(GLTF2.GLTFLoaderExtension));
  106306. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  106307. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  106308. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106309. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106310. })(BABYLON || (BABYLON = {}));
  106311. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  106312. var BABYLON;
  106313. (function (BABYLON) {
  106314. var GLTF2;
  106315. (function (GLTF2) {
  106316. var Extensions;
  106317. (function (Extensions) {
  106318. var NAME = "KHR_materials_unlit";
  106319. /**
  106320. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  106321. */
  106322. var KHR_materials_unlit = /** @class */ (function (_super) {
  106323. __extends(KHR_materials_unlit, _super);
  106324. function KHR_materials_unlit() {
  106325. var _this = _super !== null && _super.apply(this, arguments) || this;
  106326. _this.name = NAME;
  106327. return _this;
  106328. }
  106329. KHR_materials_unlit.prototype._loadMaterialAsync = function (context, material, babylonMesh, babylonDrawMode, assign) {
  106330. var _this = this;
  106331. return this._loadExtensionAsync(context, material, function () {
  106332. material._babylonData = material._babylonData || {};
  106333. var babylonData = material._babylonData[babylonDrawMode];
  106334. if (!babylonData) {
  106335. var name_1 = material.name || "materialUnlit_" + material._index;
  106336. var babylonMaterial = _this._loader._createMaterial(name_1, babylonDrawMode);
  106337. babylonMaterial.unlit = true;
  106338. var promise = _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  106339. _this._loader.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  106340. babylonData = {
  106341. material: babylonMaterial,
  106342. meshes: [],
  106343. loaded: promise
  106344. };
  106345. material._babylonData[babylonDrawMode] = babylonData;
  106346. }
  106347. babylonData.meshes.push(babylonMesh);
  106348. assign(babylonData.material);
  106349. return babylonData.loaded;
  106350. });
  106351. };
  106352. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  106353. var promises = new Array();
  106354. // Ensure metallic workflow
  106355. babylonMaterial.metallic = 1;
  106356. babylonMaterial.roughness = 1;
  106357. var properties = material.pbrMetallicRoughness;
  106358. if (properties) {
  106359. if (properties.baseColorFactor) {
  106360. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  106361. babylonMaterial.alpha = properties.baseColorFactor[3];
  106362. }
  106363. else {
  106364. babylonMaterial.albedoColor = BABYLON.Color3.White();
  106365. }
  106366. if (properties.baseColorTexture) {
  106367. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  106368. babylonMaterial.albedoTexture = texture;
  106369. }));
  106370. }
  106371. }
  106372. if (material.doubleSided) {
  106373. babylonMaterial.backFaceCulling = false;
  106374. babylonMaterial.twoSidedLighting = true;
  106375. }
  106376. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  106377. return Promise.all(promises).then(function () { });
  106378. };
  106379. return KHR_materials_unlit;
  106380. }(GLTF2.GLTFLoaderExtension));
  106381. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  106382. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  106383. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106384. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106385. })(BABYLON || (BABYLON = {}));
  106386. var BABYLON;
  106387. (function (BABYLON) {
  106388. var GLTF2;
  106389. (function (GLTF2) {
  106390. var Extensions;
  106391. (function (Extensions) {
  106392. var NAME = "KHR_lights";
  106393. var LightType;
  106394. (function (LightType) {
  106395. LightType["AMBIENT"] = "ambient";
  106396. LightType["DIRECTIONAL"] = "directional";
  106397. LightType["POINT"] = "point";
  106398. LightType["SPOT"] = "spot";
  106399. })(LightType || (LightType = {}));
  106400. /**
  106401. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  106402. */
  106403. var KHR_lights = /** @class */ (function (_super) {
  106404. __extends(KHR_lights, _super);
  106405. function KHR_lights() {
  106406. var _this = _super !== null && _super.apply(this, arguments) || this;
  106407. _this.name = NAME;
  106408. return _this;
  106409. }
  106410. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  106411. var _this = this;
  106412. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  106413. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  106414. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106415. if (light.type !== LightType.AMBIENT) {
  106416. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  106417. }
  106418. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  106419. return promise;
  106420. });
  106421. };
  106422. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  106423. var _this = this;
  106424. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  106425. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  106426. var babylonLight;
  106427. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  106428. var name = node._babylonMesh.name;
  106429. switch (light.type) {
  106430. case LightType.AMBIENT: {
  106431. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  106432. }
  106433. case LightType.DIRECTIONAL: {
  106434. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  106435. break;
  106436. }
  106437. case LightType.POINT: {
  106438. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  106439. break;
  106440. }
  106441. case LightType.SPOT: {
  106442. var spotLight = light;
  106443. // TODO: support inner and outer cone angles
  106444. //const innerConeAngle = spotLight.innerConeAngle || 0;
  106445. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  106446. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  106447. break;
  106448. }
  106449. default: {
  106450. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  106451. }
  106452. }
  106453. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  106454. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  106455. babylonLight.parent = node._babylonMesh;
  106456. return promise;
  106457. });
  106458. };
  106459. Object.defineProperty(KHR_lights.prototype, "_lights", {
  106460. get: function () {
  106461. var extensions = this._loader._gltf.extensions;
  106462. if (!extensions || !extensions[this.name]) {
  106463. throw new Error("#/extensions: '" + this.name + "' not found");
  106464. }
  106465. var extension = extensions[this.name];
  106466. return extension.lights;
  106467. },
  106468. enumerable: true,
  106469. configurable: true
  106470. });
  106471. return KHR_lights;
  106472. }(GLTF2.GLTFLoaderExtension));
  106473. Extensions.KHR_lights = KHR_lights;
  106474. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  106475. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  106476. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  106477. })(BABYLON || (BABYLON = {}));
  106478. return BABYLON;
  106479. });
  106480. /***/ }),
  106481. /* 21 */
  106482. /***/ (function(module, exports, __webpack_require__) {
  106483. module.exports = __webpack_require__(6);
  106484. /***/ }),
  106485. /* 22 */
  106486. /***/ (function(module, exports) {
  106487. var g;
  106488. // This works in non-strict mode
  106489. g = (function() {
  106490. return this;
  106491. })();
  106492. try {
  106493. // This works if eval is allowed (see CSP)
  106494. g = g || Function("return this")() || (1,eval)("this");
  106495. } catch(e) {
  106496. // This works if the window reference is available
  106497. if(typeof window === "object")
  106498. g = window;
  106499. }
  106500. // g can still be undefined, but nothing to do about it...
  106501. // We return undefined, instead of nothing here, so it's
  106502. // easier to handle this case. if(!global) { ...}
  106503. module.exports = g;
  106504. /***/ }),
  106505. /* 23 */
  106506. /***/ (function(module, exports) {
  106507. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106508. module.exports = CANNON;
  106509. /***/ }),
  106510. /* 24 */
  106511. /***/ (function(module, exports) {
  106512. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106513. module.exports = OIMO;
  106514. /***/ }),
  106515. /* 25 */
  106516. /***/ (function(module, exports) {
  106517. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  106518. module.exports = earcut;
  106519. /***/ }),
  106520. /* 26 */
  106521. /***/ (function(module, exports, __webpack_require__) {
  106522. "use strict";
  106523. Object.defineProperty(exports, "__esModule", { value: true });
  106524. var babylonjs_1 = __webpack_require__(0);
  106525. var configuration_1 = __webpack_require__(27);
  106526. var viewerModel_1 = __webpack_require__(4);
  106527. var helper_1 = __webpack_require__(2);
  106528. var viewerLabs_1 = __webpack_require__(29);
  106529. var _1 = __webpack_require__(31);
  106530. var SceneManager = /** @class */ (function () {
  106531. function SceneManager(_viewer) {
  106532. var _this = this;
  106533. this._viewer = _viewer;
  106534. this._animationBlendingEnabled = true;
  106535. this._mainColor = babylonjs_1.Color3.White();
  106536. this._reflectionColor = babylonjs_1.Color3.White();
  106537. this._white = babylonjs_1.Color3.White();
  106538. this._processShadows = true;
  106539. this._groundEnabled = true;
  106540. this._groundMirrorEnabled = false;
  106541. this._defaultRenderingPipelineEnabled = false;
  106542. this._defaultRenderingPipelineShouldBuild = true;
  106543. // default from rendering pipeline
  106544. this._bloomEnabled = false;
  106545. // default from rendering pipeline
  106546. this._fxaaEnabled = false;
  106547. this._focusOnModel = function (model) {
  106548. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  106549. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  106550. var halfSizeVec = sizeVec.scale(0.5);
  106551. var center = boundingInfo.min.add(halfSizeVec);
  106552. _this.camera.setTarget(center);
  106553. _this.camera.alpha = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.alpha) || _this.camera.alpha;
  106554. _this.camera.beta = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.beta) || _this.camera.beta;
  106555. _this.camera.radius = (_this._viewer.configuration.camera && _this._viewer.configuration.camera.radius) || _this.camera.radius;
  106556. };
  106557. this.models = [];
  106558. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  106559. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  106560. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  106561. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  106562. this.onSceneInitObservable = new babylonjs_1.Observable();
  106563. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  106564. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  106565. this._viewer.onEngineInitObservable.add(function () {
  106566. _this._handleHardwareLimitations();
  106567. });
  106568. this.labs = new viewerLabs_1.ViewerLabs(this);
  106569. this.onSceneInitObservable.add(function (scene) {
  106570. scene.registerBeforeRender(function () {
  106571. if (_this.models.length && scene.animatables && scene.animatables.length > 0) {
  106572. // make sure all models are loaded
  106573. if (_this.models.every(function (model) { return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation; }))
  106574. return;
  106575. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106576. var light = _a[_i];
  106577. var generator = light.getShadowGenerator();
  106578. if (generator) {
  106579. // Processing shadows if animates
  106580. var shadowMap = generator.getShadowMap();
  106581. if (shadowMap) {
  106582. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106583. }
  106584. }
  106585. }
  106586. }
  106587. });
  106588. return _this._viewer.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  106589. });
  106590. this._viewer.onModelLoadedObservable.add(function (model) {
  106591. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  106592. var light = _a[_i];
  106593. var generator = light.getShadowGenerator();
  106594. if (generator) {
  106595. // Processing shadows if animates
  106596. var shadowMap = generator.getShadowMap();
  106597. if (shadowMap) {
  106598. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106599. }
  106600. }
  106601. }
  106602. _this._focusOnModel(model);
  106603. });
  106604. }
  106605. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  106606. get: function () {
  106607. return this._defaultRenderingPipeline;
  106608. },
  106609. enumerable: true,
  106610. configurable: true
  106611. });
  106612. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  106613. /**
  106614. * Returns a boolean representing HDR support
  106615. */
  106616. get: function () {
  106617. return this._hdrSupport;
  106618. },
  106619. enumerable: true,
  106620. configurable: true
  106621. });
  106622. Object.defineProperty(SceneManager.prototype, "mainColor", {
  106623. /**
  106624. * Return the main color defined in the configuration.
  106625. */
  106626. get: function () {
  106627. return this._mainColor;
  106628. },
  106629. enumerable: true,
  106630. configurable: true
  106631. });
  106632. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  106633. get: function () {
  106634. return this._reflectionColor;
  106635. },
  106636. enumerable: true,
  106637. configurable: true
  106638. });
  106639. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  106640. get: function () {
  106641. return this._animationBlendingEnabled;
  106642. },
  106643. set: function (value) {
  106644. this.scene.animationPropertiesOverride = this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  106645. this.scene.animationPropertiesOverride.enableBlending = value;
  106646. this._animationBlendingEnabled = value;
  106647. },
  106648. enumerable: true,
  106649. configurable: true
  106650. });
  106651. Object.defineProperty(SceneManager.prototype, "processShadows", {
  106652. /**
  106653. * The flag defining whether shadows are rendered constantly or once.
  106654. */
  106655. get: function () {
  106656. return this._processShadows;
  106657. },
  106658. /**
  106659. * Should shadows be rendered every frame, or only once and stop.
  106660. * This can be used to optimize a scene.
  106661. *
  106662. * Not that the shadows will NOT disapear but will remain in place.
  106663. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  106664. */
  106665. set: function (process) {
  106666. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  106667. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  106668. var light = _a[_i];
  106669. var generator = light.getShadowGenerator();
  106670. if (generator) {
  106671. var shadowMap = generator.getShadowMap();
  106672. if (shadowMap) {
  106673. shadowMap.refreshRate = refreshType;
  106674. }
  106675. }
  106676. }
  106677. this._processShadows = process;
  106678. },
  106679. enumerable: true,
  106680. configurable: true
  106681. });
  106682. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  106683. get: function () {
  106684. return this._groundEnabled;
  106685. },
  106686. set: function (newValue) {
  106687. if (newValue === this._groundEnabled)
  106688. return;
  106689. this._groundEnabled = newValue;
  106690. if (this.environmentHelper && this.environmentHelper.ground) {
  106691. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  106692. }
  106693. },
  106694. enumerable: true,
  106695. configurable: true
  106696. });
  106697. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  106698. /**
  106699. * gets wether the reflection is disabled.
  106700. */
  106701. get: function () {
  106702. return this._groundMirrorEnabled;
  106703. },
  106704. /**
  106705. * sets wether the reflection is disabled.
  106706. */
  106707. set: function (value) {
  106708. if (this._groundMirrorEnabled === value) {
  106709. return;
  106710. }
  106711. this._groundMirrorEnabled = value;
  106712. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  106713. if (value) {
  106714. this.environmentHelper.groundMaterial.reflectionTexture = null;
  106715. }
  106716. else {
  106717. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  106718. }
  106719. }
  106720. },
  106721. enumerable: true,
  106722. configurable: true
  106723. });
  106724. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  106725. get: function () {
  106726. return this._defaultRenderingPipelineEnabled;
  106727. },
  106728. set: function (value) {
  106729. if (value === this._defaultRenderingPipelineEnabled) {
  106730. return;
  106731. }
  106732. this._defaultRenderingPipelineEnabled = value;
  106733. this._rebuildPostprocesses();
  106734. if (this._defaultRenderingPipeline) {
  106735. this._defaultRenderingPipelineShouldBuild = false;
  106736. this._defaultRenderingPipeline.prepare();
  106737. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106738. }
  106739. },
  106740. enumerable: true,
  106741. configurable: true
  106742. });
  106743. /**
  106744. * Sets the engine flags to unlock all babylon features.
  106745. * Can also be configured using the scene.flags configuration object
  106746. */
  106747. SceneManager.prototype.unlockBabylonFeatures = function () {
  106748. this.scene.shadowsEnabled = true;
  106749. this.scene.particlesEnabled = true;
  106750. this.scene.postProcessesEnabled = true;
  106751. this.scene.collisionsEnabled = true;
  106752. this.scene.lightsEnabled = true;
  106753. this.scene.texturesEnabled = true;
  106754. this.scene.lensFlaresEnabled = true;
  106755. this.scene.proceduralTexturesEnabled = true;
  106756. this.scene.renderTargetsEnabled = true;
  106757. this.scene.spritesEnabled = true;
  106758. this.scene.skeletonsEnabled = true;
  106759. this.scene.audioEnabled = true;
  106760. };
  106761. /**
  106762. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  106763. */
  106764. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  106765. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  106766. // if the scen exists, dispose it.
  106767. if (this.scene) {
  106768. this.scene.dispose();
  106769. }
  106770. // create a new scene
  106771. this.scene = new babylonjs_1.Scene(this._viewer.engine);
  106772. // TODO - is this needed, now that Babylon is integrated?
  106773. // set a default PBR material
  106774. if (!sceneConfiguration.defaultMaterial) {
  106775. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  106776. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  106777. defaultMaterial.microSurface = 0.6;
  106778. if (this.scene.defaultMaterial) {
  106779. this.scene.defaultMaterial.dispose();
  106780. }
  106781. this.scene.defaultMaterial = defaultMaterial;
  106782. }
  106783. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  106784. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  106785. this._mainColor = babylonjs_1.Color3.White();
  106786. if (sceneConfiguration.glow) {
  106787. var options = {
  106788. mainTextureFixedSize: 512
  106789. };
  106790. if (typeof sceneConfiguration.glow === 'object') {
  106791. options = sceneConfiguration.glow;
  106792. }
  106793. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  106794. }
  106795. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  106796. };
  106797. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  106798. if (clearModels === void 0) { clearModels = true; }
  106799. if (clearLights === void 0) { clearLights = false; }
  106800. if (clearModels) {
  106801. this.models.forEach(function (m) { return m.dispose(); });
  106802. this.models.length = 0;
  106803. }
  106804. if (clearLights) {
  106805. this.scene.lights.forEach(function (l) { return l.dispose(); });
  106806. }
  106807. };
  106808. /**
  106809. * This will update the scene's configuration, including camera, lights, environment.
  106810. * @param newConfiguration the delta that should be configured. This includes only the changes
  106811. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  106812. */
  106813. SceneManager.prototype.updateConfiguration = function (newConfiguration, globalConfiguration, model) {
  106814. var _this = this;
  106815. if (newConfiguration.lab) {
  106816. if (newConfiguration.lab.assetsRootURL) {
  106817. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  106818. }
  106819. }
  106820. // update scene configuration
  106821. if (newConfiguration.scene) {
  106822. this._configureScene(newConfiguration.scene);
  106823. }
  106824. // optimizer
  106825. if (newConfiguration.optimizer) {
  106826. this._configureOptimizer(newConfiguration.optimizer);
  106827. }
  106828. // configure model
  106829. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  106830. this._configureModel(newConfiguration.model);
  106831. }*/
  106832. // lights
  106833. this._configureLights(newConfiguration.lights, model);
  106834. // environment
  106835. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  106836. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground, model);
  106837. }
  106838. // camera
  106839. this._configureCamera(newConfiguration.camera, model);
  106840. if (newConfiguration.lab) {
  106841. if (newConfiguration.lab.environmentMap) {
  106842. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  106843. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  106844. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  106845. });
  106846. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  106847. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  106848. }
  106849. }
  106850. // rendering piplines
  106851. if (newConfiguration.lab.defaultRenderingPipelines) {
  106852. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  106853. if (typeof pipelineConfig === 'boolean') {
  106854. this.defaultRenderingPipelineEnabled = pipelineConfig;
  106855. }
  106856. else {
  106857. this.defaultRenderingPipelineEnabled = true;
  106858. }
  106859. }
  106860. if (newConfiguration.lab.environmentMainColor) {
  106861. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  106862. this.environmentHelper.setMainColor(mainColor);
  106863. }
  106864. }
  106865. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  106866. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  106867. }
  106868. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  106869. this._defaultRenderingPipelineShouldBuild = false;
  106870. this._defaultRenderingPipeline.prepare();
  106871. }
  106872. };
  106873. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  106874. if (!this.defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._viewer.configuration)) {
  106875. if (this._defaultRenderingPipeline) {
  106876. this._defaultRenderingPipeline.dispose();
  106877. this._defaultRenderingPipeline = null;
  106878. this.scene.autoClearDepthAndStencil = true;
  106879. this.scene.autoClear = true;
  106880. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  106881. }
  106882. return;
  106883. }
  106884. var pipelineConfig = configuration || (this._viewer.configuration.lab && this._viewer.configuration.lab.defaultRenderingPipelines);
  106885. if (pipelineConfig) {
  106886. if (!this._defaultRenderingPipeline) {
  106887. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  106888. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  106889. }
  106890. this.scene.autoClear = false;
  106891. this.scene.autoClearDepthAndStencil = false;
  106892. this._defaultRenderingPipelineShouldBuild = true;
  106893. var bloomEnabled = this._bloomEnabled;
  106894. if (typeof pipelineConfig !== 'boolean') {
  106895. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  106896. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  106897. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  106898. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  106899. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  106900. }
  106901. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  106902. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  106903. }
  106904. };
  106905. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  106906. get: function () {
  106907. return this._bloomEnabled;
  106908. },
  106909. set: function (value) {
  106910. if (this._bloomEnabled === value) {
  106911. return;
  106912. }
  106913. this._bloomEnabled = value;
  106914. this._rebuildPostprocesses();
  106915. if (this._defaultRenderingPipeline) {
  106916. this._defaultRenderingPipelineShouldBuild = false;
  106917. this._defaultRenderingPipeline.prepare();
  106918. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106919. }
  106920. },
  106921. enumerable: true,
  106922. configurable: true
  106923. });
  106924. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  106925. get: function () {
  106926. return this._fxaaEnabled;
  106927. },
  106928. set: function (value) {
  106929. if (this._fxaaEnabled === value) {
  106930. return;
  106931. }
  106932. this._fxaaEnabled = value;
  106933. this._rebuildPostprocesses();
  106934. if (this._defaultRenderingPipeline) {
  106935. this._defaultRenderingPipelineShouldBuild = false;
  106936. this._defaultRenderingPipeline.prepare();
  106937. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  106938. }
  106939. },
  106940. enumerable: true,
  106941. configurable: true
  106942. });
  106943. /**
  106944. * internally configure the scene using the provided configuration.
  106945. * The scene will not be recreated, but just updated.
  106946. * @param sceneConfig the (new) scene configuration
  106947. */
  106948. SceneManager.prototype._configureScene = function (sceneConfig) {
  106949. // sanity check!
  106950. if (!this.scene) {
  106951. return;
  106952. }
  106953. var cc = sceneConfig.clearColor;
  106954. var oldcc = this.scene.clearColor;
  106955. if (cc) {
  106956. if (cc.r !== undefined) {
  106957. oldcc.r = cc.r;
  106958. }
  106959. if (cc.g !== undefined) {
  106960. oldcc.g = cc.g;
  106961. }
  106962. if (cc.b !== undefined) {
  106963. oldcc.b = cc.b;
  106964. }
  106965. if (cc.a !== undefined) {
  106966. oldcc.a = cc.a;
  106967. }
  106968. }
  106969. // image processing configuration - optional.
  106970. if (sceneConfig.imageProcessingConfiguration) {
  106971. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  106972. }
  106973. //animation properties override
  106974. if (sceneConfig.animationPropertiesOverride) {
  106975. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  106976. }
  106977. if (sceneConfig.environmentTexture) {
  106978. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  106979. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  106980. this.scene.environmentTexture.dispose();
  106981. }
  106982. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  106983. this.scene.environmentTexture = environmentTexture;
  106984. }
  106985. }
  106986. if (sceneConfig.debug) {
  106987. this.scene.debugLayer.show();
  106988. }
  106989. else {
  106990. if (this.scene.debugLayer.isVisible()) {
  106991. this.scene.debugLayer.hide();
  106992. }
  106993. }
  106994. if (sceneConfig.disableHdr) {
  106995. this._handleHardwareLimitations(false);
  106996. }
  106997. else {
  106998. this._handleHardwareLimitations(true);
  106999. }
  107000. if (sceneConfig.renderInBackground !== undefined) {
  107001. this._viewer.renderInBackground = !!sceneConfig.renderInBackground;
  107002. }
  107003. if (this.camera && sceneConfig.disableCameraControl) {
  107004. this.camera.detachControl(this._viewer.canvas);
  107005. }
  107006. else if (this.camera && sceneConfig.disableCameraControl === false) {
  107007. this.camera.attachControl(this._viewer.canvas);
  107008. }
  107009. // process mainColor changes:
  107010. if (sceneConfig.mainColor) {
  107011. this._mainColor = this._mainColor || babylonjs_1.Color3.White();
  107012. var mc = sceneConfig.mainColor;
  107013. if (mc.r !== undefined) {
  107014. this._mainColor.r = mc.r;
  107015. }
  107016. if (mc.g !== undefined) {
  107017. this._mainColor.g = mc.g;
  107018. }
  107019. if (mc.b !== undefined) {
  107020. this._mainColor.b = mc.b;
  107021. }
  107022. this._reflectionColor.copyFrom(this.mainColor);
  107023. if (this._viewer.configuration.camera && this._viewer.configuration.camera.exposure) {
  107024. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._viewer.configuration) || 0;
  107025. /*this._mainColor.toLinearSpaceToRef(this._mainColor);
  107026. let exposure = Math.pow(2.0, -(this._viewer.configuration.camera.exposure) * Math.PI);
  107027. this._mainColor.scaleToRef(1 / exposure, this._mainColor);
  107028. let tmpColor = Color3.Lerp(this._white, this._mainColor, environmentTint);
  107029. this._mainColor.copyFrom(tmpColor);*/
  107030. // reflection color
  107031. this._reflectionColor.toLinearSpaceToRef(this._reflectionColor);
  107032. this._reflectionColor.scaleToRef(1 / this._viewer.configuration.camera.exposure, this._reflectionColor);
  107033. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this._reflectionColor, environmentTint);
  107034. this._reflectionColor.copyFrom(tmpColor3);
  107035. }
  107036. //update the environment, if exists
  107037. if (this.environmentHelper) {
  107038. if (this.environmentHelper.groundMaterial) {
  107039. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107040. }
  107041. if (this.environmentHelper.skyboxMaterial) {
  107042. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  107043. }
  107044. }
  107045. }
  107046. if (sceneConfig.defaultMaterial) {
  107047. var conf = sceneConfig.defaultMaterial;
  107048. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  107049. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  107050. this.scene.defaultMaterial.dispose();
  107051. if (conf.materialType === 'standard') {
  107052. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  107053. }
  107054. else {
  107055. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  107056. }
  107057. }
  107058. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  107059. }
  107060. if (sceneConfig.flags) {
  107061. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  107062. }
  107063. this.onSceneConfiguredObservable.notifyObservers({
  107064. sceneManager: this,
  107065. object: this.scene,
  107066. newConfiguration: sceneConfig
  107067. });
  107068. };
  107069. /**
  107070. * Configure the scene optimizer.
  107071. * The existing scene optimizer will be disposed and a new one will be created.
  107072. * @param optimizerConfig the (new) optimizer configuration
  107073. */
  107074. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  107075. var _this = this;
  107076. if (typeof optimizerConfig === 'boolean') {
  107077. if (this.sceneOptimizer) {
  107078. this.sceneOptimizer.stop();
  107079. this.sceneOptimizer.dispose();
  107080. delete this.sceneOptimizer;
  107081. }
  107082. if (optimizerConfig) {
  107083. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  107084. this.sceneOptimizer.start();
  107085. }
  107086. }
  107087. else {
  107088. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  107089. // check for degradation
  107090. if (optimizerConfig.degradation) {
  107091. switch (optimizerConfig.degradation) {
  107092. case "low":
  107093. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  107094. break;
  107095. case "moderate":
  107096. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  107097. break;
  107098. case "hight":
  107099. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  107100. break;
  107101. }
  107102. }
  107103. if (this.sceneOptimizer) {
  107104. this.sceneOptimizer.stop();
  107105. this.sceneOptimizer.dispose();
  107106. }
  107107. if (optimizerConfig.custom) {
  107108. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  107109. if (customOptimizer_1) {
  107110. optimizerOptions.addCustomOptimization(function () {
  107111. return customOptimizer_1(_this._viewer);
  107112. }, function () {
  107113. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  107114. });
  107115. }
  107116. }
  107117. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  107118. this.sceneOptimizer.start();
  107119. }
  107120. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  107121. sceneManager: this,
  107122. object: this.sceneOptimizer,
  107123. newConfiguration: optimizerConfig
  107124. });
  107125. };
  107126. /**
  107127. * configure all models using the configuration.
  107128. * @param modelConfiguration the configuration to use to reconfigure the models
  107129. */
  107130. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  107131. this.models.forEach(model => {
  107132. model.updateConfiguration(modelConfiguration);
  107133. });
  107134. this.onModelsConfiguredObservable.notifyObservers({
  107135. sceneManager: this,
  107136. object: this.models,
  107137. newConfiguration: modelConfiguration
  107138. });
  107139. }*/
  107140. /**
  107141. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  107142. * @param cameraConfig the new camera configuration
  107143. * @param model optionally use the model to configure the camera.
  107144. */
  107145. SceneManager.prototype._configureCamera = function (cameraConfig, model) {
  107146. var _this = this;
  107147. if (cameraConfig === void 0) { cameraConfig = {}; }
  107148. if (!this.scene.activeCamera) {
  107149. var attachControl = true;
  107150. if (this._viewer.configuration.scene && this._viewer.configuration.scene.disableCameraControl) {
  107151. attachControl = false;
  107152. }
  107153. this.scene.createDefaultCamera(true, true, attachControl);
  107154. this.camera = this.scene.activeCamera;
  107155. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  107156. }
  107157. if (cameraConfig.position) {
  107158. var newPosition = this.camera.position.clone();
  107159. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  107160. this.camera.setPosition(newPosition);
  107161. }
  107162. if (cameraConfig.target) {
  107163. var newTarget = this.camera.target.clone();
  107164. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  107165. this.camera.setTarget(newTarget);
  107166. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  107167. this._focusOnModel(this.models[0]);
  107168. }*/
  107169. if (cameraConfig.rotation) {
  107170. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  107171. }
  107172. if (cameraConfig.behaviors) {
  107173. for (var name_1 in cameraConfig.behaviors) {
  107174. if (cameraConfig.behaviors[name_1]) {
  107175. this._setCameraBehavior(cameraConfig.behaviors[name_1]);
  107176. }
  107177. }
  107178. }
  107179. ;
  107180. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  107181. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  107182. });
  107183. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  107184. var sceneDiagonalLenght = sceneDiagonal.length();
  107185. if (isFinite(sceneDiagonalLenght))
  107186. this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  107187. else {
  107188. this.camera.upperRadiusLimit = 10;
  107189. }
  107190. // sanity check!
  107191. if (this.scene.imageProcessingConfiguration) {
  107192. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  107193. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  107194. if (cameraConfig.contrast !== undefined)
  107195. this.scene.imageProcessingConfiguration.contrast = cameraConfig.contrast;
  107196. if (cameraConfig.exposure !== undefined)
  107197. this.scene.imageProcessingConfiguration.exposure = cameraConfig.exposure;
  107198. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!cameraConfig.toneMappingEnabled;
  107199. }
  107200. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  107201. this.onCameraConfiguredObservable.notifyObservers({
  107202. sceneManager: this,
  107203. object: this.camera,
  107204. newConfiguration: cameraConfig,
  107205. model: model
  107206. });
  107207. };
  107208. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration, model) {
  107209. var _this = this;
  107210. if (!skyboxConifguration && !groundConfiguration) {
  107211. if (this.environmentHelper) {
  107212. this.environmentHelper.dispose();
  107213. delete this.environmentHelper;
  107214. }
  107215. ;
  107216. return Promise.resolve(this.scene);
  107217. }
  107218. var options = {
  107219. createGround: !!groundConfiguration && this._groundEnabled,
  107220. createSkybox: !!skyboxConifguration,
  107221. setupImageProcessing: false,
  107222. };
  107223. // will that cause problems with model ground configuration?
  107224. /*if (model) {
  107225. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  107226. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  107227. const halfSizeVec = sizeVec.scale(0.5);
  107228. const center = boundingInfo.min.add(halfSizeVec);
  107229. options.groundYBias = -center.y;
  107230. }*/
  107231. if (groundConfiguration) {
  107232. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107233. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  107234. if (groundSize) {
  107235. options.groundSize = groundSize;
  107236. }
  107237. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  107238. if (groundConfig_1.shadowLevel !== undefined) {
  107239. options.groundShadowLevel = groundConfig_1.shadowLevel;
  107240. }
  107241. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  107242. if (groundConfig_1.texture) {
  107243. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  107244. }
  107245. if (groundConfig_1.color) {
  107246. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  107247. }
  107248. if (groundConfig_1.opacity !== undefined) {
  107249. options.groundOpacity = groundConfig_1.opacity;
  107250. }
  107251. if (groundConfig_1.mirror) {
  107252. options.enableGroundMirror = true;
  107253. // to prevent undefines
  107254. if (typeof groundConfig_1.mirror === "object") {
  107255. if (groundConfig_1.mirror.amount !== undefined)
  107256. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  107257. if (groundConfig_1.mirror.sizeRatio !== undefined)
  107258. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  107259. if (groundConfig_1.mirror.blurKernel !== undefined)
  107260. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  107261. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  107262. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  107263. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  107264. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  107265. if (this._defaultPipelineTextureType !== undefined)
  107266. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  107267. }
  107268. }
  107269. }
  107270. var postInitSkyboxMaterial = false;
  107271. if (skyboxConifguration) {
  107272. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  107273. if (conf.material && conf.material.imageProcessingConfiguration) {
  107274. options.setupImageProcessing = false; // will be configured later manually.
  107275. }
  107276. var skyboxSize = conf.scale;
  107277. if (skyboxSize) {
  107278. options.skyboxSize = skyboxSize;
  107279. }
  107280. options.sizeAuto = !options.skyboxSize;
  107281. if (conf.color) {
  107282. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  107283. }
  107284. if (conf.cubeTexture && conf.cubeTexture.url) {
  107285. if (typeof conf.cubeTexture.url === "string") {
  107286. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  107287. }
  107288. else {
  107289. // init later!
  107290. postInitSkyboxMaterial = true;
  107291. }
  107292. }
  107293. if (conf.material) {
  107294. postInitSkyboxMaterial = true;
  107295. }
  107296. }
  107297. options.setupImageProcessing = false; // TMP
  107298. if (!this.environmentHelper) {
  107299. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107300. }
  107301. else {
  107302. // there might be a new scene! we need to dispose.
  107303. // get the scene used by the envHelper
  107304. var scene = this.environmentHelper.rootMesh.getScene();
  107305. // is it a different scene? Oh no!
  107306. if (scene !== this.scene) {
  107307. this.environmentHelper.dispose();
  107308. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  107309. }
  107310. else {
  107311. this.environmentHelper.updateOptions(options);
  107312. }
  107313. }
  107314. if (this.environmentHelper.rootMesh && this._viewer.configuration.scene && this._viewer.configuration.scene.environmentRotationY !== undefined) {
  107315. this.environmentHelper.rootMesh.rotation.y = this._viewer.configuration.scene.environmentRotationY;
  107316. }
  107317. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  107318. if (this.environmentHelper.groundMaterial && groundConfig && groundConfig.material) {
  107319. //if (!this.environmentHelper.groundMaterial._perceptualColor) {
  107320. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  107321. //}
  107322. //this.environmentHelper.groundMaterial._perceptualColor.copyFrom(this.mainColor);
  107323. // to be configured using the configuration object
  107324. /*this.environmentHelper.groundMaterial.primaryColorHighlightLevel = groundConfig.material.highlightLevel;
  107325. this.environmentHelper.groundMaterial.primaryColorShadowLevel = groundConfig.material.shadowLevel;
  107326. this.environmentHelper.groundMaterial.enableNoise = true;
  107327. if (this.environmentHelper.groundMaterial.diffuseTexture) {
  107328. this.environmentHelper.groundMaterial.diffuseTexture.gammaSpace = true;
  107329. }
  107330. this.environmentHelper.groundMaterial.useRGBColor = false;
  107331. this.environmentHelper.groundMaterial.maxSimultaneousLights = 1;*/
  107332. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  107333. if (this.environmentHelper.groundMirror) {
  107334. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  107335. //let exposure = Math.pow(2.0, -this.configuration.camera.exposure) * Math.PI;
  107336. //mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  107337. // TODO use highlight if required
  107338. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  107339. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  107340. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  107341. this.environmentHelper.groundMirror.clearColor.a = 1;
  107342. if (!this.groundMirrorEnabled) {
  107343. this.environmentHelper.groundMaterial.reflectionTexture = null;
  107344. }
  107345. }
  107346. }
  107347. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  107348. if (skyboxMaterial) {
  107349. skyboxMaterial._perceptualColor = this.mainColor;
  107350. if (postInitSkyboxMaterial) {
  107351. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  107352. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  107353. }
  107354. }
  107355. }
  107356. this._viewer.onModelLoadedObservable.add(function (model) {
  107357. _this._updateGroundMirrorRenderList(model);
  107358. });
  107359. this.onEnvironmentConfiguredObservable.notifyObservers({
  107360. sceneManager: this,
  107361. object: this.environmentHelper,
  107362. newConfiguration: {
  107363. skybox: skyboxConifguration,
  107364. ground: groundConfiguration
  107365. },
  107366. model: model
  107367. });
  107368. };
  107369. /**
  107370. * configure the lights.
  107371. *
  107372. * @param lightsConfiguration the (new) light(s) configuration
  107373. * @param model optionally use the model to configure the camera.
  107374. */
  107375. SceneManager.prototype._configureLights = function (lightsConfiguration, model) {
  107376. var _this = this;
  107377. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  107378. // sanity check!
  107379. if (!Object.keys(lightsConfiguration).length) {
  107380. if (!this.scene.lights.length)
  107381. this.scene.createDefaultLight(true);
  107382. return;
  107383. }
  107384. ;
  107385. var lightsAvailable = this.scene.lights.map(function (light) { return light.name; });
  107386. // compare to the global (!) configuration object and dispose unneeded:
  107387. var lightsToConfigure = Object.keys(this._viewer.configuration.lights || []);
  107388. if (Object.keys(lightsToConfigure).length !== lightsAvailable.length) {
  107389. lightsAvailable.forEach(function (lName) {
  107390. if (lightsToConfigure.indexOf(lName) === -1) {
  107391. _this.scene.getLightByName(lName).dispose();
  107392. }
  107393. });
  107394. }
  107395. Object.keys(lightsConfiguration).forEach(function (name, idx) {
  107396. var lightConfig = { type: 0 };
  107397. if (typeof lightsConfiguration[name] === 'object') {
  107398. lightConfig = lightsConfiguration[name];
  107399. }
  107400. lightConfig.name = name;
  107401. var light;
  107402. // light is not already available
  107403. if (lightsAvailable.indexOf(name) === -1) {
  107404. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107405. if (!constructor)
  107406. return;
  107407. light = constructor();
  107408. }
  107409. else {
  107410. // available? get it from the scene
  107411. light = _this.scene.getLightByName(name);
  107412. lightsAvailable = lightsAvailable.filter(function (ln) { return ln !== name; });
  107413. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  107414. light.dispose();
  107415. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  107416. if (!constructor)
  107417. return;
  107418. light = constructor();
  107419. }
  107420. }
  107421. // if config set the light to false, dispose it.
  107422. if (lightsConfiguration[name] === false) {
  107423. light.dispose();
  107424. return;
  107425. }
  107426. //enabled
  107427. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  107428. light.setEnabled(enabled);
  107429. helper_1.extendClassWithConfig(light, lightConfig);
  107430. //position. Some lights don't support shadows
  107431. if (light instanceof babylonjs_1.ShadowLight) {
  107432. // set default values
  107433. light.shadowMinZ = light.shadowMinZ || 0.2;
  107434. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  107435. if (lightConfig.target) {
  107436. if (light.setDirectionToTarget) {
  107437. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  107438. light.setDirectionToTarget(target);
  107439. }
  107440. }
  107441. else if (lightConfig.direction) {
  107442. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  107443. light.direction = direction;
  107444. }
  107445. var isShadowEnabled = false;
  107446. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107447. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  107448. isShadowEnabled = true;
  107449. }
  107450. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107451. var spotLight = light;
  107452. if (lightConfig.spotAngle !== undefined) {
  107453. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  107454. }
  107455. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  107456. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  107457. }
  107458. isShadowEnabled = true;
  107459. }
  107460. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107461. if (lightConfig.shadowFieldOfView) {
  107462. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  107463. }
  107464. isShadowEnabled = true;
  107465. }
  107466. var shadowGenerator_1 = light.getShadowGenerator();
  107467. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  107468. var bufferSize = lightConfig.shadowBufferSize || 256;
  107469. if (!shadowGenerator_1) {
  107470. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  107471. // TODO blur kernel definition ?
  107472. }
  107473. var blurKernel = _this.getBlurKernel(light, bufferSize);
  107474. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  107475. shadowGenerator_1.blurKernel = blurKernel;
  107476. //override defaults
  107477. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  107478. // add the focues meshes to the shadow list
  107479. _this._viewer.onModelLoadedObservable.add(function (model) {
  107480. _this._updateShadowRenderList(shadowGenerator_1, model);
  107481. });
  107482. //if (model) {
  107483. _this._updateShadowRenderList(shadowGenerator_1, model);
  107484. //}
  107485. }
  107486. else if (shadowGenerator_1) {
  107487. shadowGenerator_1.dispose();
  107488. }
  107489. }
  107490. });
  107491. // render priority
  107492. var globalLightsConfiguration = this._viewer.configuration.lights || {};
  107493. Object.keys(globalLightsConfiguration).sort().forEach(function (name, idx) {
  107494. var configuration = globalLightsConfiguration[name];
  107495. var light = _this.scene.getLightByName(name);
  107496. // sanity check
  107497. if (!light)
  107498. return;
  107499. light.renderPriority = -idx;
  107500. });
  107501. this.onLightsConfiguredObservable.notifyObservers({
  107502. sceneManager: this,
  107503. object: this.scene.lights,
  107504. newConfiguration: lightsConfiguration,
  107505. model: model
  107506. });
  107507. };
  107508. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  107509. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107510. // add the focues meshes to the shadow list
  107511. var shadownMap = shadowGenerator.getShadowMap();
  107512. if (!shadownMap)
  107513. return;
  107514. if (resetList && shadownMap.renderList) {
  107515. shadownMap.renderList.length = 0;
  107516. }
  107517. else {
  107518. shadownMap.renderList = shadownMap.renderList || [];
  107519. }
  107520. for (var index = 0; index < focusMeshes.length; index++) {
  107521. var mesh = focusMeshes[index];
  107522. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  107523. shadownMap.renderList.push(mesh);
  107524. }
  107525. }
  107526. if (!this._shadowGroundPlane) {
  107527. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  107528. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  107529. shadowGroundPlane.useVertexColors = false;
  107530. //material isn't ever used in rendering, just used to set back face culling
  107531. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  107532. shadowGroundPlane.material.backFaceCulling = false;
  107533. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  107534. shadowGroundPlane.freezeWorldMatrix();
  107535. this._shadowGroundPlane = shadowGroundPlane;
  107536. this.scene.removeMesh(shadowGroundPlane);
  107537. }
  107538. }
  107539. else {
  107540. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  107541. this._shadowGroundPlane.dispose();
  107542. this._shadowGroundPlane = null;
  107543. }
  107544. }
  107545. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  107546. shadownMap.renderList.push(this._shadowGroundPlane);
  107547. }
  107548. };
  107549. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  107550. if (this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  107551. var focusMeshes = model ? model.meshes : this.scene.meshes;
  107552. var renderList = this.environmentHelper.groundMirror.renderList;
  107553. if (resetList) {
  107554. renderList.length = 0;
  107555. }
  107556. for (var index = 0; index < focusMeshes.length; index++) {
  107557. var mesh = focusMeshes[index];
  107558. if (renderList.indexOf(mesh) === -1) {
  107559. renderList.push(mesh);
  107560. }
  107561. }
  107562. }
  107563. };
  107564. /**
  107565. * Gets the shadow map blur kernel according to the light configuration.
  107566. * @param light The light used to generate the shadows
  107567. * @param bufferSize The size of the shadow map
  107568. * @return the kernel blur size
  107569. */
  107570. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  107571. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  107572. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  107573. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  107574. }
  107575. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  107576. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  107577. }
  107578. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  107579. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  107580. }
  107581. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  107582. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  107583. return blurKernel;
  107584. };
  107585. /**
  107586. * Alters render settings to reduce features based on hardware feature limitations
  107587. * @param enableHDR Allows the viewer to run in HDR mode.
  107588. */
  107589. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  107590. if (enableHDR === void 0) { enableHDR = true; }
  107591. //flip rendering settings switches based on hardware support
  107592. var maxVaryingRows = this._viewer.engine.getCaps().maxVaryingVectors;
  107593. var maxFragmentSamplers = this._viewer.engine.getCaps().maxTexturesImageUnits;
  107594. //shadows are disabled if there's not enough varyings for a single shadow
  107595. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  107596. this._maxShadows = 0;
  107597. }
  107598. else {
  107599. this._maxShadows = 3;
  107600. }
  107601. //can we render to any >= 16-bit targets (required for HDR)
  107602. var caps = this._viewer.engine.getCaps();
  107603. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  107604. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  107605. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  107606. if (linearHalfFloatTargets) {
  107607. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  107608. this._shadowGeneratorBias = 0.002;
  107609. }
  107610. else if (linearFloatTargets) {
  107611. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  107612. this._shadowGeneratorBias = 0.001;
  107613. }
  107614. else {
  107615. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107616. this._shadowGeneratorBias = 0.001;
  107617. }
  107618. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  107619. };
  107620. /**
  107621. * Dispoe the entire viewer including the scene and the engine
  107622. */
  107623. SceneManager.prototype.dispose = function () {
  107624. // this.onCameraConfiguredObservable.clear();
  107625. this.onEnvironmentConfiguredObservable.clear();
  107626. this.onLightsConfiguredObservable.clear();
  107627. this.onModelsConfiguredObservable.clear();
  107628. this.onSceneConfiguredObservable.clear();
  107629. this.onSceneInitObservable.clear();
  107630. this.onSceneOptimizerConfiguredObservable.clear();
  107631. if (this.sceneOptimizer) {
  107632. this.sceneOptimizer.stop();
  107633. this.sceneOptimizer.dispose();
  107634. }
  107635. if (this.environmentHelper) {
  107636. this.environmentHelper.dispose();
  107637. }
  107638. this.models.forEach(function (model) {
  107639. model.dispose();
  107640. });
  107641. if (this._defaultRenderingPipeline) {
  107642. this._defaultRenderingPipeline.dispose();
  107643. }
  107644. this.models.length = 0;
  107645. this.scene.dispose();
  107646. };
  107647. SceneManager.prototype._setCameraBehavior = function (behaviorConfig, payload) {
  107648. var behavior;
  107649. var type = (typeof behaviorConfig !== "object") ? behaviorConfig : behaviorConfig.type;
  107650. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  107651. // constructing behavior
  107652. switch (type) {
  107653. case 0 /* AUTOROTATION */:
  107654. this.camera.useAutoRotationBehavior = true;
  107655. behavior = this.camera.autoRotationBehavior;
  107656. break;
  107657. case 1 /* BOUNCING */:
  107658. this.camera.useBouncingBehavior = true;
  107659. behavior = this.camera.bouncingBehavior;
  107660. break;
  107661. case 2 /* FRAMING */:
  107662. this.camera.useFramingBehavior = true;
  107663. behavior = this.camera.framingBehavior;
  107664. break;
  107665. default:
  107666. behavior = null;
  107667. break;
  107668. }
  107669. if (behavior) {
  107670. if (typeof behaviorConfig === "object") {
  107671. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  107672. }
  107673. }
  107674. // post attach configuration. Some functionalities require the attached camera.
  107675. switch (type) {
  107676. case 0 /* AUTOROTATION */:
  107677. break;
  107678. case 1 /* BOUNCING */:
  107679. break;
  107680. case 2 /* FRAMING */:
  107681. this._viewer.onModelLoadedObservable.add(function (model) {
  107682. if (config.zoomOnBoundingInfo) {
  107683. behavior.zoomOnMeshHierarchy(model.rootMesh);
  107684. }
  107685. });
  107686. break;
  107687. }
  107688. };
  107689. return SceneManager;
  107690. }());
  107691. exports.SceneManager = SceneManager;
  107692. /***/ }),
  107693. /* 27 */
  107694. /***/ (function(module, exports, __webpack_require__) {
  107695. "use strict";
  107696. Object.defineProperty(exports, "__esModule", { value: true });
  107697. function getConfigurationKey(key, configObject) {
  107698. var splits = key.split('.');
  107699. if (splits.length === 0 || !configObject)
  107700. return false;
  107701. else if (splits.length === 1) {
  107702. if (configObject[key] !== undefined) {
  107703. return configObject[key];
  107704. }
  107705. }
  107706. else {
  107707. var firstKey = splits.shift();
  107708. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  107709. }
  107710. }
  107711. exports.getConfigurationKey = getConfigurationKey;
  107712. /***/ }),
  107713. /* 28 */
  107714. /***/ (function(module, exports, __webpack_require__) {
  107715. "use strict";
  107716. Object.defineProperty(exports, "__esModule", { value: true });
  107717. /**
  107718. * Animation play mode enum - is the animation looping or playing once
  107719. */
  107720. var AnimationPlayMode;
  107721. (function (AnimationPlayMode) {
  107722. AnimationPlayMode[AnimationPlayMode["ONCE"] = 0] = "ONCE";
  107723. AnimationPlayMode[AnimationPlayMode["LOOP"] = 1] = "LOOP";
  107724. })(AnimationPlayMode = exports.AnimationPlayMode || (exports.AnimationPlayMode = {}));
  107725. /**
  107726. * An enum representing the current state of an animation object
  107727. */
  107728. var AnimationState;
  107729. (function (AnimationState) {
  107730. AnimationState[AnimationState["INIT"] = 0] = "INIT";
  107731. AnimationState[AnimationState["PLAYING"] = 1] = "PLAYING";
  107732. AnimationState[AnimationState["PAUSED"] = 2] = "PAUSED";
  107733. AnimationState[AnimationState["STOPPED"] = 3] = "STOPPED";
  107734. AnimationState[AnimationState["ENDED"] = 4] = "ENDED";
  107735. })(AnimationState = exports.AnimationState || (exports.AnimationState = {}));
  107736. /**
  107737. * The different type of easing functions available
  107738. */
  107739. var EasingFunction;
  107740. (function (EasingFunction) {
  107741. EasingFunction[EasingFunction["Linear"] = 0] = "Linear";
  107742. EasingFunction[EasingFunction["CircleEase"] = 1] = "CircleEase";
  107743. EasingFunction[EasingFunction["BackEase"] = 2] = "BackEase";
  107744. EasingFunction[EasingFunction["BounceEase"] = 3] = "BounceEase";
  107745. EasingFunction[EasingFunction["CubicEase"] = 4] = "CubicEase";
  107746. EasingFunction[EasingFunction["ElasticEase"] = 5] = "ElasticEase";
  107747. EasingFunction[EasingFunction["ExponentialEase"] = 6] = "ExponentialEase";
  107748. EasingFunction[EasingFunction["PowerEase"] = 7] = "PowerEase";
  107749. EasingFunction[EasingFunction["QuadraticEase"] = 8] = "QuadraticEase";
  107750. EasingFunction[EasingFunction["QuarticEase"] = 9] = "QuarticEase";
  107751. EasingFunction[EasingFunction["QuinticEase"] = 10] = "QuinticEase";
  107752. EasingFunction[EasingFunction["SineEase"] = 11] = "SineEase";
  107753. })(EasingFunction = exports.EasingFunction || (exports.EasingFunction = {}));
  107754. /**
  107755. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  107756. * native GroupAnimation class.
  107757. */
  107758. var GroupModelAnimation = /** @class */ (function () {
  107759. /**
  107760. * Create a new GroupModelAnimation object using an AnimationGroup object
  107761. * @param _animationGroup The aniamtion group to base the class on
  107762. */
  107763. function GroupModelAnimation(_animationGroup) {
  107764. var _this = this;
  107765. this._animationGroup = _animationGroup;
  107766. this._state = 0 /* INIT */;
  107767. this._playMode = 1 /* LOOP */;
  107768. this._animationGroup.onAnimationEndObservable.add(function () {
  107769. _this.stop();
  107770. _this._state = 4 /* ENDED */;
  107771. });
  107772. }
  107773. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  107774. /**
  107775. * Get the animation's name
  107776. */
  107777. get: function () {
  107778. return this._animationGroup.name;
  107779. },
  107780. enumerable: true,
  107781. configurable: true
  107782. });
  107783. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  107784. /**
  107785. * Get the current animation's state
  107786. */
  107787. get: function () {
  107788. return this._state;
  107789. },
  107790. enumerable: true,
  107791. configurable: true
  107792. });
  107793. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  107794. /**
  107795. * Gets the speed ratio to use for all animations
  107796. */
  107797. get: function () {
  107798. return this._animationGroup.speedRatio;
  107799. },
  107800. /**
  107801. * Sets the speed ratio to use for all animations
  107802. */
  107803. set: function (value) {
  107804. this._animationGroup.speedRatio = value;
  107805. },
  107806. enumerable: true,
  107807. configurable: true
  107808. });
  107809. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  107810. /**
  107811. * Get the max numbers of frame available in the animation group
  107812. *
  107813. * In correlation to an arry, this would be ".length"
  107814. */
  107815. get: function () {
  107816. /*let animationFrames = this._animationGroup.targetedAnimations.map(ta => {
  107817. let keys = ta.animation.getKeys();
  107818. return keys[keys.length - 1].frame;
  107819. });
  107820. return Math.max.apply(null, animationFrames);*/
  107821. return this._animationGroup.to - this._animationGroup.from;
  107822. },
  107823. enumerable: true,
  107824. configurable: true
  107825. });
  107826. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  107827. /**
  107828. * Get the current frame playing right now.
  107829. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  107830. *
  107831. * In correlation to an array, this would be the current index
  107832. */
  107833. get: function () {
  107834. // get the first currentFrame found
  107835. /*for (let i = 0; i < this._animationGroup.animatables.length; ++i) {
  107836. let animatable: Animatable = this._animationGroup.animatables[i];
  107837. let animations = animatable.getAnimations();
  107838. if (!animations || !animations.length) {
  107839. continue;
  107840. }
  107841. for (let idx = 0; idx < animations.length; ++idx) {
  107842. if (animations[idx].currentFrame) {
  107843. return animations[idx].currentFrame;
  107844. }
  107845. }
  107846. }*/
  107847. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  107848. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  107849. }
  107850. else {
  107851. return 0;
  107852. }
  107853. },
  107854. enumerable: true,
  107855. configurable: true
  107856. });
  107857. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  107858. /**
  107859. * Get the FPS value of this animation
  107860. */
  107861. get: function () {
  107862. // get the first currentFrame found
  107863. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  107864. var animatable = this._animationGroup.animatables[i];
  107865. var animations = animatable.getAnimations();
  107866. if (!animations || !animations.length) {
  107867. continue;
  107868. }
  107869. for (var idx = 0; idx < animations.length; ++idx) {
  107870. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  107871. return animations[idx].animation.framePerSecond;
  107872. }
  107873. }
  107874. }
  107875. return 0;
  107876. },
  107877. enumerable: true,
  107878. configurable: true
  107879. });
  107880. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  107881. /**
  107882. * What is the animation'S play mode (looping or played once)
  107883. */
  107884. get: function () {
  107885. return this._playMode;
  107886. },
  107887. /**
  107888. * Set the play mode.
  107889. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  107890. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  107891. */
  107892. set: function (value) {
  107893. if (value === this._playMode) {
  107894. return;
  107895. }
  107896. this._playMode = value;
  107897. if (this.state === 1 /* PLAYING */) {
  107898. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  107899. }
  107900. else {
  107901. this._animationGroup.reset();
  107902. this._state = 0 /* INIT */;
  107903. }
  107904. },
  107905. enumerable: true,
  107906. configurable: true
  107907. });
  107908. /**
  107909. * Reset the animation group
  107910. */
  107911. GroupModelAnimation.prototype.reset = function () {
  107912. this._animationGroup.reset();
  107913. };
  107914. /**
  107915. * Restart the animation group
  107916. */
  107917. GroupModelAnimation.prototype.restart = function () {
  107918. if (this.state === 2 /* PAUSED */)
  107919. this._animationGroup.restart();
  107920. else
  107921. this.start();
  107922. };
  107923. /**
  107924. *
  107925. * @param frameNumber Go to a specific frame in the animation
  107926. */
  107927. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  107928. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  107929. };
  107930. /**
  107931. * Start playing the animation.
  107932. */
  107933. GroupModelAnimation.prototype.start = function () {
  107934. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  107935. if (this._animationGroup.isStarted) {
  107936. this._state = 1 /* PLAYING */;
  107937. }
  107938. };
  107939. /**
  107940. * Pause the animation
  107941. */
  107942. GroupModelAnimation.prototype.pause = function () {
  107943. this._animationGroup.pause();
  107944. this._state = 2 /* PAUSED */;
  107945. };
  107946. /**
  107947. * Stop the animation.
  107948. * This will fail silently if the animation group is already stopped.
  107949. */
  107950. GroupModelAnimation.prototype.stop = function () {
  107951. this._animationGroup.stop();
  107952. if (!this._animationGroup.isStarted) {
  107953. this._state = 3 /* STOPPED */;
  107954. }
  107955. };
  107956. /**
  107957. * Dispose this animation object.
  107958. */
  107959. GroupModelAnimation.prototype.dispose = function () {
  107960. this._animationGroup.dispose();
  107961. };
  107962. return GroupModelAnimation;
  107963. }());
  107964. exports.GroupModelAnimation = GroupModelAnimation;
  107965. /***/ }),
  107966. /* 29 */
  107967. /***/ (function(module, exports, __webpack_require__) {
  107968. "use strict";
  107969. Object.defineProperty(exports, "__esModule", { value: true });
  107970. var environmentSerializer_1 = __webpack_require__(30);
  107971. var babylonjs_1 = __webpack_require__(0);
  107972. var texture_1 = __webpack_require__(11);
  107973. var ViewerLabs = /** @class */ (function () {
  107974. function ViewerLabs(_sceneManager) {
  107975. this._sceneManager = _sceneManager;
  107976. this.environment = {
  107977. //irradiance
  107978. irradiancePolynomialCoefficients: {
  107979. x: new BABYLON.Vector3(0, 0, 0),
  107980. y: new BABYLON.Vector3(0, 0, 0),
  107981. z: new BABYLON.Vector3(0, 0, 0),
  107982. xx: new BABYLON.Vector3(0, 0, 0),
  107983. yy: new BABYLON.Vector3(0, 0, 0),
  107984. zz: new BABYLON.Vector3(0, 0, 0),
  107985. yz: new BABYLON.Vector3(0, 0, 0),
  107986. zx: new BABYLON.Vector3(0, 0, 0),
  107987. xy: new BABYLON.Vector3(0, 0, 0)
  107988. },
  107989. textureIntensityScale: 1.0
  107990. };
  107991. }
  107992. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  107993. var _this = this;
  107994. //@! todo: should loadEnvironment cancel any currently loading environments?
  107995. if (data instanceof ArrayBuffer) {
  107996. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  107997. if (onSuccess)
  107998. onSuccess(this.environment);
  107999. }
  108000. else if (typeof data === 'string') {
  108001. var url = this.getAssetUrl(data);
  108002. this._sceneManager.scene._loadFile(url, function (arrayBuffer) {
  108003. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  108004. if (onSuccess)
  108005. onSuccess(_this.environment);
  108006. }, function (progressEvent) { if (onProgress)
  108007. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  108008. if (onError) {
  108009. onError(e);
  108010. }
  108011. });
  108012. }
  108013. else {
  108014. //data assumed to be PBREnvironment object
  108015. this.environment = data;
  108016. if (onSuccess)
  108017. onSuccess(data);
  108018. }
  108019. };
  108020. /**
  108021. * Applies an `EnvironmentMapConfiguration` to the scene
  108022. * @param environmentMapConfiguration Environment map configuration to apply
  108023. */
  108024. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  108025. if (!this.environment)
  108026. return;
  108027. //set orientation
  108028. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(BABYLON.Axis.Y, rotationY || 0);
  108029. // Add env texture to the scene.
  108030. if (this.environment.specularTexture) {
  108031. // IE crashes when disposing the old texture and setting a new one
  108032. if (!this._sceneManager.scene.environmentTexture) {
  108033. this._sceneManager.scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._sceneManager.scene, this.environment.specularTexture, false, true);
  108034. }
  108035. if (this._sceneManager.scene.environmentTexture) {
  108036. this._sceneManager.scene.environmentTexture.level = this.environment.textureIntensityScale;
  108037. this._sceneManager.scene.environmentTexture.invertZ = true;
  108038. this._sceneManager.scene.environmentTexture.lodLevelInAlpha = true;
  108039. var poly = this._sceneManager.scene.environmentTexture.sphericalPolynomial || new BABYLON.SphericalPolynomial();
  108040. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  108041. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  108042. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  108043. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  108044. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  108045. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  108046. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  108047. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  108048. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  108049. this._sceneManager.scene.environmentTexture.sphericalPolynomial = poly;
  108050. //set orientation
  108051. BABYLON.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._sceneManager.scene.environmentTexture.getReflectionTextureMatrix());
  108052. }
  108053. }
  108054. };
  108055. /**
  108056. * Get an environment asset url by using the configuration if the path is not absolute.
  108057. * @param url Asset url
  108058. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  108059. */
  108060. ViewerLabs.prototype.getAssetUrl = function (url) {
  108061. var returnUrl = url;
  108062. if (url && url.toLowerCase().indexOf("//") === -1) {
  108063. if (!this.assetsRootURL) {
  108064. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  108065. return url;
  108066. }
  108067. returnUrl = this.assetsRootURL + returnUrl;
  108068. }
  108069. return returnUrl;
  108070. };
  108071. return ViewerLabs;
  108072. }());
  108073. exports.ViewerLabs = ViewerLabs;
  108074. /***/ }),
  108075. /* 30 */
  108076. /***/ (function(module, exports, __webpack_require__) {
  108077. "use strict";
  108078. Object.defineProperty(exports, "__esModule", { value: true });
  108079. var babylonjs_1 = __webpack_require__(0);
  108080. var texture_1 = __webpack_require__(11);
  108081. /**
  108082. * A static class proving methods to aid parsing Spectre environment files
  108083. */
  108084. var EnvironmentDeserializer = /** @class */ (function () {
  108085. function EnvironmentDeserializer() {
  108086. }
  108087. /**
  108088. * Parses an arraybuffer into a new PBREnvironment object
  108089. * @param arrayBuffer The arraybuffer of the Spectre environment file
  108090. * @return a PBREnvironment object
  108091. */
  108092. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  108093. var environment = {
  108094. //irradiance
  108095. irradiancePolynomialCoefficients: {
  108096. x: new babylonjs_1.Vector3(0, 0, 0),
  108097. y: new babylonjs_1.Vector3(0, 0, 0),
  108098. z: new babylonjs_1.Vector3(0, 0, 0),
  108099. xx: new babylonjs_1.Vector3(0, 0, 0),
  108100. yy: new babylonjs_1.Vector3(0, 0, 0),
  108101. zz: new babylonjs_1.Vector3(0, 0, 0),
  108102. yz: new babylonjs_1.Vector3(0, 0, 0),
  108103. zx: new babylonjs_1.Vector3(0, 0, 0),
  108104. xy: new babylonjs_1.Vector3(0, 0, 0)
  108105. },
  108106. //specular
  108107. textureIntensityScale: 1.0,
  108108. };
  108109. //read .env
  108110. var littleEndian = false;
  108111. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  108112. var dataView = new DataView(arrayBuffer);
  108113. var pos = 0;
  108114. for (var i = 0; i < magicBytes.length; i++) {
  108115. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  108116. babylonjs_1.Tools.Error('Not a Spectre environment map');
  108117. }
  108118. }
  108119. var version = dataView.getUint16(pos, littleEndian);
  108120. pos += 2;
  108121. if (version !== 1) {
  108122. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  108123. }
  108124. //read json descriptor - collect characters up to null terminator
  108125. var descriptorString = '';
  108126. var charCode = 0x00;
  108127. while ((charCode = dataView.getUint8(pos++))) {
  108128. descriptorString += String.fromCharCode(charCode);
  108129. }
  108130. var descriptor = JSON.parse(descriptorString);
  108131. var payloadPos = pos;
  108132. //irradiance
  108133. switch (descriptor.irradiance.type) {
  108134. case 'irradiance_sh_coefficients_9':
  108135. //irradiance
  108136. var harmonics = descriptor.irradiance;
  108137. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  108138. //harmonics now represent radiance
  108139. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  108140. break;
  108141. default:
  108142. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  108143. }
  108144. //specular
  108145. switch (descriptor.specular.type) {
  108146. case 'cubemap_faces':
  108147. var specularDescriptor = descriptor.specular;
  108148. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  108149. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  108150. var mipmaps = specularDescriptor.mipmaps;
  108151. var imageType = specularDescriptor.imageType;
  108152. for (var l = 0; l < mipmaps.length; l++) {
  108153. var faceRanges = mipmaps[l];
  108154. specularTexture.source[l] = [];
  108155. for (var i = 0; i < 6; i++) {
  108156. var range = faceRanges[i];
  108157. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  108158. switch (imageType) {
  108159. case 'png':
  108160. //construct image element from bytes
  108161. var image = new Image();
  108162. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  108163. image.src = src;
  108164. specularTexture.source[l][i] = image;
  108165. break;
  108166. default:
  108167. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  108168. }
  108169. }
  108170. }
  108171. break;
  108172. default:
  108173. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  108174. }
  108175. return environment;
  108176. };
  108177. /**
  108178. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  108179. * L = (1/pi) * E * rho
  108180. *
  108181. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  108182. * @param harmonics Spherical harmonic coefficients (9)
  108183. */
  108184. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  108185. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  108186. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  108187. // (The pixel shader must apply albedo after texture fetches, etc).
  108188. };
  108189. /**
  108190. * Convert spherical harmonics to spherical polynomial coefficients
  108191. * @param harmonics Spherical harmonic coefficients (9)
  108192. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  108193. */
  108194. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  108195. var rPi = 1 / Math.PI;
  108196. //x
  108197. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  108198. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  108199. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  108200. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  108201. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  108202. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  108203. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  108204. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  108205. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  108206. //xx
  108207. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  108208. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  108209. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  108210. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  108211. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  108212. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  108213. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  108214. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  108215. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  108216. //yz
  108217. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  108218. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  108219. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  108220. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  108221. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  108222. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  108223. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  108224. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  108225. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  108226. };
  108227. /**
  108228. * Multiplies harmonic coefficients in place
  108229. * @param harmonics Spherical harmonic coefficients (9)
  108230. * @param scaleFactor Value to multiply by
  108231. */
  108232. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  108233. harmonics.l00[0] *= scaleFactor;
  108234. harmonics.l00[1] *= scaleFactor;
  108235. harmonics.l00[2] *= scaleFactor;
  108236. harmonics.l1_1[0] *= scaleFactor;
  108237. harmonics.l1_1[1] *= scaleFactor;
  108238. harmonics.l1_1[2] *= scaleFactor;
  108239. harmonics.l10[0] *= scaleFactor;
  108240. harmonics.l10[1] *= scaleFactor;
  108241. harmonics.l10[2] *= scaleFactor;
  108242. harmonics.l11[0] *= scaleFactor;
  108243. harmonics.l11[1] *= scaleFactor;
  108244. harmonics.l11[2] *= scaleFactor;
  108245. harmonics.l2_2[0] *= scaleFactor;
  108246. harmonics.l2_2[1] *= scaleFactor;
  108247. harmonics.l2_2[2] *= scaleFactor;
  108248. harmonics.l2_1[0] *= scaleFactor;
  108249. harmonics.l2_1[1] *= scaleFactor;
  108250. harmonics.l2_1[2] *= scaleFactor;
  108251. harmonics.l20[0] *= scaleFactor;
  108252. harmonics.l20[1] *= scaleFactor;
  108253. harmonics.l20[2] *= scaleFactor;
  108254. harmonics.l21[0] *= scaleFactor;
  108255. harmonics.l21[1] *= scaleFactor;
  108256. harmonics.l21[2] *= scaleFactor;
  108257. harmonics.l22[0] *= scaleFactor;
  108258. harmonics.l22[1] *= scaleFactor;
  108259. harmonics.l22[2] *= scaleFactor;
  108260. };
  108261. return EnvironmentDeserializer;
  108262. }());
  108263. exports.EnvironmentDeserializer = EnvironmentDeserializer;
  108264. /***/ }),
  108265. /* 31 */
  108266. /***/ (function(module, exports, __webpack_require__) {
  108267. "use strict";
  108268. Object.defineProperty(exports, "__esModule", { value: true });
  108269. var extended_1 = __webpack_require__(32);
  108270. var cache = {};
  108271. function getCustomOptimizerByName(name, upgrade) {
  108272. if (!cache[name]) {
  108273. switch (name) {
  108274. case 'extended':
  108275. if (upgrade) {
  108276. return extended_1.extendedUpgrade;
  108277. }
  108278. else {
  108279. return extended_1.extendedDegrade;
  108280. }
  108281. }
  108282. }
  108283. return cache[name];
  108284. }
  108285. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  108286. /***/ }),
  108287. /* 32 */
  108288. /***/ (function(module, exports, __webpack_require__) {
  108289. "use strict";
  108290. Object.defineProperty(exports, "__esModule", { value: true });
  108291. var babylonjs_1 = __webpack_require__(0);
  108292. function extendedUpgrade(viewer) {
  108293. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108294. // if (!this.Scene.BackgroundHelper) {
  108295. // this.Scene.EngineScene.autoClear = false;
  108296. // this.Scene.BackgroundHelper = true;
  108297. // Would require a dedicated clear color;
  108298. // return false;
  108299. // }
  108300. if (viewer.engine.getHardwareScalingLevel() > 1) {
  108301. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, 1);
  108302. viewer.engine.setHardwareScalingLevel(scaling);
  108303. return false;
  108304. }
  108305. if (!viewer.sceneManager.scene.postProcessesEnabled) {
  108306. viewer.sceneManager.scene.postProcessesEnabled = true;
  108307. return false;
  108308. }
  108309. if (!viewer.sceneManager.groundEnabled) {
  108310. viewer.sceneManager.groundEnabled = true;
  108311. return false;
  108312. }
  108313. if (defaultPipeline && !viewer.sceneManager.fxaaEnabled) {
  108314. viewer.sceneManager.fxaaEnabled = true;
  108315. return false;
  108316. }
  108317. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  108318. if (viewer.engine.getHardwareScalingLevel() > hardwareScalingLevel) {
  108319. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  108320. viewer.engine.setHardwareScalingLevel(scaling);
  108321. return false;
  108322. }
  108323. if (!viewer.sceneManager.processShadows) {
  108324. viewer.sceneManager.processShadows = true;
  108325. return false;
  108326. }
  108327. if (defaultPipeline && !viewer.sceneManager.bloomEnabled) {
  108328. viewer.sceneManager.bloomEnabled = true;
  108329. return false;
  108330. }
  108331. if (!viewer.sceneManager.groundMirrorEnabled) {
  108332. viewer.sceneManager.groundMirrorEnabled = true;
  108333. return false;
  108334. }
  108335. return true;
  108336. }
  108337. exports.extendedUpgrade = extendedUpgrade;
  108338. function extendedDegrade(viewer) {
  108339. var defaultPipeline = viewer.sceneManager.defaultRenderingPipeline;
  108340. if (viewer.sceneManager.groundMirrorEnabled) {
  108341. viewer.sceneManager.groundMirrorEnabled = false;
  108342. return false;
  108343. }
  108344. if (defaultPipeline && viewer.sceneManager.bloomEnabled) {
  108345. viewer.sceneManager.bloomEnabled = false;
  108346. return false;
  108347. }
  108348. if (viewer.sceneManager.processShadows) {
  108349. viewer.sceneManager.processShadows = false;
  108350. return false;
  108351. }
  108352. if (viewer.engine.getHardwareScalingLevel() < 1) {
  108353. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1);
  108354. viewer.engine.setHardwareScalingLevel(scaling);
  108355. return false;
  108356. }
  108357. if (defaultPipeline && viewer.sceneManager.fxaaEnabled) {
  108358. viewer.sceneManager.fxaaEnabled = false;
  108359. return false;
  108360. }
  108361. if (viewer.sceneManager.groundEnabled) {
  108362. viewer.sceneManager.groundEnabled = false;
  108363. return false;
  108364. }
  108365. if (viewer.sceneManager.scene.postProcessesEnabled) {
  108366. viewer.sceneManager.scene.postProcessesEnabled = false;
  108367. return false;
  108368. }
  108369. if (viewer.engine.getHardwareScalingLevel() < 1.25) {
  108370. var scaling = babylonjs_1.Scalar.Clamp(viewer.engine.getHardwareScalingLevel() + 0.25, 0, 1.25);
  108371. viewer.engine.setHardwareScalingLevel(scaling);
  108372. return false;
  108373. }
  108374. // if (this.Scene.BackgroundHelper) {
  108375. // this.Scene.EngineScene.autoClear = true;
  108376. // this.Scene.BackgroundHelper = false;
  108377. // Would require a dedicated clear color;
  108378. // return false;
  108379. // }
  108380. return true;
  108381. }
  108382. exports.extendedDegrade = extendedDegrade;
  108383. /***/ }),
  108384. /* 33 */
  108385. /***/ (function(module, exports, __webpack_require__) {
  108386. "use strict";
  108387. Object.defineProperty(exports, "__esModule", { value: true });
  108388. var babylonjs_1 = __webpack_require__(0);
  108389. var helper_1 = __webpack_require__(2);
  108390. var deepmerge = __webpack_require__(1);
  108391. /**
  108392. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  108393. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  108394. */
  108395. var TemplateManager = /** @class */ (function () {
  108396. function TemplateManager(containerElement) {
  108397. this.containerElement = containerElement;
  108398. this.templates = {};
  108399. this.onTemplateInit = new babylonjs_1.Observable();
  108400. this.onTemplateLoaded = new babylonjs_1.Observable();
  108401. this.onTemplateStateChange = new babylonjs_1.Observable();
  108402. this.onAllLoaded = new babylonjs_1.Observable();
  108403. this.onEventTriggered = new babylonjs_1.Observable();
  108404. this.eventManager = new eventManager_1.EventManager(this);
  108405. }
  108406. /**
  108407. * Initialize the template(s) for the viewer. Called bay the Viewer class
  108408. * @param templates the templates to be used to initialize the main template
  108409. */
  108410. TemplateManager.prototype.initTemplate = function (templates) {
  108411. var _this = this;
  108412. var internalInit = function (dependencyMap, name, parentTemplate) {
  108413. //init template
  108414. var template = _this.templates[name];
  108415. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  108416. return internalInit(dependencyMap[childName], childName, template);
  108417. });
  108418. // register the observers
  108419. //template.onLoaded.add(() => {
  108420. var addToParent = function () {
  108421. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  108422. template.appendTo(containingElement);
  108423. _this._checkLoadedState();
  108424. };
  108425. if (parentTemplate && !parentTemplate.parent) {
  108426. parentTemplate.onAppended.add(function () {
  108427. addToParent();
  108428. });
  108429. }
  108430. else {
  108431. addToParent();
  108432. }
  108433. //});
  108434. return template;
  108435. };
  108436. //build the html tree
  108437. return this._buildHTMLTree(templates).then(function (htmlTree) {
  108438. if (_this.templates['main']) {
  108439. internalInit(htmlTree, 'main');
  108440. }
  108441. else {
  108442. _this._checkLoadedState();
  108443. }
  108444. return;
  108445. });
  108446. };
  108447. /**
  108448. *
  108449. * This function will create a simple map with child-dependencies of the template html tree.
  108450. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  108451. * It is expected that the main template will be called main!
  108452. *
  108453. * @param templates
  108454. */
  108455. TemplateManager.prototype._buildHTMLTree = function (templates) {
  108456. var _this = this;
  108457. var promises = Object.keys(templates).map(function (name) {
  108458. // if the template was overridden
  108459. if (!templates[name])
  108460. return Promise.resolve(false);
  108461. // else - we have a template, let's do our job!
  108462. var template = new Template(name, templates[name]);
  108463. template.onLoaded.add(function () {
  108464. _this.onTemplateLoaded.notifyObservers(template);
  108465. });
  108466. template.onStateChange.add(function () {
  108467. _this.onTemplateStateChange.notifyObservers(template);
  108468. });
  108469. _this.onTemplateInit.notifyObservers(template);
  108470. // make sure the global onEventTriggered is called as well
  108471. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  108472. _this.templates[name] = template;
  108473. return template.initPromise;
  108474. });
  108475. return Promise.all(promises).then(function () {
  108476. var templateStructure = {};
  108477. // now iterate through all templates and check for children:
  108478. var buildTree = function (parentObject, name) {
  108479. _this.templates[name].isInHtmlTree = true;
  108480. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  108481. childNodes.forEach(function (element) {
  108482. parentObject[element] = {};
  108483. buildTree(parentObject[element], element);
  108484. });
  108485. };
  108486. if (_this.templates['main']) {
  108487. buildTree(templateStructure, "main");
  108488. }
  108489. return templateStructure;
  108490. });
  108491. };
  108492. /**
  108493. * Get the canvas in the template tree.
  108494. * There must be one and only one canvas inthe template.
  108495. */
  108496. TemplateManager.prototype.getCanvas = function () {
  108497. return this.containerElement.querySelector('canvas');
  108498. };
  108499. /**
  108500. * Get a specific template from the template tree
  108501. * @param name the name of the template to load
  108502. */
  108503. TemplateManager.prototype.getTemplate = function (name) {
  108504. return this.templates[name];
  108505. };
  108506. TemplateManager.prototype._checkLoadedState = function () {
  108507. var _this = this;
  108508. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  108509. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  108510. });
  108511. if (done) {
  108512. this.onAllLoaded.notifyObservers(this);
  108513. }
  108514. };
  108515. /**
  108516. * Dispose the template manager
  108517. */
  108518. TemplateManager.prototype.dispose = function () {
  108519. var _this = this;
  108520. // dispose all templates
  108521. Object.keys(this.templates).forEach(function (template) {
  108522. _this.templates[template].dispose();
  108523. });
  108524. this.templates = {};
  108525. this.eventManager.dispose();
  108526. this.onTemplateInit.clear();
  108527. this.onAllLoaded.clear();
  108528. this.onEventTriggered.clear();
  108529. this.onTemplateLoaded.clear();
  108530. this.onTemplateStateChange.clear();
  108531. };
  108532. return TemplateManager;
  108533. }());
  108534. exports.TemplateManager = TemplateManager;
  108535. var Handlebars = __webpack_require__(34);
  108536. var eventManager_1 = __webpack_require__(35);
  108537. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  108538. Handlebars.registerHelper('eachInMap', function (map, block) {
  108539. var out = '';
  108540. Object.keys(map).map(function (prop) {
  108541. var data = map[prop];
  108542. if (typeof data === 'object') {
  108543. data.id = data.id || prop;
  108544. out += block.fn(data);
  108545. }
  108546. else {
  108547. out += block.fn({ id: prop, value: data });
  108548. }
  108549. });
  108550. return out;
  108551. });
  108552. Handlebars.registerHelper('add', function (a, b) {
  108553. var out = a + b;
  108554. return out;
  108555. });
  108556. Handlebars.registerHelper('eq', function (a, b) {
  108557. var out = (a == b);
  108558. return out;
  108559. });
  108560. Handlebars.registerHelper('or', function (a, b) {
  108561. var out = a || b;
  108562. return out;
  108563. });
  108564. Handlebars.registerHelper('not', function (a) {
  108565. var out = !a;
  108566. return out;
  108567. });
  108568. Handlebars.registerHelper('count', function (map) {
  108569. return map.length;
  108570. });
  108571. Handlebars.registerHelper('gt', function (a, b) {
  108572. var out = a > b;
  108573. return out;
  108574. });
  108575. /**
  108576. * This class represents a single template in the viewer's template tree.
  108577. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  108578. * A template is injected using the template manager in the correct position.
  108579. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  108580. *
  108581. * For further information please refer to the documentation page, https://doc.babylonjs.com
  108582. */
  108583. var Template = /** @class */ (function () {
  108584. function Template(name, _configuration) {
  108585. var _this = this;
  108586. this.name = name;
  108587. this._configuration = _configuration;
  108588. this.onLoaded = new babylonjs_1.Observable();
  108589. this.onAppended = new babylonjs_1.Observable();
  108590. this.onStateChange = new babylonjs_1.Observable();
  108591. this.onEventTriggered = new babylonjs_1.Observable();
  108592. this.loadRequests = [];
  108593. this.isLoaded = false;
  108594. this.isShown = false;
  108595. this.isInHtmlTree = false;
  108596. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  108597. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  108598. if (htmlTemplate) {
  108599. _this._htmlTemplate = htmlTemplate;
  108600. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && _this._configuration.params.noEscape) });
  108601. var config = _this._configuration.params || {};
  108602. _this._rawHtml = compiledTemplate(config);
  108603. try {
  108604. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  108605. }
  108606. catch (e) {
  108607. var test = document.createElement(_this.name);
  108608. test.innerHTML = _this._rawHtml;
  108609. _this._fragment = test;
  108610. }
  108611. _this.isLoaded = true;
  108612. _this.isShown = true;
  108613. _this.onLoaded.notifyObservers(_this);
  108614. }
  108615. return _this;
  108616. });
  108617. }
  108618. /**
  108619. * Some templates have parameters (like background color for example).
  108620. * The parameters are provided to Handlebars which in turn generates the template.
  108621. * This function will update the template with the new parameters
  108622. *
  108623. * @param params the new template parameters
  108624. */
  108625. Template.prototype.updateParams = function (params, append) {
  108626. if (append === void 0) { append = true; }
  108627. if (append) {
  108628. this._configuration.params = deepmerge(this._configuration.params, params);
  108629. }
  108630. else {
  108631. this._configuration.params = params;
  108632. }
  108633. // update the template
  108634. if (this.isLoaded) {
  108635. // this.dispose();
  108636. }
  108637. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  108638. var config = this._configuration.params || {};
  108639. this._rawHtml = compiledTemplate(config);
  108640. try {
  108641. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  108642. }
  108643. catch (e) {
  108644. var test = document.createElement(this.name);
  108645. test.innerHTML = this._rawHtml;
  108646. this._fragment = test;
  108647. }
  108648. if (this.parent) {
  108649. this.appendTo(this.parent, true);
  108650. }
  108651. };
  108652. Object.defineProperty(Template.prototype, "configuration", {
  108653. /**
  108654. * Get the template'S configuration
  108655. */
  108656. get: function () {
  108657. return this._configuration;
  108658. },
  108659. enumerable: true,
  108660. configurable: true
  108661. });
  108662. /**
  108663. * A template can be a parent element for other templates or HTML elements.
  108664. * This function will deliver all child HTML elements of this template.
  108665. */
  108666. Template.prototype.getChildElements = function () {
  108667. var childrenArray = [];
  108668. //Edge and IE don't support frage,ent.children
  108669. var children = this._fragment && this._fragment.children;
  108670. if (!this._fragment) {
  108671. var fragment = this.parent.querySelector(this.name);
  108672. if (fragment) {
  108673. children = fragment.querySelectorAll('*');
  108674. }
  108675. }
  108676. if (!children) {
  108677. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  108678. children = this._fragment.querySelectorAll('*');
  108679. }
  108680. for (var i = 0; i < children.length; ++i) {
  108681. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  108682. }
  108683. return childrenArray;
  108684. };
  108685. /**
  108686. * Appending the template to a parent HTML element.
  108687. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  108688. * @param parent the parent to which the template is added
  108689. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  108690. */
  108691. Template.prototype.appendTo = function (parent, forceRemove) {
  108692. var _this = this;
  108693. if (this.parent) {
  108694. if (forceRemove && this._addedFragment) {
  108695. /*let fragement = this.parent.querySelector(this.name)
  108696. if (fragement)
  108697. this.parent.removeChild(fragement);*/
  108698. this.parent.innerHTML = '';
  108699. }
  108700. else {
  108701. return;
  108702. }
  108703. }
  108704. this.parent = parent;
  108705. if (this._configuration.id) {
  108706. this.parent.id = this._configuration.id;
  108707. }
  108708. if (this._fragment) {
  108709. this.parent.appendChild(this._fragment);
  108710. this._addedFragment = this._fragment;
  108711. }
  108712. else {
  108713. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  108714. }
  108715. // appended only one frame after.
  108716. setTimeout(function () {
  108717. _this._registerEvents();
  108718. _this.onAppended.notifyObservers(_this);
  108719. });
  108720. };
  108721. /**
  108722. * Show the template using the provided visibilityFunction, or natively using display: flex.
  108723. * The provided function returns a promise that should be fullfilled when the element is shown.
  108724. * Since it is a promise async operations are more than possible.
  108725. * See the default viewer for an opacity example.
  108726. * @param visibilityFunction The function to execute to show the template.
  108727. */
  108728. Template.prototype.show = function (visibilityFunction) {
  108729. var _this = this;
  108730. if (this._isHiding)
  108731. return Promise.resolve(this);
  108732. return Promise.resolve().then(function () {
  108733. _this._isShowing = true;
  108734. if (visibilityFunction) {
  108735. return visibilityFunction(_this);
  108736. }
  108737. else {
  108738. // flex? box? should this be configurable easier than the visibilityFunction?
  108739. _this.parent.style.display = 'flex';
  108740. // support old browsers with no flex:
  108741. if (_this.parent.style.display !== 'flex') {
  108742. _this.parent.style.display = '';
  108743. }
  108744. return _this;
  108745. }
  108746. }).then(function () {
  108747. _this.isShown = true;
  108748. _this._isShowing = false;
  108749. _this.onStateChange.notifyObservers(_this);
  108750. return _this;
  108751. });
  108752. };
  108753. /**
  108754. * Hide the template using the provided visibilityFunction, or natively using display: none.
  108755. * The provided function returns a promise that should be fullfilled when the element is hidden.
  108756. * Since it is a promise async operations are more than possible.
  108757. * See the default viewer for an opacity example.
  108758. * @param visibilityFunction The function to execute to show the template.
  108759. */
  108760. Template.prototype.hide = function (visibilityFunction) {
  108761. var _this = this;
  108762. if (this._isShowing)
  108763. return Promise.resolve(this);
  108764. return Promise.resolve().then(function () {
  108765. _this._isHiding = true;
  108766. if (visibilityFunction) {
  108767. return visibilityFunction(_this);
  108768. }
  108769. else {
  108770. // flex? box? should this be configurable easier than the visibilityFunction?
  108771. _this.parent.style.display = 'none';
  108772. return _this;
  108773. }
  108774. }).then(function () {
  108775. _this.isShown = false;
  108776. _this._isHiding = false;
  108777. _this.onStateChange.notifyObservers(_this);
  108778. return _this;
  108779. });
  108780. };
  108781. /**
  108782. * Dispose this template
  108783. */
  108784. Template.prototype.dispose = function () {
  108785. this.onAppended.clear();
  108786. this.onEventTriggered.clear();
  108787. this.onLoaded.clear();
  108788. this.onStateChange.clear();
  108789. this.isLoaded = false;
  108790. // remove from parent
  108791. try {
  108792. this.parent.removeChild(this._fragment);
  108793. }
  108794. catch (e) {
  108795. //noop
  108796. }
  108797. this.loadRequests.forEach(function (request) {
  108798. request.abort();
  108799. });
  108800. if (this._registeredEvents) {
  108801. this._registeredEvents.forEach(function (evt) {
  108802. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  108803. });
  108804. }
  108805. delete this._fragment;
  108806. };
  108807. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  108808. var _this = this;
  108809. if (!templateConfig) {
  108810. return Promise.reject('No templateConfig provided');
  108811. }
  108812. else if (templateConfig.html !== undefined) {
  108813. return Promise.resolve(templateConfig.html);
  108814. }
  108815. else {
  108816. var location_1 = this._getTemplateLocation(templateConfig);
  108817. if (helper_1.isUrl(location_1)) {
  108818. return new Promise(function (resolve, reject) {
  108819. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  108820. resolve(data);
  108821. }, undefined, undefined, false, function (request, error) {
  108822. reject(error);
  108823. });
  108824. _this.loadRequests.push(fileRequest);
  108825. });
  108826. }
  108827. else {
  108828. location_1 = location_1.replace('#', '');
  108829. var element = document.getElementById(location_1);
  108830. if (element) {
  108831. return Promise.resolve(element.innerHTML);
  108832. }
  108833. else {
  108834. return Promise.reject('Template ID not found');
  108835. }
  108836. }
  108837. }
  108838. };
  108839. Template.prototype._registerEvents = function () {
  108840. var _this = this;
  108841. this._registeredEvents = this._registeredEvents || [];
  108842. if (this._registeredEvents.length) {
  108843. // first remove the registered events
  108844. this._registeredEvents.forEach(function (evt) {
  108845. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  108846. });
  108847. }
  108848. if (this._configuration.events) {
  108849. var _loop_1 = function (eventName) {
  108850. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  108851. var functionToFire_1 = function (selector, event) {
  108852. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  108853. };
  108854. // if boolean, set the parent as the event listener
  108855. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  108856. var selector = this_1.parent.id;
  108857. if (selector) {
  108858. selector = '#' + selector;
  108859. }
  108860. else {
  108861. selector = this_1.parent.tagName;
  108862. }
  108863. var binding = functionToFire_1.bind(this_1, selector);
  108864. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  108865. this_1._registeredEvents.push({
  108866. htmlElement: this_1.parent,
  108867. eventName: eventName,
  108868. function: binding
  108869. });
  108870. }
  108871. else if (typeof this_1._configuration.events[eventName] === 'object') {
  108872. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  108873. // strict null checl is working incorrectly, must override:
  108874. var event_1 = this_1._configuration.events[eventName] || {};
  108875. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  108876. if (selector && selector.indexOf('#') !== 0) {
  108877. selector = '#' + selector;
  108878. }
  108879. var htmlElement = _this.parent.querySelector(selector);
  108880. if (htmlElement) {
  108881. var binding = functionToFire_1.bind(_this, selector);
  108882. htmlElement.addEventListener(eventName, binding, false);
  108883. _this._registeredEvents.push({
  108884. htmlElement: htmlElement,
  108885. eventName: eventName,
  108886. function: binding
  108887. });
  108888. }
  108889. });
  108890. }
  108891. }
  108892. };
  108893. var this_1 = this;
  108894. for (var eventName in this._configuration.events) {
  108895. _loop_1(eventName);
  108896. }
  108897. }
  108898. };
  108899. Template.prototype._getTemplateLocation = function (templateConfig) {
  108900. if (!templateConfig || typeof templateConfig === 'string') {
  108901. return templateConfig;
  108902. }
  108903. else {
  108904. return templateConfig.location;
  108905. }
  108906. };
  108907. return Template;
  108908. }());
  108909. exports.Template = Template;
  108910. /***/ }),
  108911. /* 34 */
  108912. /***/ (function(module, exports, __webpack_require__) {
  108913. /**!
  108914. @license
  108915. handlebars v4.0.11
  108916. Copyright (C) 2011-2017 by Yehuda Katz
  108917. Permission is hereby granted, free of charge, to any person obtaining a copy
  108918. of this software and associated documentation files (the "Software"), to deal
  108919. in the Software without restriction, including without limitation the rights
  108920. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  108921. copies of the Software, and to permit persons to whom the Software is
  108922. furnished to do so, subject to the following conditions:
  108923. The above copyright notice and this permission notice shall be included in
  108924. all copies or substantial portions of the Software.
  108925. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  108926. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  108927. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  108928. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  108929. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  108930. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  108931. THE SOFTWARE.
  108932. */
  108933. !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],
  108934. 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){
  108935. 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"]}])});
  108936. /***/ }),
  108937. /* 35 */
  108938. /***/ (function(module, exports, __webpack_require__) {
  108939. "use strict";
  108940. Object.defineProperty(exports, "__esModule", { value: true });
  108941. /**
  108942. * The EventManager is in charge of registering user interctions with the viewer.
  108943. * It is used in the TemplateManager
  108944. */
  108945. var EventManager = /** @class */ (function () {
  108946. function EventManager(_templateManager) {
  108947. var _this = this;
  108948. this._templateManager = _templateManager;
  108949. this._callbacksContainer = {};
  108950. this._templateManager.onEventTriggered.add(function (eventData) {
  108951. _this._eventTriggered(eventData);
  108952. });
  108953. }
  108954. /**
  108955. * Register a new callback to a specific template.
  108956. * The best example for the usage can be found in the DefaultViewer
  108957. *
  108958. * @param templateName the templateName to register the event to
  108959. * @param callback The callback to be executed
  108960. * @param eventType the type of event to register
  108961. * @param selector an optional selector. if not defined the parent object in the template will be selected
  108962. */
  108963. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  108964. if (!this._callbacksContainer[templateName]) {
  108965. this._callbacksContainer[templateName] = [];
  108966. }
  108967. this._callbacksContainer[templateName].push({
  108968. eventType: eventType,
  108969. callback: callback,
  108970. selector: selector
  108971. });
  108972. };
  108973. /**
  108974. * This will remove a registered event from the defined template.
  108975. * Each one of the variables apart from the template name are optional, but one must be provided.
  108976. *
  108977. * @param templateName the templateName
  108978. * @param callback the callback to remove (optional)
  108979. * @param eventType the event type to remove (optional)
  108980. * @param selector the selector from which to remove the event (optional)
  108981. */
  108982. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  108983. var callbackDefs = this._callbacksContainer[templateName] || [];
  108984. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  108985. };
  108986. EventManager.prototype._eventTriggered = function (data) {
  108987. var templateName = data.template.name;
  108988. var eventType = data.event.type;
  108989. var selector = data.selector;
  108990. var callbackDefs = this._callbacksContainer[templateName] || [];
  108991. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  108992. callbackDef.callback(data);
  108993. });
  108994. };
  108995. /**
  108996. * Dispose the event manager
  108997. */
  108998. EventManager.prototype.dispose = function () {
  108999. this._callbacksContainer = {};
  109000. };
  109001. return EventManager;
  109002. }());
  109003. exports.EventManager = EventManager;
  109004. /***/ }),
  109005. /* 36 */
  109006. /***/ (function(module, exports, __webpack_require__) {
  109007. "use strict";
  109008. Object.defineProperty(exports, "__esModule", { value: true });
  109009. var mappers_1 = __webpack_require__(3);
  109010. var types_1 = __webpack_require__(37);
  109011. var deepmerge = __webpack_require__(1);
  109012. var babylonjs_1 = __webpack_require__(0);
  109013. /**
  109014. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  109015. * parse the object and return a conform ViewerConfiguration.
  109016. * It is a private member of the scene.
  109017. */
  109018. var ConfigurationLoader = /** @class */ (function () {
  109019. function ConfigurationLoader(_enableCache) {
  109020. if (_enableCache === void 0) { _enableCache = false; }
  109021. this._enableCache = _enableCache;
  109022. this._configurationCache = {};
  109023. this._loadRequests = [];
  109024. }
  109025. /**
  109026. * load a configuration object that is defined in the initial configuration provided.
  109027. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  109028. *
  109029. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  109030. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  109031. * @returns A promise that delivers the extended viewer configuration, when done.
  109032. */
  109033. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  109034. var _this = this;
  109035. if (initConfig === void 0) { initConfig = {}; }
  109036. var loadedConfig = deepmerge({}, initConfig);
  109037. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  109038. loadedConfig = deepmerge(extendedConfiguration, loadedConfig);
  109039. if (loadedConfig.configuration) {
  109040. var mapperType_1 = "json";
  109041. return Promise.resolve().then(function () {
  109042. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  109043. // a file to load
  109044. var url = '';
  109045. if (typeof loadedConfig.configuration === "string") {
  109046. url = loadedConfig.configuration;
  109047. }
  109048. // if configuration is an object
  109049. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  109050. url = loadedConfig.configuration.url;
  109051. var type = loadedConfig.configuration.mapper;
  109052. // empty string?
  109053. if (!type) {
  109054. // load mapper type from filename / url
  109055. type = loadedConfig.configuration.url.split('.').pop();
  109056. }
  109057. mapperType_1 = type || mapperType_1;
  109058. }
  109059. return _this._loadFile(url);
  109060. }
  109061. else {
  109062. if (typeof loadedConfig.configuration === "object") {
  109063. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  109064. return loadedConfig.configuration.payload || {};
  109065. }
  109066. return {};
  109067. }
  109068. }).then(function (data) {
  109069. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  109070. var parsed = mapper.map(data);
  109071. var merged = deepmerge(loadedConfig, parsed);
  109072. if (callback)
  109073. callback(merged);
  109074. return merged;
  109075. });
  109076. }
  109077. else {
  109078. if (callback)
  109079. callback(loadedConfig);
  109080. return Promise.resolve(loadedConfig);
  109081. }
  109082. };
  109083. /**
  109084. * Dispose the configuration loader. This will cancel file requests, if active.
  109085. */
  109086. ConfigurationLoader.prototype.dispose = function () {
  109087. this._loadRequests.forEach(function (request) {
  109088. request.abort();
  109089. });
  109090. this._loadRequests.length = 0;
  109091. };
  109092. ConfigurationLoader.prototype._loadFile = function (url) {
  109093. var _this = this;
  109094. var cacheReference = this._configurationCache;
  109095. if (this._enableCache && cacheReference[url]) {
  109096. return Promise.resolve(cacheReference[url]);
  109097. }
  109098. return new Promise(function (resolve, reject) {
  109099. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  109100. var idx = _this._loadRequests.indexOf(fileRequest);
  109101. if (idx !== -1)
  109102. _this._loadRequests.splice(idx, 1);
  109103. if (_this._enableCache)
  109104. cacheReference[url] = result;
  109105. resolve(result);
  109106. }, undefined, undefined, false, function (request, error) {
  109107. var idx = _this._loadRequests.indexOf(fileRequest);
  109108. if (idx !== -1)
  109109. _this._loadRequests.splice(idx, 1);
  109110. reject(error);
  109111. });
  109112. _this._loadRequests.push(fileRequest);
  109113. });
  109114. };
  109115. return ConfigurationLoader;
  109116. }());
  109117. exports.ConfigurationLoader = ConfigurationLoader;
  109118. /***/ }),
  109119. /* 37 */
  109120. /***/ (function(module, exports, __webpack_require__) {
  109121. "use strict";
  109122. Object.defineProperty(exports, "__esModule", { value: true });
  109123. var minimal_1 = __webpack_require__(38);
  109124. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  109125. var default_1 = __webpack_require__(39);
  109126. exports.defaultConfiguration = default_1.defaultConfiguration;
  109127. var extended_1 = __webpack_require__(46);
  109128. var shadowLight_1 = __webpack_require__(47);
  109129. var environmentMap_1 = __webpack_require__(48);
  109130. var deepmerge = __webpack_require__(1);
  109131. var getConfigurationType = function (types) {
  109132. var config = {};
  109133. var typesSeparated = types.split(",");
  109134. typesSeparated.forEach(function (type) {
  109135. switch (type.trim()) {
  109136. case 'environmentMap':
  109137. config = deepmerge(config, environmentMap_1.environmentMapConfiguration);
  109138. break;
  109139. case 'shadowDirectionalLight':
  109140. config = deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  109141. break;
  109142. case 'shadowSpotLight':
  109143. config = deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  109144. break;
  109145. case 'extended':
  109146. config = deepmerge(config, extended_1.extendedConfiguration);
  109147. break;
  109148. case 'minimal':
  109149. config = deepmerge(config, minimal_1.minimalConfiguration);
  109150. break;
  109151. case 'none':
  109152. break;
  109153. case 'default':
  109154. default:
  109155. config = deepmerge(config, default_1.defaultConfiguration);
  109156. break;
  109157. }
  109158. if (config.extends) {
  109159. config = deepmerge(config, getConfigurationType(config.extends));
  109160. }
  109161. });
  109162. return config;
  109163. };
  109164. exports.getConfigurationType = getConfigurationType;
  109165. /***/ }),
  109166. /* 38 */
  109167. /***/ (function(module, exports, __webpack_require__) {
  109168. "use strict";
  109169. Object.defineProperty(exports, "__esModule", { value: true });
  109170. exports.minimalConfiguration = {
  109171. version: "0.1",
  109172. templates: {
  109173. main: {
  109174. html: __webpack_require__(12)
  109175. },
  109176. loadingScreen: {
  109177. html: __webpack_require__(13),
  109178. params: {
  109179. backgroundColor: "#000000",
  109180. loadingImage: __webpack_require__(14) //"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"
  109181. }
  109182. },
  109183. viewer: {
  109184. html: __webpack_require__(15),
  109185. },
  109186. overlay: {
  109187. html: __webpack_require__(16),
  109188. params: {
  109189. closeImage: __webpack_require__(17),
  109190. closeText: 'Close'
  109191. }
  109192. },
  109193. error: {
  109194. html: __webpack_require__(18)
  109195. }
  109196. },
  109197. engine: {
  109198. antialiasing: true
  109199. }
  109200. };
  109201. /***/ }),
  109202. /* 39 */
  109203. /***/ (function(module, exports, __webpack_require__) {
  109204. "use strict";
  109205. Object.defineProperty(exports, "__esModule", { value: true });
  109206. exports.defaultConfiguration = {
  109207. version: "3.2.0-alpha4",
  109208. templates: {
  109209. main: {
  109210. html: __webpack_require__(12),
  109211. params: {
  109212. babylonFont: __webpack_require__(40),
  109213. noEscape: true
  109214. }
  109215. },
  109216. fillContainer: {
  109217. html: __webpack_require__(41),
  109218. params: {
  109219. disable: false
  109220. }
  109221. },
  109222. loadingScreen: {
  109223. html: __webpack_require__(13),
  109224. params: {
  109225. backgroundColor: "#000000",
  109226. loadingImage: __webpack_require__(14)
  109227. }
  109228. },
  109229. viewer: {
  109230. html: __webpack_require__(15)
  109231. },
  109232. navBar: {
  109233. html: __webpack_require__(42),
  109234. params: {
  109235. speedList: {
  109236. "0.5x": "0.5",
  109237. "1.0x": "1.0",
  109238. "1.5x": "1.5",
  109239. "2.0x": "2.0",
  109240. },
  109241. logoImage: __webpack_require__(43),
  109242. logoText: 'BabylonJS',
  109243. logoLink: 'https://babylonjs.com',
  109244. hideHelp: true,
  109245. disableOnFullscreen: true,
  109246. },
  109247. events: {
  109248. pointerdown: {
  109249. 'navbar-control': true,
  109250. 'help-button': true
  109251. },
  109252. input: {
  109253. 'progress-wrapper': true
  109254. },
  109255. pointerup: {
  109256. 'progress-wrapper': true
  109257. }
  109258. }
  109259. },
  109260. overlay: {
  109261. html: __webpack_require__(16),
  109262. params: {
  109263. closeImage: __webpack_require__(17),
  109264. closeText: 'Close'
  109265. }
  109266. },
  109267. help: {
  109268. html: __webpack_require__(44)
  109269. },
  109270. share: {
  109271. html: __webpack_require__(45)
  109272. },
  109273. error: {
  109274. html: __webpack_require__(18)
  109275. }
  109276. },
  109277. camera: {
  109278. behaviors: {
  109279. autoRotate: {
  109280. type: 0
  109281. },
  109282. framing: {
  109283. type: 2,
  109284. zoomOnBoundingInfo: true,
  109285. zoomStopsAnimation: false
  109286. },
  109287. bouncing: {
  109288. type: 1
  109289. }
  109290. },
  109291. wheelPrecision: 200,
  109292. },
  109293. skybox: {},
  109294. ground: {
  109295. receiveShadows: true
  109296. },
  109297. engine: {
  109298. antialiasing: true
  109299. },
  109300. scene: {
  109301. /*imageProcessingConfiguration: {
  109302. exposure: 1.4,
  109303. contrast: 1.66,
  109304. toneMappingEnabled: true
  109305. }*/
  109306. }
  109307. };
  109308. /***/ }),
  109309. /* 40 */
  109310. /***/ (function(module, exports) {
  109311. 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=="
  109312. /***/ }),
  109313. /* 41 */
  109314. /***/ (function(module, exports) {
  109315. 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>";
  109316. /***/ }),
  109317. /* 42 */
  109318. /***/ (function(module, exports) {
  109319. 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>";
  109320. /***/ }),
  109321. /* 43 */
  109322. /***/ (function(module, exports) {
  109323. 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="
  109324. /***/ }),
  109325. /* 44 */
  109326. /***/ (function(module, exports) {
  109327. module.exports = "HELP";
  109328. /***/ }),
  109329. /* 45 */
  109330. /***/ (function(module, exports) {
  109331. module.exports = "SHARE";
  109332. /***/ }),
  109333. /* 46 */
  109334. /***/ (function(module, exports, __webpack_require__) {
  109335. "use strict";
  109336. Object.defineProperty(exports, "__esModule", { value: true });
  109337. var babylonjs_1 = __webpack_require__(0);
  109338. exports.extendedConfiguration = {
  109339. version: "3.2.0",
  109340. extends: "default",
  109341. camera: {
  109342. exposure: 3.034578,
  109343. fov: 0.7853981633974483,
  109344. contrast: 1.6,
  109345. toneMappingEnabled: true,
  109346. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  109347. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  109348. behaviors: {
  109349. framing: {
  109350. type: 2,
  109351. mode: 0,
  109352. positionScale: 0.5,
  109353. defaultElevation: 0.2617993877991494,
  109354. elevationReturnWaitTime: 3000,
  109355. elevationReturnTime: 2000,
  109356. framingTime: 500,
  109357. zoomStopsAnimation: false,
  109358. radiusScale: 0.866
  109359. },
  109360. autoRotate: {
  109361. type: 0,
  109362. idleRotationWaitTime: 4000,
  109363. idleRotationSpeed: 0.17453292519943295,
  109364. idleRotationSpinupTime: 2500,
  109365. zoomStopsAnimation: false
  109366. },
  109367. bouncing: {
  109368. type: 1,
  109369. lowerRadiusTransitionRange: 0.05,
  109370. upperRadiusTransitionRange: -0.2
  109371. }
  109372. },
  109373. upperRadiusLimit: 5,
  109374. lowerRadiusLimit: 0.5,
  109375. frameOnModelLoad: true,
  109376. framingElevation: 0.2617993877991494,
  109377. framingRotation: 1.5707963267948966,
  109378. radius: 2,
  109379. alpha: 1.5708,
  109380. beta: Math.PI * 0.5 - 0.2618,
  109381. wheelPrecision: 300,
  109382. minZ: 0.1,
  109383. maxZ: 50,
  109384. fovMode: 0,
  109385. pinchPrecision: 1500,
  109386. panningSensibility: 3000
  109387. },
  109388. lights: {
  109389. light0: {
  109390. type: 0,
  109391. frustumEdgeFalloff: 0,
  109392. intensity: 7,
  109393. intensityMode: 0,
  109394. radius: 0.6,
  109395. range: 0.6,
  109396. spotAngle: 60,
  109397. diffuse: {
  109398. r: 1,
  109399. g: 1,
  109400. b: 1
  109401. },
  109402. position: {
  109403. x: -2,
  109404. y: 2.5,
  109405. z: 2
  109406. },
  109407. target: {
  109408. x: 0,
  109409. y: 0,
  109410. z: 0
  109411. },
  109412. enabled: true,
  109413. shadowEnabled: true,
  109414. shadowBufferSize: 512,
  109415. shadowMinZ: 1,
  109416. shadowMaxZ: 10,
  109417. shadowFieldOfView: 60,
  109418. shadowFrustumSize: 2,
  109419. shadowConfig: {
  109420. useBlurCloseExponentialShadowMap: true,
  109421. useKernelBlur: true,
  109422. blurScale: 1.0,
  109423. bias: 0.001,
  109424. depthScale: 50 * (10 - 1),
  109425. frustumEdgeFalloff: 0
  109426. }
  109427. },
  109428. light1: {
  109429. type: 0,
  109430. frustumEdgeFalloff: 0,
  109431. intensity: 7,
  109432. intensityMode: 0,
  109433. radius: 0.4,
  109434. range: 0.4,
  109435. spotAngle: 57,
  109436. diffuse: {
  109437. r: 1,
  109438. g: 1,
  109439. b: 1
  109440. },
  109441. position: {
  109442. x: 4,
  109443. y: 3,
  109444. z: -0.5
  109445. },
  109446. target: {
  109447. x: 0,
  109448. y: 0,
  109449. z: 0
  109450. },
  109451. enabled: true,
  109452. shadowEnabled: false,
  109453. shadowBufferSize: 512,
  109454. shadowMinZ: 0.2,
  109455. shadowMaxZ: 10,
  109456. shadowFieldOfView: 28,
  109457. shadowFrustumSize: 2
  109458. },
  109459. light2: {
  109460. type: 0,
  109461. frustumEdgeFalloff: 0,
  109462. intensity: 1,
  109463. intensityMode: 0,
  109464. radius: 0.5,
  109465. range: 0.5,
  109466. spotAngle: 42.85,
  109467. diffuse: {
  109468. r: 0.8,
  109469. g: 0.8,
  109470. b: 0.8
  109471. },
  109472. position: {
  109473. x: -1,
  109474. y: 3,
  109475. z: -3
  109476. },
  109477. target: {
  109478. x: 0,
  109479. y: 0,
  109480. z: 0
  109481. },
  109482. enabled: true,
  109483. shadowEnabled: false,
  109484. shadowBufferSize: 512,
  109485. shadowMinZ: 0.2,
  109486. shadowMaxZ: 10,
  109487. shadowFieldOfView: 45,
  109488. shadowFrustumSize: 2
  109489. }
  109490. },
  109491. ground: {
  109492. shadowLevel: 0.9,
  109493. texture: "Ground_2.0-1024.png",
  109494. material: {
  109495. primaryColorHighlightLevel: 0.035,
  109496. primaryColorShadowLevel: 0,
  109497. enableNoise: true,
  109498. useRGBColor: false,
  109499. maxSimultaneousLights: 1,
  109500. diffuseTexture: {
  109501. gammaSpace: true
  109502. }
  109503. },
  109504. opacity: 1,
  109505. mirror: false,
  109506. receiveShadows: true,
  109507. size: 5
  109508. },
  109509. skybox: {
  109510. scale: 11,
  109511. cubeTexture: {
  109512. url: "Skybox_2.0-256.dds"
  109513. },
  109514. material: {
  109515. primaryColorHighlightLevel: 0.03,
  109516. primaryColorShadowLevel: 0.03,
  109517. enableNoise: true,
  109518. useRGBColor: false,
  109519. reflectionTexture: {
  109520. gammaSpace: true
  109521. }
  109522. }
  109523. },
  109524. engine: {
  109525. renderInBackground: true
  109526. },
  109527. scene: {
  109528. flags: {
  109529. shadowsEnabled: true,
  109530. particlesEnabled: false,
  109531. collisionsEnabled: false,
  109532. lightsEnabled: true,
  109533. texturesEnabled: true,
  109534. lensFlaresEnabled: false,
  109535. proceduralTexturesEnabled: false,
  109536. renderTargetsEnabled: true,
  109537. spritesEnabled: false,
  109538. skeletonsEnabled: true,
  109539. audioEnabled: false,
  109540. },
  109541. defaultMaterial: {
  109542. materialType: 'pbr',
  109543. reflectivityColor: {
  109544. r: 0.1,
  109545. g: 0.1,
  109546. b: 0.1
  109547. },
  109548. microSurface: 0.6
  109549. },
  109550. clearColor: {
  109551. r: 0.9,
  109552. g: 0.9,
  109553. b: 0.9,
  109554. a: 1.0
  109555. },
  109556. imageProcessingConfiguration: {
  109557. vignetteCentreX: 0,
  109558. vignetteCentreY: 0,
  109559. vignetteColor: {
  109560. r: 0.086,
  109561. g: 0.184,
  109562. b: 0.259,
  109563. a: 1
  109564. },
  109565. vignetteWeight: 0.855,
  109566. vignetteStretch: 0.5,
  109567. vignetteBlendMode: 0,
  109568. vignetteCameraFov: 0.7853981633974483,
  109569. isEnabled: true,
  109570. colorCurves: {
  109571. shadowsHue: 0,
  109572. shadowsDensity: 0,
  109573. shadowsSaturation: 0,
  109574. shadowsExposure: 0,
  109575. midtonesHue: 0,
  109576. midtonesDensity: 0,
  109577. midtonesExposure: 0,
  109578. midtonesSaturation: 0,
  109579. highlightsHue: 0,
  109580. highlightsDensity: 0,
  109581. highlightsExposure: 0,
  109582. highlightsSaturation: 0
  109583. }
  109584. },
  109585. mainColor: {
  109586. r: 0.8823529411764706,
  109587. g: 0.8823529411764706,
  109588. b: 0.8823529411764706
  109589. }
  109590. },
  109591. loaderPlugins: {
  109592. extendedMaterial: true,
  109593. applyMaterialConfig: true,
  109594. msftLod: true,
  109595. telemetry: true
  109596. },
  109597. model: {
  109598. rotationOffsetAxis: {
  109599. x: 0,
  109600. y: -1,
  109601. z: 0
  109602. },
  109603. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  109604. material: {
  109605. directEnabled: true,
  109606. directIntensity: 0.884,
  109607. emissiveIntensity: 1.04,
  109608. environmentIntensity: 0.6
  109609. },
  109610. entryAnimation: {
  109611. scaling: {
  109612. x: 0,
  109613. y: 0,
  109614. z: 0
  109615. },
  109616. time: 0.5,
  109617. easingFunction: 4,
  109618. easingMode: 1
  109619. },
  109620. exitAnimation: {
  109621. scaling: {
  109622. x: 0,
  109623. y: 0,
  109624. z: 0
  109625. },
  109626. time: 0.5,
  109627. easingFunction: 4,
  109628. easingMode: 1
  109629. },
  109630. normalize: true,
  109631. castShadow: true,
  109632. receiveShadows: true
  109633. },
  109634. lab: {
  109635. assetsRootURL: '/assets/environment/',
  109636. environmentMap: {
  109637. texture: "EnvMap_2.0-256.env",
  109638. rotationY: 3,
  109639. tintLevel: 0.4
  109640. },
  109641. defaultRenderingPipelines: {
  109642. bloomEnabled: true,
  109643. bloomThreshold: 1.0,
  109644. fxaaEnabled: true,
  109645. bloomWeight: 0.05
  109646. }
  109647. }
  109648. };
  109649. /***/ }),
  109650. /* 47 */
  109651. /***/ (function(module, exports, __webpack_require__) {
  109652. "use strict";
  109653. Object.defineProperty(exports, "__esModule", { value: true });
  109654. exports.shadowDirectionalLightConfiguration = {
  109655. model: {
  109656. receiveShadows: true,
  109657. castShadow: true
  109658. },
  109659. ground: {
  109660. receiveShadows: true
  109661. },
  109662. lights: {
  109663. shadowDirectionalLight: {
  109664. type: 1,
  109665. shadowEnabled: true,
  109666. target: { x: 0, y: 0, z: 0.5 },
  109667. position: { x: 1.49, y: 2.39, z: -1.33 },
  109668. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  109669. intensity: 4.887,
  109670. intensityMode: 0,
  109671. shadowBufferSize: 1024,
  109672. shadowFrustumSize: 6.0,
  109673. shadowFieldOfView: 50.977,
  109674. shadowMinZ: 0.1,
  109675. shadowMaxZ: 10.0,
  109676. shadowConfig: {
  109677. blurKernel: 32,
  109678. useBlurCloseExponentialShadowMap: true
  109679. }
  109680. }
  109681. }
  109682. };
  109683. exports.shadowSpotlLightConfiguration = {
  109684. model: {
  109685. receiveShadows: true,
  109686. castShadow: true
  109687. },
  109688. ground: {
  109689. receiveShadows: true
  109690. },
  109691. lights: {
  109692. shadowSpotLight: {
  109693. type: 2,
  109694. intensity: 2,
  109695. shadowEnabled: true,
  109696. target: { x: 0, y: 0, z: 0.5 },
  109697. position: { x: 0, y: 3.5, z: 3.7 },
  109698. angle: 1,
  109699. shadowOrthoScale: 0.5,
  109700. shadowBufferSize: 1024,
  109701. shadowMinZ: 0.1,
  109702. shadowMaxZ: 50.0,
  109703. shadowConfig: {
  109704. frustumEdgeFalloff: 0.5,
  109705. blurKernel: 32,
  109706. useBlurExponentialShadowMap: true
  109707. }
  109708. }
  109709. }
  109710. };
  109711. /***/ }),
  109712. /* 48 */
  109713. /***/ (function(module, exports, __webpack_require__) {
  109714. "use strict";
  109715. Object.defineProperty(exports, "__esModule", { value: true });
  109716. exports.environmentMapConfiguration = {
  109717. lab: {
  109718. assetsRootURL: '/assets/environment/',
  109719. environmentMap: {
  109720. texture: 'EnvMap_2.0-256.env',
  109721. rotationY: 0,
  109722. tintLevel: 0.4
  109723. }
  109724. }
  109725. };
  109726. /***/ }),
  109727. /* 49 */
  109728. /***/ (function(module, exports, __webpack_require__) {
  109729. "use strict";
  109730. Object.defineProperty(exports, "__esModule", { value: true });
  109731. var telemetryLoaderPlugin_1 = __webpack_require__(50);
  109732. var msftLodLoaderPlugin_1 = __webpack_require__(51);
  109733. var extendedMaterialLoaderPlugin_1 = __webpack_require__(52);
  109734. var pluginCache = {};
  109735. function getLoaderPluginByName(name) {
  109736. if (!pluginCache[name]) {
  109737. switch (name) {
  109738. case 'telemetry':
  109739. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  109740. break;
  109741. case 'msftLod':
  109742. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109743. break;
  109744. case 'applyMaterialConfig':
  109745. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  109746. break;
  109747. case 'extendedMaterial':
  109748. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  109749. break;
  109750. }
  109751. }
  109752. return pluginCache[name];
  109753. }
  109754. exports.getLoaderPluginByName = getLoaderPluginByName;
  109755. /***/ }),
  109756. /* 50 */
  109757. /***/ (function(module, exports, __webpack_require__) {
  109758. "use strict";
  109759. Object.defineProperty(exports, "__esModule", { value: true });
  109760. var telemetryManager_1 = __webpack_require__(5);
  109761. var babylonjs_1 = __webpack_require__(0);
  109762. var TelemetryLoaderPlugin = /** @class */ (function () {
  109763. function TelemetryLoaderPlugin() {
  109764. }
  109765. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  109766. this._model = model;
  109767. this._loadStart = babylonjs_1.Tools.Now;
  109768. };
  109769. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  109770. telemetryManager_1.telemetryManager.broadcast("Load First LOD Complete", model.getViewer(), {
  109771. model: model,
  109772. loadTime: babylonjs_1.Tools.Now - this._loadStart
  109773. });
  109774. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109775. };
  109776. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  109777. this._loadEnd = babylonjs_1.Tools.Now;
  109778. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewer(), {
  109779. model: this._model,
  109780. loadTime: this._loadEnd - this._loadStart
  109781. });
  109782. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109783. };
  109784. TelemetryLoaderPlugin.prototype.onComplete = function () {
  109785. this._loadEnd = babylonjs_1.Tools.Now;
  109786. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewer(), {
  109787. model: this._model,
  109788. loadTime: this._loadEnd - this._loadStart
  109789. });
  109790. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.getViewer());
  109791. };
  109792. return TelemetryLoaderPlugin;
  109793. }());
  109794. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  109795. /***/ }),
  109796. /* 51 */
  109797. /***/ (function(module, exports, __webpack_require__) {
  109798. "use strict";
  109799. Object.defineProperty(exports, "__esModule", { value: true });
  109800. var MSFTLodLoaderPlugin = /** @class */ (function () {
  109801. function MSFTLodLoaderPlugin() {
  109802. }
  109803. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  109804. this._model = model;
  109805. };
  109806. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  109807. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  109808. var MSFT_lod = extension;
  109809. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  109810. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  109811. }
  109812. };
  109813. return MSFTLodLoaderPlugin;
  109814. }());
  109815. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  109816. /***/ }),
  109817. /* 52 */
  109818. /***/ (function(module, exports, __webpack_require__) {
  109819. "use strict";
  109820. Object.defineProperty(exports, "__esModule", { value: true });
  109821. var babylonjs_1 = __webpack_require__(0);
  109822. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  109823. function ExtendedMaterialLoaderPlugin() {
  109824. }
  109825. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  109826. var material = baseMaterial;
  109827. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  109828. };
  109829. return ExtendedMaterialLoaderPlugin;
  109830. }());
  109831. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  109832. /***/ }),
  109833. /* 53 */
  109834. /***/ (function(module, exports, __webpack_require__) {
  109835. /*!
  109836. * PEP v0.4.3 | https://github.com/jquery/PEP
  109837. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  109838. */
  109839. !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);
  109840. // define inherited MouseEvent properties
  109841. // skip bubbles and cancelable since they're set above in initEvent()
  109842. for(var d,e=2;e<m.length;e++)d=m[e],c[d]=b[d]||n[e];c.buttons=b.buttons||0;
  109843. // Spec requires that pointers without pressure specified use 0.5 for down
  109844. // state and 0 for up state.
  109845. var f=0;
  109846. // add x/y properties aliased to clientX/Y
  109847. // define the properties of the PointerEvent interface
  109848. 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(){
  109849. // only activate if this platform does not have pointer events
  109850. 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}})}/**
  109851. * This is the constructor for new PointerEvents.
  109852. *
  109853. * New Pointer Events must be given a type, and an optional dictionary of
  109854. * initialization properties.
  109855. *
  109856. * Due to certain platform requirements, events returned from the constructor
  109857. * identify as MouseEvents.
  109858. *
  109859. * @constructor
  109860. * @param {String} inType The type of the event to create.
  109861. * @param {Object} [inDict] An optional dictionary of initial event properties.
  109862. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  109863. */
  109864. 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},
  109865. // return value, key, map
  109866. forEach:function(a,b){return this.array.forEach(function(c,d){a.call(b,c,d,this)},this)}};var q=[
  109867. // MouseEvent
  109868. "bubbles","cancelable","view","detail","screenX","screenY","clientX","clientY","ctrlKey","altKey","shiftKey","metaKey","button","relatedTarget",
  109869. // DOM Level 3
  109870. "buttons",
  109871. // PointerEvent
  109872. "pointerId","width","height","pressure","tiltX","tiltY","pointerType","hwTimestamp","isPrimary",
  109873. // event instance
  109874. "type","target","currentTarget","which","pageX","pageY","timeStamp"],r=[
  109875. // MouseEvent
  109876. !1,!1,null,null,0,0,0,0,!1,!1,!1,!1,0,null,
  109877. // DOM Level 3
  109878. 0,
  109879. // PointerEvent
  109880. 0,0,0,0,0,0,"",0,!1,
  109881. // event instance
  109882. "",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),
  109883. // Scope objects for native events.
  109884. // This exists for ease of testing.
  109885. eventSources:Object.create(null),eventSourceList:[],/**
  109886. * Add a new event source that will generate pointer events.
  109887. *
  109888. * `inSource` must contain an array of event names named `events`, and
  109889. * functions with the names specified in the `events` array.
  109890. * @param {string} name A name for the event source
  109891. * @param {Object} source A new source of platform events.
  109892. */
  109893. 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++)
  109894. // call eventsource register
  109895. b.register.call(b,a)},unregister:function(a){for(var b,c=this.eventSourceList.length,d=0;d<c&&(b=this.eventSourceList[d]);d++)
  109896. // call eventsource register
  109897. b.unregister.call(b,a)},contains:/*scope.external.contains || */function(a,b){try{return a.contains(b)}catch(c){
  109898. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  109899. return!1}},
  109900. // EVENTS
  109901. 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)},
  109902. // LISTENER LOGIC
  109903. eventHandler:function(a){
  109904. // This is used to prevent multiple dispatch of pointerevents from
  109905. // platform events. This can happen when two elements in different scopes
  109906. // are set up to create pointer events, which is relevant to Shadow DOM.
  109907. if(!a._handledByPE){var b=a.type,c=this.eventMap&&this.eventMap[b];c&&c(a),a._handledByPE=!0}},
  109908. // set up event listeners
  109909. listen:function(a,b){b.forEach(function(b){this.addEvent(a,b)},this)},
  109910. // remove event listeners
  109911. 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)},
  109912. // EVENT CREATION AND TRACKING
  109913. /**
  109914. * Creates a new Event of type `inType`, based on the information in
  109915. * `inEvent`.
  109916. *
  109917. * @param {string} inType A string representing the type of event to create
  109918. * @param {Event} inEvent A platform event with a target
  109919. * @return {Event} A PointerEvent of type `inType`
  109920. */
  109921. makeEvent:function(b,c){
  109922. // relatedTarget must be null if pointer is captured
  109923. 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},
  109924. // make and dispatch an event in one call
  109925. fireEvent:function(a,b){var c=this.makeEvent(a,b);return this.dispatchEvent(c)},/**
  109926. * Returns a snapshot of inEvent, with writable properties.
  109927. *
  109928. * @param {Event} inEvent An event that contains properties to copy.
  109929. * @return {Object} An object containing shallow copies of `inEvent`'s
  109930. * properties.
  109931. */
  109932. 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],
  109933. // Work around SVGInstanceElement shadow tree
  109934. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  109935. // This is the behavior implemented by Firefox.
  109936. !t||"target"!==b&&"relatedTarget"!==b||c[b]instanceof SVGElementInstance&&(c[b]=c[b].correspondingUseElement);
  109937. // keep the semantics of preventDefault
  109938. 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){
  109939. // Order of conditions due to document.contains() missing in IE.
  109940. for(var d=a.target,e=[];d!==document&&!d.contains(a.relatedTarget);)
  109941. // Touch: Do not propagate if node is detached.
  109942. 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)}},/**
  109943. * Dispatches the event to its target.
  109944. *
  109945. * @param {Event} inEvent The event to be dispatched.
  109946. * @return {Boolean} True if an event handler returns true, false otherwise.
  109947. */
  109948. 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(
  109949. // is element a shadow host?
  109950. e=this.targetingShadow(f);e;){if(
  109951. // find the the element inside the shadow root
  109952. d=e.elementFromPoint(b,c)){
  109953. // shadowed element may contain a shadow root
  109954. var g=this.targetingShadow(d);return this.searchRoot(g,b,c)||d}
  109955. // check for older shadows
  109956. e=this.olderShadow(e)}
  109957. // light dom element is the target
  109958. return f}},owner:function(a){
  109959. // walk up until you hit the shadow root or document
  109960. for(var b=a;b.parentNode;)b=b.parentNode;
  109961. // the owner element is expected to be a Document or ShadowRoot
  109962. 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);
  109963. // if x, y is not in this root, fall back to document search
  109964. 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){
  109965. // Only watch scopes that can target find, as these are top-level.
  109966. // Otherwise we can see duplicate additions and removals that add noise.
  109967. //
  109968. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  109969. // a removal without an insertion when a node is redistributed among
  109970. // shadows. Since it all ends up correct in the document, watching only
  109971. // the document will yield the correct mutations to watch.
  109972. 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))},
  109973. // register all touch-action = none nodes on document load
  109974. 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){
  109975. // find children with touch-action
  109976. var b=x(a,this.findElements,this);
  109977. // flatten the list
  109978. // make sure the added nodes are accounted for
  109979. 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){}
  109980. // handler block for native mouse events
  109981. 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:[],
  109982. // collide with the global mouse listener
  109983. 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++){
  109984. // simulated mouse events will be swallowed near a primary touchend
  109985. 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);
  109986. // Update buttons state after possible out-of-document mouseup.
  109987. 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];
  109988. // Produces wrong state of buttons in Browsers without `buttons` support
  109989. // when a mouse button that was pressed outside the document is released
  109990. // inside and other buttons are still pressed down.
  109991. c.buttons=b?b.buttons&~d:0,a.buttons=c.buttons}H.set(this.POINTER_ID,a),
  109992. // Support: Firefox <=44 only
  109993. // FF Ubuntu includes the lifted button in the `buttons` property on
  109994. // mouseup.
  109995. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  109996. 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),
  109997. // set touch-action on shadows as well
  109998. 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),
  109999. // remove touch-action from shadow
  110000. 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);
  110001. // simply update scrollType if listeners are already established
  110002. 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){
  110003. // set primary touch if there no pointers, or the only pointer is the mouse
  110004. (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,
  110005. // forward modifier keys
  110006. c.altKey=b.altKey,c.ctrlKey=b.ctrlKey,c.metaKey=b.metaKey,c.shiftKey=b.shiftKey;
  110007. // forward touch preventDefaults
  110008. 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))},
  110009. // For single axis scrollers, determines whether the element should emit
  110010. // pointer events or behave as a scroller
  110011. shouldScroll:function(a){if(this.firstXY){var b,c=a.currentTarget._scrollType;if("none"===c)
  110012. // this element is a touch-action: none, should never scroll
  110013. b=!1;else if("XY"===c)
  110014. // this element should always scroll
  110015. 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]);
  110016. // if delta in the scroll axis > delta other axis, scroll instead of
  110017. // making events
  110018. 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},
  110019. // In some instances, a touchstart can happen without a touchend. This
  110020. // leaves the pointermap in a broken state.
  110021. // Therefore, on every touchstart, we remove the touches that did not fire a
  110022. // touchend event.
  110023. // To keep state globally consistent, we fire a
  110024. // pointercancel for this "abandoned" touch
  110025. vacuumTouches:function(a){var b=a.touches;
  110026. // pointermap.size should be < tl.length here, as the touchstart has not
  110027. // been processed yet.
  110028. if(R.size>=b.length){var c=[];R.forEach(function(a,d){
  110029. // Never remove pointerId == 1, which is mouse.
  110030. // Touch identifiers are 2 smaller than their pointerId, which is the
  110031. // index in pointermap.
  110032. 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);
  110033. // a finger drifted off the screen, ignore it
  110034. if(c){var d=c.out,e=c.outTarget;u.move(b),d&&e!==b.target&&(d.relatedTarget=b.target,b.relatedTarget=e,
  110035. // recover from retargeting by shadow
  110036. d.target=e,b.target?(u.leaveOut(d),u.enterOver(b)):(
  110037. // clean up case when finger leaves the screen
  110038. 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)},
  110039. // prevent synth mouse events from creating pointer events
  110040. dedupSynthMouse:function(a){var b=N.lastTouches,c=a.changedTouches[0];
  110041. // only the primary finger will synth mouse events
  110042. if(this.isPrimaryTouch(c)){
  110043. // remember x/y of last touch
  110044. 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});
  110045. /***/ }),
  110046. /* 54 */
  110047. /***/ (function(module, exports, __webpack_require__) {
  110048. "use strict";
  110049. Object.defineProperty(exports, "__esModule", { value: true });
  110050. var defaultViewer_1 = __webpack_require__(9);
  110051. var mappers_1 = __webpack_require__(3);
  110052. var _1 = __webpack_require__(6);
  110053. /**
  110054. * Will attach an init function the the DOMContentLoaded event.
  110055. * The init function will be removed automatically after the event was triggered.
  110056. */
  110057. function initListeners() {
  110058. document.addEventListener("DOMContentLoaded", init);
  110059. function init(event) {
  110060. document.removeEventListener("DOMContentLoaded", init);
  110061. if (_1.viewerGlobals.disableInit || _1.disableInit)
  110062. return;
  110063. InitTags();
  110064. }
  110065. }
  110066. exports.initListeners = initListeners;
  110067. /**
  110068. * Select all HTML tags on the page that match the selector and initialize a viewer
  110069. *
  110070. * @param selector the selector to initialize the viewer on (default is 'babylon')
  110071. */
  110072. function InitTags(selector) {
  110073. if (selector === void 0) { selector = 'babylon'; }
  110074. var elements = document.querySelectorAll(selector);
  110075. for (var i = 0; i < elements.length; ++i) {
  110076. var element = elements.item(i);
  110077. // get the html configuration
  110078. var configMapper = mappers_1.mapperManager.getMapper('dom');
  110079. var config = configMapper.map(element);
  110080. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  110081. }
  110082. }
  110083. exports.InitTags = InitTags;
  110084. /***/ })
  110085. /******/ ]);
  110086. return BabylonViewer;
  110087. });